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,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/ArrayBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#pragma warning disable CA1825 // Avoid zero-length array allocations.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class ArrayBuilder<T>
{
private static readonly ObjectPool<ArrayBuilder<T>> s_poolInstance = new ObjectPool<ArrayBuilder<T>>(() => new ArrayBuilder<T>(), 16);
private static readonly ReadOnlyCollection<T> s_empty = new ReadOnlyCollection<T>(new T[0]);
private readonly List<T> _items;
public static ArrayBuilder<T> GetInstance(int size = 0)
{
var builder = s_poolInstance.Allocate();
Debug.Assert(builder.Count == 0);
if (size > 0)
{
builder._items.Capacity = size;
}
return builder;
}
internal ArrayBuilder()
{
_items = new List<T>();
}
public int Count
{
get { return _items.Count; }
}
public void Add(T item)
{
_items.Add(item);
}
public void AddRange(T[] items)
{
foreach (var item in items)
{
_items.Add(item);
}
}
public void AddRange(IEnumerable<T> items)
{
_items.AddRange(items);
}
public T Peek()
{
return _items[_items.Count - 1];
}
public void Push(T item)
{
Add(item);
}
public T Pop()
{
var position = _items.Count - 1;
var result = _items[position];
_items.RemoveAt(position);
return result;
}
public void Clear()
{
_items.Clear();
}
public void Free()
{
_items.Clear();
s_poolInstance.Free(this);
}
public T[] ToArray()
{
return _items.ToArray();
}
public T[] ToArrayAndFree()
{
var result = this.ToArray();
this.Free();
return result;
}
public ReadOnlyCollection<T> ToImmutable()
{
return (_items.Count > 0) ? new ReadOnlyCollection<T>(_items.ToArray()) : s_empty;
}
public ReadOnlyCollection<T> ToImmutableAndFree()
{
var result = this.ToImmutable();
this.Free();
return result;
}
public T this[int i]
{
get { return _items[i]; }
}
public void Sort(IComparer<T> comparer)
{
_items.Sort(comparer);
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#pragma warning disable CA1825 // Avoid zero-length array allocations.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class ArrayBuilder<T>
{
private static readonly ObjectPool<ArrayBuilder<T>> s_poolInstance = new ObjectPool<ArrayBuilder<T>>(() => new ArrayBuilder<T>(), 16);
private static readonly ReadOnlyCollection<T> s_empty = new ReadOnlyCollection<T>(new T[0]);
private readonly List<T> _items;
public static ArrayBuilder<T> GetInstance(int size = 0)
{
var builder = s_poolInstance.Allocate();
Debug.Assert(builder.Count == 0);
if (size > 0)
{
builder._items.Capacity = size;
}
return builder;
}
internal ArrayBuilder()
{
_items = new List<T>();
}
public int Count
{
get { return _items.Count; }
}
public void Add(T item)
{
_items.Add(item);
}
public void AddRange(T[] items)
{
foreach (var item in items)
{
_items.Add(item);
}
}
public void AddRange(IEnumerable<T> items)
{
_items.AddRange(items);
}
public T Peek()
{
return _items[_items.Count - 1];
}
public void Push(T item)
{
Add(item);
}
public T Pop()
{
var position = _items.Count - 1;
var result = _items[position];
_items.RemoveAt(position);
return result;
}
public void Clear()
{
_items.Clear();
}
public void Free()
{
_items.Clear();
s_poolInstance.Free(this);
}
public T[] ToArray()
{
return _items.ToArray();
}
public T[] ToArrayAndFree()
{
var result = this.ToArray();
this.Free();
return result;
}
public ReadOnlyCollection<T> ToImmutable()
{
return (_items.Count > 0) ? new ReadOnlyCollection<T>(_items.ToArray()) : s_empty;
}
public ReadOnlyCollection<T> ToImmutableAndFree()
{
var result = this.ToImmutable();
this.Free();
return result;
}
public T this[int i]
{
get { return _items[i]; }
}
public void Sort(IComparer<T> comparer)
{
_items.Sort(comparer);
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void SuppressNullableWarningOperation()
{
var comp = CreateCompilation(@"
class C
{
#nullable enable
void M(string? x)
/*<bind>*/{
x!.ToString();
}/*</bind>*/
}");
var expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
Arguments(0)";
var diagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics);
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)";
VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void SuppressNullableWarningOperation_ConstantValue()
{
var comp = CreateCompilation(@"
class C
{
#nullable enable
void M()
/*<bind>*/{
((string)null)!.ToString();
}/*</bind>*/
}");
var expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '((string)nu ... ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '((string)nu ... .ToString()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Arguments(0)";
var diagnostics = new[]
{
// (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type.
// ((string)null)!.ToString();
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(7, 10)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void SuppressNullableWarningOperation_NestedFlow()
{
var comp = CreateCompilation(@"
class C
{
#nullable enable
void M(bool b, string? x, string? y)
/*<bind>*/{
(b ? x : y)!.ToString();
}/*</bind>*/
}");
comp.VerifyDiagnostics();
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'x')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(b ? x : y)!.ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '(b ? x : y)!.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b ? x : y')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)";
VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void RefReassignmentExpressions()
{
var comp = CreateCompilation(@"
class C
{
ref readonly int M(ref int rx)
{
ref int ry = ref rx;
rx = ref ry;
ry = ref """".Length == 0
? ref (rx = ref ry)
: ref (ry = ref rx);
return ref (ry = ref rx);
}
}");
comp.VerifyDiagnostics();
var m = comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<BlockSyntax>().Single();
comp.VerifyOperationTree(m, expectedOperationTree: @"
IBlockOperation (4 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 ry
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'ref int ry = ref rx;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref int ry = ref rx')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 ry) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ry = ref rx')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref rx')
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'rx = ref ry;')
Expression:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry')
Left:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
Right:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ry = ref """" ... = ref rx);')
Expression:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref """" ... y = ref rx)')
Left:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
Right:
IConditionalOperation (IsRef) (OperationKind.Conditional, Type: System.Int32) (Syntax: '"""".Length = ... y = ref rx)')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: '"""".Length == 0')
Left:
IPropertyReferenceOperation: System.Int32 System.String.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '"""".Length')
Instance Receiver:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
WhenTrue:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry')
Left:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
Right:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
WhenFalse:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx')
Left:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
Right:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return ref ... = ref rx);')
ReturnedValue:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx')
Left:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
Right:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')");
}
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
[Fact]
public void IOperationRefFor()
{
var tree = CSharpSyntaxTree.ParseText(@"
using System;
class C
{
public class LinkedList
{
public int Value;
public LinkedList Next;
}
public void M(LinkedList list)
{
for (ref readonly var cur = ref list; cur != null; cur = ref cur.Next)
{
Console.WriteLine(cur.Value);
}
}
}", options: TestOptions.Regular);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics();
var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
comp.VerifyOperationTree(m, @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (ref re ... }')
Locals: Local_1: C.LinkedList cur
Condition:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'cur != null')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'cur')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Before:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'ref readonl ... = ref list')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref readonl ... = ref list')
Declarators:
IVariableDeclaratorOperation (Symbol: C.LinkedList cur) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'cur = ref list')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref list')
IParameterReferenceOperation: list (OperationKind.ParameterReference, Type: C.LinkedList) (Syntax: 'list')
Initializer:
null
AtLoopBottom:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'cur = ref cur.Next')
Expression:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: C.LinkedList) (Syntax: 'cur = ref cur.Next')
Left:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
Right:
IFieldReferenceOperation: C.LinkedList C.LinkedList.Next (OperationKind.FieldReference, Type: C.LinkedList) (Syntax: 'cur.Next')
Instance Receiver:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... cur.Value);')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (cur.Value)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'cur.Value')
IFieldReferenceOperation: System.Int32 C.LinkedList.Value (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'cur.Value')
Instance Receiver:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)");
var op = (IForLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForStatementSyntax>().Single());
Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind);
}
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
[Fact]
public void IOperationRefForeach()
{
var tree = CSharpSyntaxTree.ParseText(@"
using System;
class C
{
public void M(RefEnumerable re)
{
foreach (ref readonly var x in re)
{
Console.WriteLine(x);
}
}
}
class RefEnumerable
{
private readonly int[] _arr = new int[5];
public StructEnum GetEnumerator() => new StructEnum(_arr);
public struct StructEnum
{
private readonly int[] _arr;
private int _current;
public StructEnum(int[] arr)
{
_arr = arr;
_current = -1;
}
public ref int Current => ref _arr[_current];
public bool MoveNext() => ++_current != _arr.Length;
}
}", options: TestOptions.Regular);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics();
var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
comp.VerifyOperationTree(m, @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'foreach (re ... }')
Locals: Local_1: System.Int32 x
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: RefEnumerable, IsImplicit) (Syntax: 're')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: re (OperationKind.ParameterReference, Type: RefEnumerable) (Syntax: 're')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x);')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)");
var op = (IForEachLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single());
Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(382240, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=382240")]
public void NullInPlaceOfParamArray()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(null);
Test2(new object(), null);
}
static void Test1(params int[] x)
{
}
static void Test2(int y, params int[] x)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,15): error CS1503: Argument 1: cannot convert from 'object' to 'int'
// Test2(new object(), null);
Diagnostic(ErrorCode.ERR_BadArgType, "new object()").WithArguments("1", "object", "int").WithLocation(7, 15)
);
var tree = compilation.SyntaxTrees.Single();
var nodes = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray();
compilation.VerifyOperationTree(nodes[0], expectedOperationTree:
@"IInvocationOperation (void Cls.Test1(params System.Int32[] x)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test1(null)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[], Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
compilation.VerifyOperationTree(nodes[1], expectedOperationTree:
@"IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'Test2(new o ... ct(), null)')
Children(2):
IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()')
Arguments(0)
Initializer:
null
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructionAssignmentFromTuple()
{
var text = @"
public class C
{
public static void M()
{
int x, y, z;
(x, y, z) = (1, 2, 3);
(x, y, z) = new C();
var (a, b) = (1, 2);
}
public void Deconstruct(out int a, out int b, out int c)
{
a = b = c = 1;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef });
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var assignments = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().ToArray();
Assert.Equal("(x, y, z) = (1, 2, 3)", assignments[0].ToString());
IOperation operation1 = model.GetOperation(assignments[0]);
Assert.NotNull(operation1);
Assert.Equal(OperationKind.DeconstructionAssignment, operation1.Kind);
Assert.False(operation1 is ISimpleAssignmentOperation);
Assert.Equal("(x, y, z) = new C()", assignments[1].ToString());
IOperation operation2 = model.GetOperation(assignments[1]);
Assert.NotNull(operation2);
Assert.Equal(OperationKind.DeconstructionAssignment, operation2.Kind);
Assert.False(operation2 is ISimpleAssignmentOperation);
Assert.Equal("var (a, b) = (1, 2)", assignments[2].ToString());
IOperation operation3 = model.GetOperation(assignments[2]);
Assert.NotNull(operation3);
Assert.Equal(OperationKind.DeconstructionAssignment, operation3.Kind);
Assert.False(operation3 is ISimpleAssignmentOperation);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/45687")]
public void TestClone()
{
var sourceCode = TestResource.AllInOneCSharpCode;
var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs");
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
VerifyClone(model);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(22964, "https://github.com/dotnet/roslyn/issues/22964")]
[Fact]
public void GlobalStatement_Parent()
{
var source =
@"
System.Console.WriteLine();
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var statement = tree.GetRoot().DescendantNodes().OfType<StatementSyntax>().Single();
var model = compilation.GetSemanticModel(tree);
var operation = model.GetOperation(statement);
Assert.Equal(OperationKind.ExpressionStatement, operation.Kind);
Assert.Null(operation.Parent);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestParentOperations()
{
var sourceCode = TestResource.AllInOneCSharpCode;
var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs");
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
VerifyParentOperations(model);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(23001, "https://github.com/dotnet/roslyn/issues/23001")]
[Fact]
public void TestGetOperationForQualifiedName()
{
var text = @"using System;
public class Test
{
class A
{
public B b;
}
class B
{
}
void M(A a)
{
int x2 = /*<bind>*/a.b/*</bind>*/;
}
}
";
var comp = CreateCompilation(text);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
// Verify we return non-null operation only for topmost member access expression.
var expr = (MemberAccessExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree));
Assert.Equal("a.b", expr.ToString());
var operation = model.GetOperation(expr);
Assert.NotNull(operation);
Assert.Equal(OperationKind.FieldReference, operation.Kind);
var fieldOperation = (IFieldReferenceOperation)operation;
Assert.Equal("b", fieldOperation.Field.Name);
// Verify we return null operation for child nodes of member access expression.
Assert.Null(model.GetOperation(expr.Name));
}
[Fact]
public void TestSemanticModelOnOperationAncestors()
{
var compilation = CreateCompilation(@"
class C
{
void M(bool flag)
{
if (flag)
{
int y = 1000;
}
}
}
");
var tree = compilation.SyntaxTrees[0];
var root = tree.GetCompilationUnitRoot();
var literal = root.DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
var methodDeclSyntax = literal.Ancestors().OfType<MethodDeclarationSyntax>().Single();
var model = compilation.GetSemanticModel(tree);
IOperation operation = model.GetOperation(literal);
VerifyRootAndModelForOperationAncestors(operation, model, expectedRootOperationKind: OperationKind.MethodBody, expectedRootSyntax: methodDeclSyntax);
}
[Fact]
public void TestGetOperationOnSpeculativeSemanticModel()
{
var compilation = CreateCompilation(@"
class C
{
void M(int x)
{
int y = 1000;
}
}
");
var speculatedBlock = (BlockSyntax)SyntaxFactory.ParseStatement(@"
{
int z = 0;
}
");
var tree = compilation.SyntaxTrees[0];
var root = tree.GetCompilationUnitRoot();
var typeDecl = (TypeDeclarationSyntax)root.Members[0];
var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
var model = compilation.GetSemanticModel(tree);
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, speculatedBlock, out speculativeModel);
Assert.True(success);
Assert.NotNull(speculativeModel);
var localDecl = (LocalDeclarationStatementSyntax)speculatedBlock.Statements[0];
IOperation operation = speculativeModel.GetOperation(localDecl);
VerifyRootAndModelForOperationAncestors(operation, speculativeModel, expectedRootOperationKind: OperationKind.Block, expectedRootSyntax: speculatedBlock);
speculativeModel.VerifyOperationTree(localDecl, expectedOperationTree: @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int z = 0;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int z = 0')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 z) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'z = 0')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Initializer:
null
");
}
[Fact, WorkItem(26649, "https://github.com/dotnet/roslyn/issues/26649")]
public void IncrementalBindingReusesBlock()
{
var source = @"
class C
{
void M()
{
try
{
}
catch (Exception e)
{
throw new Exception();
}
}
}";
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(syntaxTree);
// We want to get the IOperation for the { throw new Exception(); } first, and then for the containing catch block, to
// force the semantic model to bind the inner first. It should reuse that inner block when binding the outer catch.
var catchBlock = syntaxTree.GetRoot().DescendantNodes().OfType<CatchClauseSyntax>().Single();
var exceptionBlock = catchBlock.Block;
var blockOperation = semanticModel.GetOperation(exceptionBlock);
var catchOperation = (ICatchClauseOperation)semanticModel.GetOperation(catchBlock);
Assert.Same(blockOperation, catchOperation.Handler);
}
private static void VerifyRootAndModelForOperationAncestors(
IOperation operation,
SemanticModel model,
OperationKind expectedRootOperationKind,
SyntaxNode expectedRootSyntax)
{
SemanticModel memberModel = ((Operation)operation).OwningSemanticModel;
while (true)
{
Assert.Same(model, operation.SemanticModel);
Assert.Same(memberModel, ((Operation)operation).OwningSemanticModel);
if (operation.Parent == null)
{
Assert.Equal(expectedRootOperationKind, operation.Kind);
Assert.Same(expectedRootSyntax, operation.Syntax);
break;
}
operation = operation.Parent;
}
}
[Fact, WorkItem(45955, "https://github.com/dotnet/roslyn/issues/45955")]
public void SemanticModelFieldInitializerRace()
{
var source = $@"
#nullable enable
public class C
{{
// Use a big initializer to increase the odds of hitting the race
public static object o = null;
public string s = {string.Join(" + ", Enumerable.Repeat("(string)o", 1000))};
}}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var fieldInitializer = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last().Value;
for (int i = 0; i < 5; i++)
{
// We had a race condition where the first attempt to access a field initializer could cause an assert to be hit,
// and potentially more work to be done than was necessary. So we kick off a parallel task to attempt to
// get info on a bunch of different threads at the same time and reproduce the issue.
var model = comp.GetSemanticModel(tree);
const int nTasks = 10;
Enumerable.Range(0, nTasks).AsParallel()
.ForAll(_ => Assert.Equal("System.String System.String.op_Addition(System.String left, System.String right)", model.GetSymbolInfo(fieldInitializer).Symbol.ToTestDisplayString(includeNonNullable: 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.IOperation)]
public class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void SuppressNullableWarningOperation()
{
var comp = CreateCompilation(@"
class C
{
#nullable enable
void M(string? x)
/*<bind>*/{
x!.ToString();
}/*</bind>*/
}");
var expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
Arguments(0)";
var diagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics);
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x!.ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x!.ToString()')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)";
VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void SuppressNullableWarningOperation_ConstantValue()
{
var comp = CreateCompilation(@"
class C
{
#nullable enable
void M()
/*<bind>*/{
((string)null)!.ToString();
}/*</bind>*/
}");
var expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '((string)nu ... ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '((string)nu ... .ToString()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Arguments(0)";
var diagnostics = new[]
{
// (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type.
// ((string)null)!.ToString();
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(7, 10)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, expectedOperationTree, diagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void SuppressNullableWarningOperation_NestedFlow()
{
var comp = CreateCompilation(@"
class C
{
#nullable enable
void M(bool b, string? x, string? y)
/*<bind>*/{
(b ? x : y)!.ToString();
}/*</bind>*/
}");
comp.VerifyDiagnostics();
var expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'x')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String?) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(b ? x : y)!.ToString();')
Expression:
IInvocationOperation (virtual System.String System.String.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '(b ? x : y)!.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'b ? x : y')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)";
VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.RefLocalsReturns)]
[Fact]
public void RefReassignmentExpressions()
{
var comp = CreateCompilation(@"
class C
{
ref readonly int M(ref int rx)
{
ref int ry = ref rx;
rx = ref ry;
ry = ref """".Length == 0
? ref (rx = ref ry)
: ref (ry = ref rx);
return ref (ry = ref rx);
}
}");
comp.VerifyDiagnostics();
var m = comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<BlockSyntax>().Single();
comp.VerifyOperationTree(m, expectedOperationTree: @"
IBlockOperation (4 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 ry
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'ref int ry = ref rx;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref int ry = ref rx')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 ry) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'ry = ref rx')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref rx')
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'rx = ref ry;')
Expression:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry')
Left:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
Right:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ry = ref """" ... = ref rx);')
Expression:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref """" ... y = ref rx)')
Left:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
Right:
IConditionalOperation (IsRef) (OperationKind.Conditional, Type: System.Int32) (Syntax: '"""".Length = ... y = ref rx)')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: '"""".Length == 0')
Left:
IPropertyReferenceOperation: System.Int32 System.String.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: '"""".Length')
Instance Receiver:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
WhenTrue:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'rx = ref ry')
Left:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
Right:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
WhenFalse:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx')
Left:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
Right:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return ref ... = ref rx);')
ReturnedValue:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'ry = ref rx')
Left:
ILocalReferenceOperation: ry (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'ry')
Right:
IParameterReferenceOperation: rx (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'rx')");
}
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
[Fact]
public void IOperationRefFor()
{
var tree = CSharpSyntaxTree.ParseText(@"
using System;
class C
{
public class LinkedList
{
public int Value;
public LinkedList Next;
}
public void M(LinkedList list)
{
for (ref readonly var cur = ref list; cur != null; cur = ref cur.Next)
{
Console.WriteLine(cur.Value);
}
}
}", options: TestOptions.Regular);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics();
var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
comp.VerifyOperationTree(m, @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (ref re ... }')
Locals: Local_1: C.LinkedList cur
Condition:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'cur != null')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'cur')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Before:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'ref readonl ... = ref list')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'ref readonl ... = ref list')
Declarators:
IVariableDeclaratorOperation (Symbol: C.LinkedList cur) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'cur = ref list')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ref list')
IParameterReferenceOperation: list (OperationKind.ParameterReference, Type: C.LinkedList) (Syntax: 'list')
Initializer:
null
AtLoopBottom:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'cur = ref cur.Next')
Expression:
ISimpleAssignmentOperation (IsRef) (OperationKind.SimpleAssignment, Type: C.LinkedList) (Syntax: 'cur = ref cur.Next')
Left:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
Right:
IFieldReferenceOperation: C.LinkedList C.LinkedList.Next (OperationKind.FieldReference, Type: C.LinkedList) (Syntax: 'cur.Next')
Instance Receiver:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... cur.Value);')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (cur.Value)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'cur.Value')
IFieldReferenceOperation: System.Int32 C.LinkedList.Value (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'cur.Value')
Instance Receiver:
ILocalReferenceOperation: cur (OperationKind.LocalReference, Type: C.LinkedList) (Syntax: 'cur')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)");
var op = (IForLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForStatementSyntax>().Single());
Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind);
}
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
[Fact]
public void IOperationRefForeach()
{
var tree = CSharpSyntaxTree.ParseText(@"
using System;
class C
{
public void M(RefEnumerable re)
{
foreach (ref readonly var x in re)
{
Console.WriteLine(x);
}
}
}
class RefEnumerable
{
private readonly int[] _arr = new int[5];
public StructEnum GetEnumerator() => new StructEnum(_arr);
public struct StructEnum
{
private readonly int[] _arr;
private int _current;
public StructEnum(int[] arr)
{
_arr = arr;
_current = -1;
}
public ref int Current => ref _arr[_current];
public bool MoveNext() => ++_current != _arr.Length;
}
}", options: TestOptions.Regular);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics();
var m = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
comp.VerifyOperationTree(m, @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'foreach (re ... }')
Locals: Local_1: System.Int32 x
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: RefEnumerable, IsImplicit) (Syntax: 're')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: re (OperationKind.ParameterReference, Type: RefEnumerable) (Syntax: 're')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x);')
Expression:
IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)");
var op = (IForEachLoopOperation)comp.GetSemanticModel(tree).GetOperation(tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single());
Assert.Equal(RefKind.RefReadOnly, op.Locals.Single().RefKind);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(382240, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=382240")]
public void NullInPlaceOfParamArray()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(null);
Test2(new object(), null);
}
static void Test1(params int[] x)
{
}
static void Test2(int y, params int[] x)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,15): error CS1503: Argument 1: cannot convert from 'object' to 'int'
// Test2(new object(), null);
Diagnostic(ErrorCode.ERR_BadArgType, "new object()").WithArguments("1", "object", "int").WithLocation(7, 15)
);
var tree = compilation.SyntaxTrees.Single();
var nodes = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray();
compilation.VerifyOperationTree(nodes[0], expectedOperationTree:
@"IInvocationOperation (void Cls.Test1(params System.Int32[] x)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Test1(null)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'null')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[], Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
compilation.VerifyOperationTree(nodes[1], expectedOperationTree:
@"IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'Test2(new o ... ct(), null)')
Children(2):
IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()')
Arguments(0)
Initializer:
null
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructionAssignmentFromTuple()
{
var text = @"
public class C
{
public static void M()
{
int x, y, z;
(x, y, z) = (1, 2, 3);
(x, y, z) = new C();
var (a, b) = (1, 2);
}
public void Deconstruct(out int a, out int b, out int c)
{
a = b = c = 1;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef });
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var assignments = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().ToArray();
Assert.Equal("(x, y, z) = (1, 2, 3)", assignments[0].ToString());
IOperation operation1 = model.GetOperation(assignments[0]);
Assert.NotNull(operation1);
Assert.Equal(OperationKind.DeconstructionAssignment, operation1.Kind);
Assert.False(operation1 is ISimpleAssignmentOperation);
Assert.Equal("(x, y, z) = new C()", assignments[1].ToString());
IOperation operation2 = model.GetOperation(assignments[1]);
Assert.NotNull(operation2);
Assert.Equal(OperationKind.DeconstructionAssignment, operation2.Kind);
Assert.False(operation2 is ISimpleAssignmentOperation);
Assert.Equal("var (a, b) = (1, 2)", assignments[2].ToString());
IOperation operation3 = model.GetOperation(assignments[2]);
Assert.NotNull(operation3);
Assert.Equal(OperationKind.DeconstructionAssignment, operation3.Kind);
Assert.False(operation3 is ISimpleAssignmentOperation);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/45687")]
public void TestClone()
{
var sourceCode = TestResource.AllInOneCSharpCode;
var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs");
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
VerifyClone(model);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(22964, "https://github.com/dotnet/roslyn/issues/22964")]
[Fact]
public void GlobalStatement_Parent()
{
var source =
@"
System.Console.WriteLine();
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var statement = tree.GetRoot().DescendantNodes().OfType<StatementSyntax>().Single();
var model = compilation.GetSemanticModel(tree);
var operation = model.GetOperation(statement);
Assert.Equal(OperationKind.ExpressionStatement, operation.Kind);
Assert.Null(operation.Parent);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestParentOperations()
{
var sourceCode = TestResource.AllInOneCSharpCode;
var compilation = CreateCompilationWithMscorlib40(sourceCode, new[] { SystemRef, SystemCoreRef, ValueTupleRef, SystemRuntimeFacadeRef }, sourceFileName: "file.cs");
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
VerifyParentOperations(model);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(23001, "https://github.com/dotnet/roslyn/issues/23001")]
[Fact]
public void TestGetOperationForQualifiedName()
{
var text = @"using System;
public class Test
{
class A
{
public B b;
}
class B
{
}
void M(A a)
{
int x2 = /*<bind>*/a.b/*</bind>*/;
}
}
";
var comp = CreateCompilation(text);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
// Verify we return non-null operation only for topmost member access expression.
var expr = (MemberAccessExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree));
Assert.Equal("a.b", expr.ToString());
var operation = model.GetOperation(expr);
Assert.NotNull(operation);
Assert.Equal(OperationKind.FieldReference, operation.Kind);
var fieldOperation = (IFieldReferenceOperation)operation;
Assert.Equal("b", fieldOperation.Field.Name);
// Verify we return null operation for child nodes of member access expression.
Assert.Null(model.GetOperation(expr.Name));
}
[Fact]
public void TestSemanticModelOnOperationAncestors()
{
var compilation = CreateCompilation(@"
class C
{
void M(bool flag)
{
if (flag)
{
int y = 1000;
}
}
}
");
var tree = compilation.SyntaxTrees[0];
var root = tree.GetCompilationUnitRoot();
var literal = root.DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
var methodDeclSyntax = literal.Ancestors().OfType<MethodDeclarationSyntax>().Single();
var model = compilation.GetSemanticModel(tree);
IOperation operation = model.GetOperation(literal);
VerifyRootAndModelForOperationAncestors(operation, model, expectedRootOperationKind: OperationKind.MethodBody, expectedRootSyntax: methodDeclSyntax);
}
[Fact]
public void TestGetOperationOnSpeculativeSemanticModel()
{
var compilation = CreateCompilation(@"
class C
{
void M(int x)
{
int y = 1000;
}
}
");
var speculatedBlock = (BlockSyntax)SyntaxFactory.ParseStatement(@"
{
int z = 0;
}
");
var tree = compilation.SyntaxTrees[0];
var root = tree.GetCompilationUnitRoot();
var typeDecl = (TypeDeclarationSyntax)root.Members[0];
var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
var model = compilation.GetSemanticModel(tree);
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, speculatedBlock, out speculativeModel);
Assert.True(success);
Assert.NotNull(speculativeModel);
var localDecl = (LocalDeclarationStatementSyntax)speculatedBlock.Statements[0];
IOperation operation = speculativeModel.GetOperation(localDecl);
VerifyRootAndModelForOperationAncestors(operation, speculativeModel, expectedRootOperationKind: OperationKind.Block, expectedRootSyntax: speculatedBlock);
speculativeModel.VerifyOperationTree(localDecl, expectedOperationTree: @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int z = 0;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int z = 0')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 z) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'z = 0')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Initializer:
null
");
}
[Fact, WorkItem(26649, "https://github.com/dotnet/roslyn/issues/26649")]
public void IncrementalBindingReusesBlock()
{
var source = @"
class C
{
void M()
{
try
{
}
catch (Exception e)
{
throw new Exception();
}
}
}";
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(syntaxTree);
// We want to get the IOperation for the { throw new Exception(); } first, and then for the containing catch block, to
// force the semantic model to bind the inner first. It should reuse that inner block when binding the outer catch.
var catchBlock = syntaxTree.GetRoot().DescendantNodes().OfType<CatchClauseSyntax>().Single();
var exceptionBlock = catchBlock.Block;
var blockOperation = semanticModel.GetOperation(exceptionBlock);
var catchOperation = (ICatchClauseOperation)semanticModel.GetOperation(catchBlock);
Assert.Same(blockOperation, catchOperation.Handler);
}
private static void VerifyRootAndModelForOperationAncestors(
IOperation operation,
SemanticModel model,
OperationKind expectedRootOperationKind,
SyntaxNode expectedRootSyntax)
{
SemanticModel memberModel = ((Operation)operation).OwningSemanticModel;
while (true)
{
Assert.Same(model, operation.SemanticModel);
Assert.Same(memberModel, ((Operation)operation).OwningSemanticModel);
if (operation.Parent == null)
{
Assert.Equal(expectedRootOperationKind, operation.Kind);
Assert.Same(expectedRootSyntax, operation.Syntax);
break;
}
operation = operation.Parent;
}
}
[Fact, WorkItem(45955, "https://github.com/dotnet/roslyn/issues/45955")]
public void SemanticModelFieldInitializerRace()
{
var source = $@"
#nullable enable
public class C
{{
// Use a big initializer to increase the odds of hitting the race
public static object o = null;
public string s = {string.Join(" + ", Enumerable.Repeat("(string)o", 1000))};
}}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var fieldInitializer = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last().Value;
for (int i = 0; i < 5; i++)
{
// We had a race condition where the first attempt to access a field initializer could cause an assert to be hit,
// and potentially more work to be done than was necessary. So we kick off a parallel task to attempt to
// get info on a bunch of different threads at the same time and reproduce the issue.
var model = comp.GetSemanticModel(tree);
const int nTasks = 10;
Enumerable.Range(0, nTasks).AsParallel()
.ForAll(_ => Assert.Equal("System.String System.String.op_Addition(System.String left, System.String right)", model.GetSymbolInfo(fieldInitializer).Symbol.ToTestDisplayString(includeNonNullable: false)));
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/CSharpTest/Diagnostics/MockDiagnosticAnalyzerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MockDiagnosticAnalyzer
{
public partial class MockDiagnosticAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
private class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
public const string Id = "MockDiagnostic";
private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(_descriptor);
}
}
public override void Initialize(AnalysisContext context)
=> context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
=> context.RegisterCompilationEndAction(AnalyzeCompilation);
public void AnalyzeCompilation(CompilationAnalysisContext context)
{
}
}
public MockDiagnosticAnalyzerTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new MockDiagnosticAnalyzer(), null);
private async Task VerifyDiagnosticsAsync(
string source,
params DiagnosticDescription[] expectedDiagnostics)
{
using var workspace = TestWorkspace.CreateCSharp(source, composition: GetComposition());
var actualDiagnostics = await this.GetDiagnosticsAsync(workspace, new TestParameters());
actualDiagnostics.Verify(expectedDiagnostics);
}
[WorkItem(906919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/906919")]
[Fact]
public async Task Bug906919()
{
var source = "[|class C { }|]";
await VerifyDiagnosticsAsync(source);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MockDiagnosticAnalyzer
{
public partial class MockDiagnosticAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
private class MockDiagnosticAnalyzer : DiagnosticAnalyzer
{
public const string Id = "MockDiagnostic";
private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(_descriptor);
}
}
public override void Initialize(AnalysisContext context)
=> context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
=> context.RegisterCompilationEndAction(AnalyzeCompilation);
public void AnalyzeCompilation(CompilationAnalysisContext context)
{
}
}
public MockDiagnosticAnalyzerTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new MockDiagnosticAnalyzer(), null);
private async Task VerifyDiagnosticsAsync(
string source,
params DiagnosticDescription[] expectedDiagnostics)
{
using var workspace = TestWorkspace.CreateCSharp(source, composition: GetComposition());
var actualDiagnostics = await this.GetDiagnosticsAsync(workspace, new TestParameters());
actualDiagnostics.Verify(expectedDiagnostics);
}
[WorkItem(906919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/906919")]
[Fact]
public async Task Bug906919()
{
var source = "[|class C { }|]";
await VerifyDiagnosticsAsync(source);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_ProjectSerialization.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.SQLite.v2.Interop;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
using static SQLitePersistentStorageConstants;
internal partial class SQLitePersistentStorage
{
protected override Task<bool> ChecksumMatchesAsync(ProjectKey projectKey, Project? project, string name, Checksum checksum, CancellationToken cancellationToken)
=> _projectAccessor.ChecksumMatchesAsync((projectKey, name), checksum, cancellationToken);
protected override Task<Stream?> ReadStreamAsync(ProjectKey projectKey, Project? project, string name, Checksum? checksum, CancellationToken cancellationToken)
=> _projectAccessor.ReadStreamAsync((projectKey, name), checksum, cancellationToken);
protected override Task<bool> WriteStreamAsync(ProjectKey projectKey, Project? project, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken)
=> _projectAccessor.WriteStreamAsync((projectKey, name), stream, checksum, cancellationToken);
/// <summary>
/// <see cref="Accessor{TKey, TWriteQueueKey, TDatabaseId}"/> responsible for storing and
/// retrieving data from <see cref="ProjectDataTableName"/>.
/// </summary>
private class ProjectAccessor : Accessor<
(ProjectKey projectKey, string name),
(ProjectId projectId, string name),
long>
{
public ProjectAccessor(SQLitePersistentStorage storage) : base(storage)
{
}
protected override Table Table => Table.Project;
protected override (ProjectId projectId, string name) GetWriteQueueKey((ProjectKey projectKey, string name) key)
=> (key.projectKey.Id, key.name);
protected override bool TryGetDatabaseId(SqlConnection connection, (ProjectKey projectKey, string name) key, bool allowWrite, out long dataId)
=> Storage.TryGetProjectDataId(connection, key.projectKey, key.name, allowWrite, out dataId);
protected override void BindFirstParameter(SqlStatement statement, long dataId)
=> statement.BindInt64Parameter(parameterIndex: 1, value: dataId);
protected override bool TryGetRowId(SqlConnection connection, Database database, long dataId, out long rowId)
=> GetAndVerifyRowId(connection, database, dataId, out rowId);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.SQLite.v2.Interop;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
using static SQLitePersistentStorageConstants;
internal partial class SQLitePersistentStorage
{
protected override Task<bool> ChecksumMatchesAsync(ProjectKey projectKey, Project? project, string name, Checksum checksum, CancellationToken cancellationToken)
=> _projectAccessor.ChecksumMatchesAsync((projectKey, name), checksum, cancellationToken);
protected override Task<Stream?> ReadStreamAsync(ProjectKey projectKey, Project? project, string name, Checksum? checksum, CancellationToken cancellationToken)
=> _projectAccessor.ReadStreamAsync((projectKey, name), checksum, cancellationToken);
protected override Task<bool> WriteStreamAsync(ProjectKey projectKey, Project? project, string name, Stream stream, Checksum? checksum, CancellationToken cancellationToken)
=> _projectAccessor.WriteStreamAsync((projectKey, name), stream, checksum, cancellationToken);
/// <summary>
/// <see cref="Accessor{TKey, TWriteQueueKey, TDatabaseId}"/> responsible for storing and
/// retrieving data from <see cref="ProjectDataTableName"/>.
/// </summary>
private class ProjectAccessor : Accessor<
(ProjectKey projectKey, string name),
(ProjectId projectId, string name),
long>
{
public ProjectAccessor(SQLitePersistentStorage storage) : base(storage)
{
}
protected override Table Table => Table.Project;
protected override (ProjectId projectId, string name) GetWriteQueueKey((ProjectKey projectKey, string name) key)
=> (key.projectKey.Id, key.name);
protected override bool TryGetDatabaseId(SqlConnection connection, (ProjectKey projectKey, string name) key, bool allowWrite, out long dataId)
=> Storage.TryGetProjectDataId(connection, key.projectKey, key.name, allowWrite, out dataId);
protected override void BindFirstParameter(SqlStatement statement, long dataId)
=> statement.BindInt64Parameter(parameterIndex: 1, value: dataId);
protected override bool TryGetRowId(SqlConnection connection, Database database, long dataId, out long rowId)
=> GetAndVerifyRowId(connection, database, dataId, out rowId);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLiteConnectionPool.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.SQLite.v2.Interop;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
internal sealed partial class SQLiteConnectionPool : IDisposable
{
// We pool connections to the DB so that we don't have to take the hit of
// reconnecting. The connections also cache the prepared statements used
// to get/set data from the db. A connection is safe to use by one thread
// at a time, but is not safe for simultaneous use by multiple threads.
private readonly object _connectionGate = new();
private readonly Stack<SqlConnection> _connectionsPool = new();
private readonly CancellationTokenSource _shutdownTokenSource = new();
private readonly SQLiteConnectionPoolService _connectionPoolService;
private readonly IPersistentStorageFaultInjector? _faultInjector;
private readonly string _databasePath;
private readonly IDisposable _ownershipLock;
public SQLiteConnectionPool(SQLiteConnectionPoolService connectionPoolService, IPersistentStorageFaultInjector? faultInjector, string databasePath, IDisposable ownershipLock)
{
_connectionPoolService = connectionPoolService;
_faultInjector = faultInjector;
_databasePath = databasePath;
_ownershipLock = ownershipLock;
}
internal void Initialize(
Action<SqlConnection, CancellationToken> initializer,
CancellationToken cancellationToken)
{
// This is our startup path. No other code can be running. So it's safe for us to access a connection that
// can talk to the db without having to be on the reader/writer scheduler queue.
using var _ = GetPooledConnection(checkScheduler: false, out var connection);
initializer(connection, cancellationToken);
}
public void Dispose()
{
// Flush all pending writes so that all data our features wanted written
// are definitely persisted to the DB.
try
{
_shutdownTokenSource.Cancel();
CloseWorker();
}
finally
{
// let the lock go
_ownershipLock.Dispose();
}
}
private void CloseWorker()
{
lock (_connectionGate)
{
// Go through all our pooled connections and close them.
while (_connectionsPool.Count > 0)
{
var connection = _connectionsPool.Pop();
connection.Close_OnlyForUseBySQLiteConnectionPool();
}
}
}
/// <summary>
/// Gets a <see cref="SqlConnection"/> from the connection pool, or creates one if none are available.
/// </summary>
/// <remarks>
/// Database connections have a large amount of overhead, and should be returned to the pool when they are no
/// longer in use. In particular, make sure to avoid letting a connection lease cross an <see langword="await"/>
/// boundary, as it will prevent code in the asynchronous operation from using the existing connection.
/// </remarks>
internal PooledConnection GetPooledConnection(out SqlConnection connection)
=> GetPooledConnection(checkScheduler: true, out connection);
/// <summary>
/// <inheritdoc cref="GetPooledConnection(out SqlConnection)"/>
/// Only use this overload if it is safe to bypass the normal scheduler check. Only startup code (which runs
/// before any reads/writes/flushes happen) should use this.
/// </summary>
private PooledConnection GetPooledConnection(bool checkScheduler, out SqlConnection connection)
{
if (checkScheduler)
{
var scheduler = TaskScheduler.Current;
if (scheduler != _connectionPoolService.Scheduler.ConcurrentScheduler && scheduler != _connectionPoolService.Scheduler.ExclusiveScheduler)
throw new InvalidOperationException($"Cannot get a connection to the DB unless running on one of {nameof(SQLiteConnectionPoolService)}'s schedulers");
}
var result = new PooledConnection(this, GetConnection());
connection = result.Connection;
return result;
}
private SqlConnection GetConnection()
{
lock (_connectionGate)
{
// If we have an available connection, just return that.
if (_connectionsPool.Count > 0)
{
return _connectionsPool.Pop();
}
}
// Otherwise create a new connection.
return SqlConnection.Create(_faultInjector, _databasePath);
}
private void ReleaseConnection(SqlConnection connection)
{
lock (_connectionGate)
{
// If we've been asked to shutdown, then don't actually add the connection back to
// the pool. Instead, just close it as we no longer need it.
if (_shutdownTokenSource.IsCancellationRequested)
{
connection.Close_OnlyForUseBySQLiteConnectionPool();
return;
}
try
{
_connectionsPool.Push(connection);
}
catch
{
// An exception (likely OutOfMemoryException) occurred while returning the connection to the pool.
// The connection will be discarded, so make sure to close it so the finalizer doesn't crash the
// process later.
connection.Close_OnlyForUseBySQLiteConnectionPool();
throw;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.SQLite.v2.Interop;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
internal sealed partial class SQLiteConnectionPool : IDisposable
{
// We pool connections to the DB so that we don't have to take the hit of
// reconnecting. The connections also cache the prepared statements used
// to get/set data from the db. A connection is safe to use by one thread
// at a time, but is not safe for simultaneous use by multiple threads.
private readonly object _connectionGate = new();
private readonly Stack<SqlConnection> _connectionsPool = new();
private readonly CancellationTokenSource _shutdownTokenSource = new();
private readonly SQLiteConnectionPoolService _connectionPoolService;
private readonly IPersistentStorageFaultInjector? _faultInjector;
private readonly string _databasePath;
private readonly IDisposable _ownershipLock;
public SQLiteConnectionPool(SQLiteConnectionPoolService connectionPoolService, IPersistentStorageFaultInjector? faultInjector, string databasePath, IDisposable ownershipLock)
{
_connectionPoolService = connectionPoolService;
_faultInjector = faultInjector;
_databasePath = databasePath;
_ownershipLock = ownershipLock;
}
internal void Initialize(
Action<SqlConnection, CancellationToken> initializer,
CancellationToken cancellationToken)
{
// This is our startup path. No other code can be running. So it's safe for us to access a connection that
// can talk to the db without having to be on the reader/writer scheduler queue.
using var _ = GetPooledConnection(checkScheduler: false, out var connection);
initializer(connection, cancellationToken);
}
public void Dispose()
{
// Flush all pending writes so that all data our features wanted written
// are definitely persisted to the DB.
try
{
_shutdownTokenSource.Cancel();
CloseWorker();
}
finally
{
// let the lock go
_ownershipLock.Dispose();
}
}
private void CloseWorker()
{
lock (_connectionGate)
{
// Go through all our pooled connections and close them.
while (_connectionsPool.Count > 0)
{
var connection = _connectionsPool.Pop();
connection.Close_OnlyForUseBySQLiteConnectionPool();
}
}
}
/// <summary>
/// Gets a <see cref="SqlConnection"/> from the connection pool, or creates one if none are available.
/// </summary>
/// <remarks>
/// Database connections have a large amount of overhead, and should be returned to the pool when they are no
/// longer in use. In particular, make sure to avoid letting a connection lease cross an <see langword="await"/>
/// boundary, as it will prevent code in the asynchronous operation from using the existing connection.
/// </remarks>
internal PooledConnection GetPooledConnection(out SqlConnection connection)
=> GetPooledConnection(checkScheduler: true, out connection);
/// <summary>
/// <inheritdoc cref="GetPooledConnection(out SqlConnection)"/>
/// Only use this overload if it is safe to bypass the normal scheduler check. Only startup code (which runs
/// before any reads/writes/flushes happen) should use this.
/// </summary>
private PooledConnection GetPooledConnection(bool checkScheduler, out SqlConnection connection)
{
if (checkScheduler)
{
var scheduler = TaskScheduler.Current;
if (scheduler != _connectionPoolService.Scheduler.ConcurrentScheduler && scheduler != _connectionPoolService.Scheduler.ExclusiveScheduler)
throw new InvalidOperationException($"Cannot get a connection to the DB unless running on one of {nameof(SQLiteConnectionPoolService)}'s schedulers");
}
var result = new PooledConnection(this, GetConnection());
connection = result.Connection;
return result;
}
private SqlConnection GetConnection()
{
lock (_connectionGate)
{
// If we have an available connection, just return that.
if (_connectionsPool.Count > 0)
{
return _connectionsPool.Pop();
}
}
// Otherwise create a new connection.
return SqlConnection.Create(_faultInjector, _databasePath);
}
private void ReleaseConnection(SqlConnection connection)
{
lock (_connectionGate)
{
// If we've been asked to shutdown, then don't actually add the connection back to
// the pool. Instead, just close it as we no longer need it.
if (_shutdownTokenSource.IsCancellationRequested)
{
connection.Close_OnlyForUseBySQLiteConnectionPool();
return;
}
try
{
_connectionsPool.Push(connection);
}
catch
{
// An exception (likely OutOfMemoryException) occurred while returning the connection to the pool.
// The connection will be discarded, so make sure to close it so the finalizer doesn't crash the
// process later.
connection.Close_OnlyForUseBySQLiteConnectionPool();
throw;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/StaticLocalsTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.DiaSymReader
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class StaticLocalsTests
Inherits ExpressionCompilerTestBase
<Fact>
Public Sub StaticLocals()
Const source =
"Class C
Shared Function F(b As Boolean) As Object
If b Then
Static x As New C()
Return x
Else
Static y = 2
Return y
End If
End Function
Sub M()
Static x = Nothing
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
' Shared method.
Dim context = CreateMethodContext(runtime, "C.F")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(x, y)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 15 (0xf)
.maxstack 2
.locals init (Object V_0, //F
Boolean V_1,
Boolean V_2,
Boolean V_3)
IL_0000: ldsfld ""C.$STATIC$F$011C2$x As C""
IL_0005: dup
IL_0006: brtrue.s IL_000e
IL_0008: pop
IL_0009: ldsfld ""C.$STATIC$F$011C2$y As Object""
IL_000e: ret
}")
' Instance method.
context = CreateMethodContext(runtime, "C.M")
testData = New CompilationTestData()
context.CompileExpression("If(x, Me)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 12 (0xc)
.maxstack 2
.locals init (Boolean V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C.$STATIC$M$2001$x As Object""
IL_0006: dup
IL_0007: brtrue.s IL_000b
IL_0009: pop
IL_000a: ldarg.0
IL_000b: ret
}")
End Sub)
End Sub
<Fact>
Public Sub AssignStaticLocals()
Const source =
"Class C
Shared Sub M()
Static x = Nothing
Static y = 1
End Sub
Sub N()
Static z As New C()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
' Shared method.
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileAssignment("x", "y", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 16 (0x10)
.maxstack 1
.locals init (Boolean V_0,
Boolean V_1)
IL_0000: ldsfld ""C.$STATIC$M$001$y As Object""
IL_0005: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_000a: stsfld ""C.$STATIC$M$001$x As Object""
IL_000f: ret
}")
' Instance method.
context = CreateMethodContext(runtime, "C.N")
testData = New CompilationTestData()
context.CompileAssignment("z", "Nothing", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 8 (0x8)
.maxstack 2
.locals init (Boolean V_0)
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: stfld ""C.$STATIC$N$2001$z As C""
IL_0007: ret
}")
End Sub)
End Sub
''' <summary>
''' Static locals not exposed in the EE from lambdas.
''' This matches Dev12 EE behavior since there is no
''' map from the lambda to the containing method.
''' </summary>
<Fact>
Public Sub StaticLocalsReferenceInLambda()
Const source =
"Class C
Sub M(x As Object)
Static y As Object
Dim f = Function()
Return If(x, y)
End Function
f()
End Sub
Shared Sub M(x As Integer)
Static z As Integer
Dim f = Function()
Return x + z
End Function
f()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
' Instance method.
Dim context = CreateMethodContext(runtime, "C._Closure$__1-0._Lambda$__0")
Dim errorMessage As String = Nothing
context.CompileExpression("If(x, y)", errorMessage)
Assert.Equal(errorMessage, "error BC30451: 'y' is not declared. It may be inaccessible due to its protection level.")
' Shared method.
context = CreateMethodContext(runtime, "C._Closure$__2-0._Lambda$__0")
context.CompileExpression("x + z", errorMessage)
Assert.Equal(errorMessage, "error BC30451: 'z' is not declared. It may be inaccessible due to its protection level.")
End Sub)
End Sub
<Fact>
Public Sub GetLocals()
Const source =
"Class C
Shared Function F(b As Boolean) As Object
If b Then
Static x As New C()
Return x
Else
Static y As Integer = 2
Return y
End If
End Function
Shared Function F(i As Integer) As Object
Static x = 3
Return x
End Function
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
Dim moduleVersionId As Guid = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
GetContextState(runtime, "C.F(Boolean)", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
Dim context = CreateMethodContext(
New AppDomain(),
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
moduleVersionId,
methodToken,
methodVersion:=1,
ilOffset:=0,
localSignatureToken:=localSignatureToken,
kind:=MakeAssemblyReferencesKind.AllAssemblies)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "b")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "x", expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0, //F
Boolean V_1,
Boolean V_2,
Boolean V_3)
IL_0000: ldsfld ""C.$STATIC$F$011C2$x As C""
IL_0005: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0, //F
Boolean V_1,
Boolean V_2,
Boolean V_3)
IL_0000: ldsfld ""C.$STATIC$F$011C2$y As Integer""
IL_0005: ret
}")
locals.Free()
GetContextState(runtime, "C.F(Int32)", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
context = CreateMethodContext(
New AppDomain(),
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
moduleVersionId,
methodToken,
methodVersion:=1,
ilOffset:=0,
localSignatureToken:=localSignatureToken,
kind:=MakeAssemblyReferencesKind.AllAssemblies)
testData = New CompilationTestData()
locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "i")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "x", expectedILOpt:="
{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0, //F
Boolean V_1)
IL_0000: ldsfld ""C.$STATIC$F$011C8$x As Object""
IL_0005: ret
}
")
locals.Free()
End Sub)
End Sub
''' <summary>
''' Static locals not exposed in the EE from lambdas.
''' This matches Dev12 EE behavior since there is no
''' map from the lambda to the containing method.
''' </summary>
<Fact>
Public Sub GetLocalsInLambda()
Const source =
"Class C
Sub M(x As Object)
Static y As Object
Dim f = Function()
Return If(x, y)
End Function
f()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C._Closure$__1-0._Lambda$__0")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me")
VerifyLocal(testData, typeName, locals(1), "<>m1", "x")
locals.Free()
End Sub)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.DiaSymReader
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class StaticLocalsTests
Inherits ExpressionCompilerTestBase
<Fact>
Public Sub StaticLocals()
Const source =
"Class C
Shared Function F(b As Boolean) As Object
If b Then
Static x As New C()
Return x
Else
Static y = 2
Return y
End If
End Function
Sub M()
Static x = Nothing
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
' Shared method.
Dim context = CreateMethodContext(runtime, "C.F")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(x, y)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 15 (0xf)
.maxstack 2
.locals init (Object V_0, //F
Boolean V_1,
Boolean V_2,
Boolean V_3)
IL_0000: ldsfld ""C.$STATIC$F$011C2$x As C""
IL_0005: dup
IL_0006: brtrue.s IL_000e
IL_0008: pop
IL_0009: ldsfld ""C.$STATIC$F$011C2$y As Object""
IL_000e: ret
}")
' Instance method.
context = CreateMethodContext(runtime, "C.M")
testData = New CompilationTestData()
context.CompileExpression("If(x, Me)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 12 (0xc)
.maxstack 2
.locals init (Boolean V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C.$STATIC$M$2001$x As Object""
IL_0006: dup
IL_0007: brtrue.s IL_000b
IL_0009: pop
IL_000a: ldarg.0
IL_000b: ret
}")
End Sub)
End Sub
<Fact>
Public Sub AssignStaticLocals()
Const source =
"Class C
Shared Sub M()
Static x = Nothing
Static y = 1
End Sub
Sub N()
Static z As New C()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
' Shared method.
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileAssignment("x", "y", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 16 (0x10)
.maxstack 1
.locals init (Boolean V_0,
Boolean V_1)
IL_0000: ldsfld ""C.$STATIC$M$001$y As Object""
IL_0005: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object""
IL_000a: stsfld ""C.$STATIC$M$001$x As Object""
IL_000f: ret
}")
' Instance method.
context = CreateMethodContext(runtime, "C.N")
testData = New CompilationTestData()
context.CompileAssignment("z", "Nothing", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 8 (0x8)
.maxstack 2
.locals init (Boolean V_0)
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: stfld ""C.$STATIC$N$2001$z As C""
IL_0007: ret
}")
End Sub)
End Sub
''' <summary>
''' Static locals not exposed in the EE from lambdas.
''' This matches Dev12 EE behavior since there is no
''' map from the lambda to the containing method.
''' </summary>
<Fact>
Public Sub StaticLocalsReferenceInLambda()
Const source =
"Class C
Sub M(x As Object)
Static y As Object
Dim f = Function()
Return If(x, y)
End Function
f()
End Sub
Shared Sub M(x As Integer)
Static z As Integer
Dim f = Function()
Return x + z
End Function
f()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
' Instance method.
Dim context = CreateMethodContext(runtime, "C._Closure$__1-0._Lambda$__0")
Dim errorMessage As String = Nothing
context.CompileExpression("If(x, y)", errorMessage)
Assert.Equal(errorMessage, "error BC30451: 'y' is not declared. It may be inaccessible due to its protection level.")
' Shared method.
context = CreateMethodContext(runtime, "C._Closure$__2-0._Lambda$__0")
context.CompileExpression("x + z", errorMessage)
Assert.Equal(errorMessage, "error BC30451: 'z' is not declared. It may be inaccessible due to its protection level.")
End Sub)
End Sub
<Fact>
Public Sub GetLocals()
Const source =
"Class C
Shared Function F(b As Boolean) As Object
If b Then
Static x As New C()
Return x
Else
Static y As Integer = 2
Return y
End If
End Function
Shared Function F(i As Integer) As Object
Static x = 3
Return x
End Function
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
Dim moduleVersionId As Guid = Nothing
Dim symReader As ISymUnmanagedReader = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
GetContextState(runtime, "C.F(Boolean)", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
Dim context = CreateMethodContext(
New AppDomain(),
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
moduleVersionId,
methodToken,
methodVersion:=1,
ilOffset:=0,
localSignatureToken:=localSignatureToken,
kind:=MakeAssemblyReferencesKind.AllAssemblies)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "b")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "x", expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0, //F
Boolean V_1,
Boolean V_2,
Boolean V_3)
IL_0000: ldsfld ""C.$STATIC$F$011C2$x As C""
IL_0005: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0, //F
Boolean V_1,
Boolean V_2,
Boolean V_3)
IL_0000: ldsfld ""C.$STATIC$F$011C2$y As Integer""
IL_0005: ret
}")
locals.Free()
GetContextState(runtime, "C.F(Int32)", blocks, moduleVersionId, symReader, methodToken, localSignatureToken)
context = CreateMethodContext(
New AppDomain(),
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
moduleVersionId,
methodToken,
methodVersion:=1,
ilOffset:=0,
localSignatureToken:=localSignatureToken,
kind:=MakeAssemblyReferencesKind.AllAssemblies)
testData = New CompilationTestData()
locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "i")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "x", expectedILOpt:="
{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0, //F
Boolean V_1)
IL_0000: ldsfld ""C.$STATIC$F$011C8$x As Object""
IL_0005: ret
}
")
locals.Free()
End Sub)
End Sub
''' <summary>
''' Static locals not exposed in the EE from lambdas.
''' This matches Dev12 EE behavior since there is no
''' map from the lambda to the containing method.
''' </summary>
<Fact>
Public Sub GetLocalsInLambda()
Const source =
"Class C
Sub M(x As Object)
Static y As Object
Dim f = Function()
Return If(x, y)
End Function
f()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib40({source}, {MsvbRef}, options:=TestOptions.DebugDll)
WithRuntimeInstance(comp,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C._Closure$__1-0._Lambda$__0")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me")
VerifyLocal(testData, typeName, locals(1), "<>m1", "x")
locals.Free()
End Sub)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Symbols/Attributes/WellKnownAttributeData/MethodEarlyWellKnownAttributeData.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Information decoded from early well-known custom attributes applied on a method.
''' </summary>
Friend Class MethodEarlyWellKnownAttributeData
Inherits CommonMethodEarlyWellKnownAttributeData
#Region "ExtensionAttribute"
Private _isExtensionMethod As Boolean = False
Friend Property IsExtensionMethod As Boolean
Get
VerifySealed(expected:=True)
Return Me._isExtensionMethod
End Get
Set(value As Boolean)
VerifySealed(expected:=False)
Me._isExtensionMethod = value
SetDataStored()
End Set
End Property
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Information decoded from early well-known custom attributes applied on a method.
''' </summary>
Friend Class MethodEarlyWellKnownAttributeData
Inherits CommonMethodEarlyWellKnownAttributeData
#Region "ExtensionAttribute"
Private _isExtensionMethod As Boolean = False
Friend Property IsExtensionMethod As Boolean
Get
VerifySealed(expected:=True)
Return Me._isExtensionMethod
End Get
Set(value As Boolean)
VerifySealed(expected:=False)
Me._isExtensionMethod = value
SetDataStored()
End Set
End Property
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Tools/BuildBoss/ProjectReferenceEntry.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildBoss
{
internal struct ProjectReferenceEntry
{
internal string FileName { get; }
internal Guid? Project { get; }
internal ProjectKey ProjectKey => new ProjectKey(FileName);
internal ProjectReferenceEntry(string fileName, Guid? project)
{
FileName = fileName;
Project = project;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildBoss
{
internal struct ProjectReferenceEntry
{
internal string FileName { get; }
internal Guid? Project { get; }
internal ProjectKey ProjectKey => new ProjectKey(FileName);
internal ProjectReferenceEntry(string fileName, Guid? project)
{
FileName = fileName;
Project = project;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructTestingHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Imports Moq
Imports Roslyn.Test.EditorUtilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
Friend Module EndConstructTestingHelpers
Private Function CreateMockIndentationService() As ISmartIndentationService
Dim mock As New Mock(Of ISmartIndentationService)(MockBehavior.Strict)
mock.Setup(Function(service) service.GetDesiredIndentation(It.IsAny(Of ITextView), It.IsAny(Of ITextSnapshotLine))).Returns(0)
Return mock.Object
End Function
Private Sub DisableLineCommit(workspace As Workspace)
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False)))
End Sub
Private Sub VerifyTypedCharApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
before As String,
after As String,
typedChar As Char,
endCaretPos As Integer())
Dim caretPos = before.IndexOf("$$", StringComparison.Ordinal)
Dim beforeText = before.Replace("$$", "")
Using workspace = TestWorkspace.CreateVisualBasic(beforeText, composition:=EditorTestCompositions.EditorFeatures)
DisableLineCommit(workspace)
Dim view = workspace.Documents.First().GetTextView()
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, caretPos))
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
view.TextBuffer.Replace(New Span(caretPos, 0), typedChar.ToString())
Assert.True(doFunc(endConstructService, view, view.TextBuffer))
Assert.Equal(after, view.TextSnapshot.GetText())
Dim actualLine As Integer
Dim actualChar As Integer
view.Caret.Position.BufferPosition.GetLineAndCharacter(actualLine, actualChar)
Assert.Equal(endCaretPos(0), actualLine)
Assert.Equal(endCaretPos(1), actualChar)
End Using
End Sub
Private Sub VerifyApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
before As String,
beforeCaret As Integer(),
after As String,
afterCaret As Integer())
Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures)
DisableLineCommit(workspace)
Dim textView = workspace.Documents.First().GetTextView()
Dim subjectBuffer = workspace.Documents.First().GetTextBuffer()
textView.TryMoveCaretToAndEnsureVisible(GetSnapshotPointFromArray(textView, beforeCaret, beforeCaret.Length - 2))
If beforeCaret.Length = 4 Then
Dim span = New SnapshotSpan(
GetSnapshotPointFromArray(textView, beforeCaret, 0),
GetSnapshotPointFromArray(textView, beforeCaret, 2))
textView.SetSelection(span)
End If
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
Assert.True(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer))
Assert.Equal(EditorFactory.LinesToFullText(after), textView.TextSnapshot.GetText())
Dim afterLine = textView.TextSnapshot.GetLineFromLineNumber(afterCaret(0))
Dim afterCaretPoint As SnapshotPoint
If afterCaret(1) = -1 Then
afterCaretPoint = afterLine.End
Else
afterCaretPoint = New SnapshotPoint(textView.TextSnapshot, afterLine.Start + afterCaret(1))
End If
Assert.Equal(Of Integer)(afterCaretPoint, textView.GetCaretPoint(subjectBuffer).Value.Position)
End Using
End Sub
Private Function GetSnapshotPointFromArray(view As ITextView, caret As Integer(), startIndex As Integer) As SnapshotPoint
Dim line = view.TextSnapshot.GetLineFromLineNumber(caret(startIndex))
If caret(startIndex + 1) = -1 Then
Return line.End
Else
Return line.Start + caret(startIndex + 1)
End If
End Function
Private Sub VerifyNotApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
text As String,
caret As Integer())
Using workspace = TestWorkspace.CreateVisualBasic(text)
Dim textView = workspace.Documents.First().GetTextView()
Dim subjectBuffer = workspace.Documents.First().GetTextBuffer()
Dim line = textView.TextSnapshot.GetLineFromLineNumber(caret(0))
Dim caretPosition As SnapshotPoint
If caret(1) = -1 Then
caretPosition = line.End
Else
caretPosition = New SnapshotPoint(textView.TextSnapshot, line.Start + caret(1))
End If
textView.TryMoveCaretToAndEnsureVisible(caretPosition)
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
Assert.False(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer), "End Construct should not have generated anything.")
' The text should not have changed
Assert.Equal(EditorFactory.LinesToFullText(text), textView.TextSnapshot.GetText())
' The caret should not have moved
Assert.Equal(Of Integer)(caretPosition, textView.GetCaretPoint(subjectBuffer).Value.Position)
End Using
End Sub
Public Sub VerifyStatementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyStatementEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), text, caret)
End Sub
Public Sub VerifyXmlElementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlElementEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlCommentEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlCommentEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlCDataEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlCDataEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlEmbeddedExpressionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlEmbeddedExpressionEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlProcessingInstructionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlProcessingInstructionNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyEndConstructAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer())
VerifyTypedCharApplied(Function(s, v, b) s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos)
End Sub
Public Sub VerifyEndConstructNotAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer())
VerifyTypedCharApplied(Function(s, v, b) Not s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos)
End Sub
Public Sub VerifyAppliedAfterReturnUsingCommandHandler(
before As String,
beforeCaret As Integer(),
after As String,
afterCaret As Integer())
' create separate composition
Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures)
DisableLineCommit(workspace)
Dim view = workspace.Documents.First().GetTextView()
Dim line = view.TextSnapshot.GetLineFromLineNumber(beforeCaret(0))
If beforeCaret(1) = -1 Then
view.Caret.MoveTo(line.End)
Else
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, line.Start + beforeCaret(1)))
End If
Dim factory = workspace.ExportProvider.GetExportedValue(Of IEditorOperationsFactoryService)()
Dim endConstructor = New EndConstructCommandHandler(
factory,
workspace.ExportProvider.GetExportedValue(Of ITextUndoHistoryRegistry)())
Dim operations = factory.GetEditorOperations(view)
endConstructor.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(view, view.TextBuffer), Sub() operations.InsertNewLine(), TestCommandExecutionContext.Create())
Assert.Equal(after, view.TextSnapshot.GetText())
Dim afterLine = view.TextSnapshot.GetLineFromLineNumber(afterCaret(0))
Dim afterCaretPoint As Integer
If afterCaret(1) = -1 Then
afterCaretPoint = afterLine.End
Else
afterCaretPoint = afterLine.Start + afterCaret(1)
End If
Dim caretPosition = view.Caret.Position.VirtualBufferPosition
Assert.Equal(Of Integer)(afterCaretPoint, If(caretPosition.IsInVirtualSpace, caretPosition.Position + caretPosition.VirtualSpaces, caretPosition.Position))
End Using
End Sub
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Imports Moq
Imports Roslyn.Test.EditorUtilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
Friend Module EndConstructTestingHelpers
Private Function CreateMockIndentationService() As ISmartIndentationService
Dim mock As New Mock(Of ISmartIndentationService)(MockBehavior.Strict)
mock.Setup(Function(service) service.GetDesiredIndentation(It.IsAny(Of ITextView), It.IsAny(Of ITextSnapshotLine))).Returns(0)
Return mock.Object
End Function
Private Sub DisableLineCommit(workspace As Workspace)
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False)))
End Sub
Private Sub VerifyTypedCharApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
before As String,
after As String,
typedChar As Char,
endCaretPos As Integer())
Dim caretPos = before.IndexOf("$$", StringComparison.Ordinal)
Dim beforeText = before.Replace("$$", "")
Using workspace = TestWorkspace.CreateVisualBasic(beforeText, composition:=EditorTestCompositions.EditorFeatures)
DisableLineCommit(workspace)
Dim view = workspace.Documents.First().GetTextView()
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, caretPos))
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
view.TextBuffer.Replace(New Span(caretPos, 0), typedChar.ToString())
Assert.True(doFunc(endConstructService, view, view.TextBuffer))
Assert.Equal(after, view.TextSnapshot.GetText())
Dim actualLine As Integer
Dim actualChar As Integer
view.Caret.Position.BufferPosition.GetLineAndCharacter(actualLine, actualChar)
Assert.Equal(endCaretPos(0), actualLine)
Assert.Equal(endCaretPos(1), actualChar)
End Using
End Sub
Private Sub VerifyApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
before As String,
beforeCaret As Integer(),
after As String,
afterCaret As Integer())
Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures)
DisableLineCommit(workspace)
Dim textView = workspace.Documents.First().GetTextView()
Dim subjectBuffer = workspace.Documents.First().GetTextBuffer()
textView.TryMoveCaretToAndEnsureVisible(GetSnapshotPointFromArray(textView, beforeCaret, beforeCaret.Length - 2))
If beforeCaret.Length = 4 Then
Dim span = New SnapshotSpan(
GetSnapshotPointFromArray(textView, beforeCaret, 0),
GetSnapshotPointFromArray(textView, beforeCaret, 2))
textView.SetSelection(span)
End If
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
Assert.True(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer))
Assert.Equal(EditorFactory.LinesToFullText(after), textView.TextSnapshot.GetText())
Dim afterLine = textView.TextSnapshot.GetLineFromLineNumber(afterCaret(0))
Dim afterCaretPoint As SnapshotPoint
If afterCaret(1) = -1 Then
afterCaretPoint = afterLine.End
Else
afterCaretPoint = New SnapshotPoint(textView.TextSnapshot, afterLine.Start + afterCaret(1))
End If
Assert.Equal(Of Integer)(afterCaretPoint, textView.GetCaretPoint(subjectBuffer).Value.Position)
End Using
End Sub
Private Function GetSnapshotPointFromArray(view As ITextView, caret As Integer(), startIndex As Integer) As SnapshotPoint
Dim line = view.TextSnapshot.GetLineFromLineNumber(caret(startIndex))
If caret(startIndex + 1) = -1 Then
Return line.End
Else
Return line.Start + caret(startIndex + 1)
End If
End Function
Private Sub VerifyNotApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean),
text As String,
caret As Integer())
Using workspace = TestWorkspace.CreateVisualBasic(text)
Dim textView = workspace.Documents.First().GetTextView()
Dim subjectBuffer = workspace.Documents.First().GetTextBuffer()
Dim line = textView.TextSnapshot.GetLineFromLineNumber(caret(0))
Dim caretPosition As SnapshotPoint
If caret(1) = -1 Then
caretPosition = line.End
Else
caretPosition = New SnapshotPoint(textView.TextSnapshot, line.Start + caret(1))
End If
textView.TryMoveCaretToAndEnsureVisible(caretPosition)
Dim endConstructService As New VisualBasicEndConstructService(
CreateMockIndentationService(),
workspace.GetService(Of ITextUndoHistoryRegistry),
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of IEditorOptionsFactoryService))
Assert.False(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer), "End Construct should not have generated anything.")
' The text should not have changed
Assert.Equal(EditorFactory.LinesToFullText(text), textView.TextSnapshot.GetText())
' The caret should not have moved
Assert.Equal(Of Integer)(caretPosition, textView.GetCaretPoint(subjectBuffer).Value.Position)
End Using
End Sub
Public Sub VerifyStatementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyStatementEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), text, caret)
End Sub
Public Sub VerifyXmlElementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlElementEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlCommentEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlCommentEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlCDataEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlCDataEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlEmbeddedExpressionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlEmbeddedExpressionEndConstructNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyXmlProcessingInstructionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer())
VerifyApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret)
End Sub
Public Sub VerifyXmlProcessingInstructionNotApplied(text As String, caret As Integer())
VerifyNotApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), text, caret)
End Sub
Public Sub VerifyEndConstructAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer())
VerifyTypedCharApplied(Function(s, v, b) s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos)
End Sub
Public Sub VerifyEndConstructNotAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer())
VerifyTypedCharApplied(Function(s, v, b) Not s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos)
End Sub
Public Sub VerifyAppliedAfterReturnUsingCommandHandler(
before As String,
beforeCaret As Integer(),
after As String,
afterCaret As Integer())
' create separate composition
Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures)
DisableLineCommit(workspace)
Dim view = workspace.Documents.First().GetTextView()
Dim line = view.TextSnapshot.GetLineFromLineNumber(beforeCaret(0))
If beforeCaret(1) = -1 Then
view.Caret.MoveTo(line.End)
Else
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, line.Start + beforeCaret(1)))
End If
Dim factory = workspace.ExportProvider.GetExportedValue(Of IEditorOperationsFactoryService)()
Dim endConstructor = New EndConstructCommandHandler(
factory,
workspace.ExportProvider.GetExportedValue(Of ITextUndoHistoryRegistry)())
Dim operations = factory.GetEditorOperations(view)
endConstructor.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(view, view.TextBuffer), Sub() operations.InsertNewLine(), TestCommandExecutionContext.Create())
Assert.Equal(after, view.TextSnapshot.GetText())
Dim afterLine = view.TextSnapshot.GetLineFromLineNumber(afterCaret(0))
Dim afterCaretPoint As Integer
If afterCaret(1) = -1 Then
afterCaretPoint = afterLine.End
Else
afterCaretPoint = afterLine.Start + afterCaret(1)
End If
Dim caretPosition = view.Caret.Position.VirtualBufferPosition
Assert.Equal(Of Integer)(afterCaretPoint, If(caretPosition.IsInVirtualSpace, caretPosition.Position + caretPosition.VirtualSpaces, caretPosition.Position))
End Using
End Sub
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/EventBlockHighlighter.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class EventBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
Dim eventBlock = node.GetAncestor(Of EventBlockSyntax)()
If eventBlock Is Nothing Then
Return
End If
With eventBlock
With .EventStatement
' This span calculation should also capture the Custom keyword
Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword)
highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End))
If .ImplementsClause IsNot Nothing Then
highlights.Add(.ImplementsClause.ImplementsKeyword.Span)
End If
End With
highlights.Add(.EndEventStatement.Span)
End With
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class EventBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
Dim eventBlock = node.GetAncestor(Of EventBlockSyntax)()
If eventBlock Is Nothing Then
Return
End If
With eventBlock
With .EventStatement
' This span calculation should also capture the Custom keyword
Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword)
highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End))
If .ImplementsClause IsNot Nothing Then
highlights.Add(.ImplementsClause.ImplementsKeyword.Span)
End If
End With
highlights.Add(.EndEventStatement.Span)
End With
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/VisualBasic/Portable/FindSymbols/VisualBasicReferenceFinder.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.FindSymbols.Finders
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.FindSymbols
<ExportLanguageService(GetType(ILanguageServiceReferenceFinder), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicReferenceFinder
Implements ILanguageServiceReferenceFinder
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function DetermineCascadedSymbolsAsync(
symbol As ISymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol)) Implements ILanguageServiceReferenceFinder.DetermineCascadedSymbolsAsync
If symbol.Kind = SymbolKind.Property Then
Return DetermineCascadedSymbolsAsync(DirectCast(symbol, IPropertySymbol), project, cancellationToken)
ElseIf symbol.Kind = SymbolKind.NamedType Then
Return DetermineCascadedSymbolsAsync(DirectCast(symbol, INamedTypeSymbol), project, cancellationToken)
Else
Return SpecializedTasks.EmptyImmutableArray(Of ISymbol)
End If
End Function
Private Shared Async Function DetermineCascadedSymbolsAsync(
[property] As IPropertySymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol))
Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
Dim relatedSymbol = [property].FindRelatedExplicitlyDeclaredSymbol(compilation)
Return If([property].Equals(relatedSymbol),
ImmutableArray(Of ISymbol).Empty,
ImmutableArray.Create(relatedSymbol))
End Function
Private Shared Async Function DetermineCascadedSymbolsAsync(
namedType As INamedTypeSymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol))
Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
' If this is a WinForms project, then the VB 'my' feature may have synthesized
' a property that would return an instance of the main Form type for the project.
' Search for such properties and cascade to them as well.
Dim matchingMyPropertySymbols =
From childNamespace In compilation.RootNamespace.GetNamespaceMembers()
Where childNamespace.IsMyNamespace(compilation)
From type In childNamespace.GetAllTypes(cancellationToken)
Where type.Name = "MyForms"
From childProperty In type.GetMembers().OfType(Of IPropertySymbol)
Where childProperty.IsImplicitlyDeclared AndAlso childProperty.Type.Equals(namedType)
Select DirectCast(childProperty, ISymbol)
Return matchingMyPropertySymbols.Distinct().ToImmutableArray()
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.FindSymbols.Finders
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.FindSymbols
<ExportLanguageService(GetType(ILanguageServiceReferenceFinder), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicReferenceFinder
Implements ILanguageServiceReferenceFinder
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function DetermineCascadedSymbolsAsync(
symbol As ISymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol)) Implements ILanguageServiceReferenceFinder.DetermineCascadedSymbolsAsync
If symbol.Kind = SymbolKind.Property Then
Return DetermineCascadedSymbolsAsync(DirectCast(symbol, IPropertySymbol), project, cancellationToken)
ElseIf symbol.Kind = SymbolKind.NamedType Then
Return DetermineCascadedSymbolsAsync(DirectCast(symbol, INamedTypeSymbol), project, cancellationToken)
Else
Return SpecializedTasks.EmptyImmutableArray(Of ISymbol)
End If
End Function
Private Shared Async Function DetermineCascadedSymbolsAsync(
[property] As IPropertySymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol))
Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
Dim relatedSymbol = [property].FindRelatedExplicitlyDeclaredSymbol(compilation)
Return If([property].Equals(relatedSymbol),
ImmutableArray(Of ISymbol).Empty,
ImmutableArray.Create(relatedSymbol))
End Function
Private Shared Async Function DetermineCascadedSymbolsAsync(
namedType As INamedTypeSymbol,
project As Project,
cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol))
Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
' If this is a WinForms project, then the VB 'my' feature may have synthesized
' a property that would return an instance of the main Form type for the project.
' Search for such properties and cascade to them as well.
Dim matchingMyPropertySymbols =
From childNamespace In compilation.RootNamespace.GetNamespaceMembers()
Where childNamespace.IsMyNamespace(compilation)
From type In childNamespace.GetAllTypes(cancellationToken)
Where type.Name = "MyForms"
From childProperty In type.GetMembers().OfType(Of IPropertySymbol)
Where childProperty.IsImplicitlyDeclared AndAlso childProperty.Type.Equals(namedType)
Select DirectCast(childProperty, ISymbol)
Return matchingMyPropertySymbols.Distinct().ToImmutableArray()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/FindUsages/IFindUsagesContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
internal interface IFindUsagesContext
{
/// <summary>
/// Used for clients that are finding usages to push information about how far along they
/// are in their search.
/// </summary>
IStreamingProgressTracker ProgressTracker { get; }
/// <summary>
/// Report a message to be displayed to the user.
/// </summary>
ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken);
/// <summary>
/// Set the title of the window that results are displayed in.
/// </summary>
ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken);
ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken);
ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
internal interface IFindUsagesContext
{
/// <summary>
/// Used for clients that are finding usages to push information about how far along they
/// are in their search.
/// </summary>
IStreamingProgressTracker ProgressTracker { get; }
/// <summary>
/// Report a message to be displayed to the user.
/// </summary>
ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken);
/// <summary>
/// Set the title of the window that results are displayed in.
/// </summary>
ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken);
ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken);
ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageStrings.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.ColorSchemes
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Friend Module AdvancedOptionPageStrings
Public ReadOnly Property Option_AutomaticInsertionOfInterfaceAndMustOverrideMembers As String
Get
Return BasicVSResources.Automatic_insertion_of_Interface_and_MustOverride_members
End Get
End Property
Public ReadOnly Property Option_Analysis As String =
ServicesVSResources.Analysis
Public ReadOnly Property Option_Background_analysis_scope As String =
ServicesVSResources.Background_analysis_scope_colon
Public ReadOnly Property Option_Background_Analysis_Scope_Active_File As String =
ServicesVSResources.Current_document
Public ReadOnly Property Option_Background_Analysis_Scope_Open_Files_And_Projects As String =
ServicesVSResources.Open_documents
Public ReadOnly Property Option_Background_Analysis_Scope_Full_Solution As String =
ServicesVSResources.Entire_solution
Public ReadOnly Property Option_run_code_analysis_in_separate_process As String =
ServicesVSResources.Run_code_analysis_in_separate_process_requires_restart
Public ReadOnly Property Option_DisplayLineSeparators As String =
BasicVSResources.Show_procedure_line_separators
Public ReadOnly Property Option_Underline_reassigned_variables As String =
ServicesVSResources.Underline_reassigned_variables
Public ReadOnly Property Option_Display_all_hints_while_pressing_Alt_F1 As String =
ServicesVSResources.Display_all_hints_while_pressing_Alt_F1
Public ReadOnly Property Option_Color_hints As String =
ServicesVSResources.Color_hints
Public ReadOnly Property Option_Inline_Hints As String =
ServicesVSResources.Inline_Hints
Public ReadOnly Property Option_Display_inline_parameter_name_hints As String =
ServicesVSResources.Display_inline_parameter_name_hints
Public ReadOnly Property Option_Show_hints_for_literals As String =
ServicesVSResources.Show_hints_for_literals
Public ReadOnly Property Option_Show_hints_for_New_expressions As String =
BasicVSResources.Show_hints_for_New_expressions
Public ReadOnly Property Option_Show_hints_for_everything_else As String =
ServicesVSResources.Show_hints_for_everything_else
Public ReadOnly Property Option_Show_hints_for_indexers As String =
ServicesVSResources.Show_hints_for_indexers
Public ReadOnly Property Option_Suppress_hints_when_parameter_name_matches_the_method_s_intent As String =
ServicesVSResources.Suppress_hints_when_parameter_name_matches_the_method_s_intent
Public ReadOnly Property Option_Suppress_hints_when_parameter_names_differ_only_by_suffix As String =
ServicesVSResources.Suppress_hints_when_parameter_names_differ_only_by_suffix
Public ReadOnly Property Option_DontPutOutOrRefOnStruct As String =
BasicVSResources.Don_t_put_ByRef_on_custom_structure
Public ReadOnly Property Option_EditorHelp As String =
BasicVSResources.Editor_Help
Public ReadOnly Property Option_EnableEndConstruct As String =
BasicVSResources.A_utomatic_insertion_of_end_constructs
Public ReadOnly Property Option_EnableHighlightKeywords As String =
BasicVSResources.Highlight_related_keywords_under_cursor
Public ReadOnly Property Option_EnableHighlightReferences As String =
BasicVSResources.Highlight_references_to_symbol_under_cursor
Public ReadOnly Property Option_Quick_Actions As String =
ServicesVSResources.Quick_Actions
Public ReadOnly Property Option_Compute_Quick_Actions_asynchronously_experimental As String =
ServicesVSResources.Compute_Quick_Actions_asynchronously_experimental
Public ReadOnly Property Option_EnableLineCommit As String
Get
Return BasicVSResources.Pretty_listing_reformatting_of_code
End Get
End Property
Public ReadOnly Property Option_EnableOutlining As String
Get
Return BasicVSResources.Enter_outlining_mode_when_files_open
End Get
End Property
Public ReadOnly Property Option_ExtractMethod As String
Get
Return BasicVSResources.Extract_Method
End Get
End Property
Public ReadOnly Property Option_Implement_Interface_or_Abstract_Class As String =
ServicesVSResources.Implement_Interface_or_Abstract_Class
Public ReadOnly Property Option_When_inserting_properties_events_and_methods_place_them As String =
ServicesVSResources.When_inserting_properties_events_and_methods_place_them
Public ReadOnly Property Option_with_other_members_of_the_same_kind As String =
ServicesVSResources.with_other_members_of_the_same_kind
Public ReadOnly Property Option_When_generating_properties As String =
ServicesVSResources.When_generating_properties
Public ReadOnly Property Option_prefer_auto_properties As String =
ServicesVSResources.codegen_prefer_auto_properties
Public ReadOnly Property Option_prefer_throwing_properties As String =
ServicesVSResources.prefer_throwing_properties
Public ReadOnly Property Option_at_the_end As String =
ServicesVSResources.at_the_end
Public ReadOnly Property Option_GenerateXmlDocCommentsForTripleApostrophes As String =
BasicVSResources.Generate_XML_documentation_comments_for
Public ReadOnly Property Option_InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments As String =
BasicVSResources.Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments
Public ReadOnly Property Option_ShowRemarksInQuickInfo As String
Get
Return BasicVSResources.Show_remarks_in_Quick_Info
End Get
End Property
Public ReadOnly Property Option_GoToDefinition As String
Get
Return BasicVSResources.Go_to_Definition
End Get
End Property
Public ReadOnly Property Option_Highlighting As String
Get
Return BasicVSResources.Highlighting
End Get
End Property
Public ReadOnly Property Option_NavigateToObjectBrowser As String
Get
Return BasicVSResources.Navigate_to_Object_Browser_for_symbols_defined_in_metadata
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize As String
Get
Return BasicVSResources.Optimize_for_solution_size
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Small As String
Get
Return BasicVSResources.Small
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Regular As String
Get
Return BasicVSResources.Regular
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Large As String
Get
Return BasicVSResources.Large
End Get
End Property
Public ReadOnly Property Option_Outlining As String = ServicesVSResources.Outlining
Public ReadOnly Property Option_Show_outlining_for_declaration_level_constructs As String =
ServicesVSResources.Show_outlining_for_declaration_level_constructs
Public ReadOnly Property Option_Show_outlining_for_code_level_constructs As String =
ServicesVSResources.Show_outlining_for_code_level_constructs
Public ReadOnly Property Option_Show_outlining_for_comments_and_preprocessor_regions As String =
ServicesVSResources.Show_outlining_for_comments_and_preprocessor_regions
Public ReadOnly Property Option_Collapse_regions_when_collapsing_to_definitions As String =
ServicesVSResources.Collapse_regions_when_collapsing_to_definitions
Public ReadOnly Property Option_Block_Structure_Guides As String =
ServicesVSResources.Block_Structure_Guides
Public ReadOnly Property Option_Comments As String =
ServicesVSResources.Comments
Public ReadOnly Property Option_Show_guides_for_declaration_level_constructs As String =
ServicesVSResources.Show_guides_for_declaration_level_constructs
Public ReadOnly Property Option_Show_guides_for_code_level_constructs As String =
ServicesVSResources.Show_guides_for_code_level_constructs
Public ReadOnly Property Option_Fading As String = ServicesVSResources.Fading
Public ReadOnly Property Option_Fade_out_unused_imports As String = BasicVSResources.Fade_out_unused_imports
Public ReadOnly Property Option_Performance As String
Get
Return BasicVSResources.Performance
End Get
End Property
Public ReadOnly Property Option_Report_invalid_placeholders_in_string_dot_format_calls As String
Get
Return BasicVSResources.Report_invalid_placeholders_in_string_dot_format_calls
End Get
End Property
Public ReadOnly Property Option_RenameTrackingPreview As String
Get
Return BasicVSResources.Show_preview_for_rename_tracking
End Get
End Property
Public ReadOnly Property Option_Import_Directives As String =
BasicVSResources.Import_Directives
Public ReadOnly Property Option_PlaceSystemNamespaceFirst As String =
BasicVSResources.Place_System_directives_first_when_sorting_imports
Public ReadOnly Property Option_SeparateImportGroups As String =
BasicVSResources.Separate_import_directive_groups
Public ReadOnly Property Option_Suggest_imports_for_types_in_reference_assemblies As String =
BasicVSResources.Suggest_imports_for_types_in_reference_assemblies
Public ReadOnly Property Option_Suggest_imports_for_types_in_NuGet_packages As String =
BasicVSResources.Suggest_imports_for_types_in_NuGet_packages
Public ReadOnly Property Option_Add_missing_imports_on_paste As String =
BasicVSResources.Add_missing_imports_on_paste
Public ReadOnly Property Option_Regular_Expressions As String =
ServicesVSResources.Regular_Expressions
Public ReadOnly Property Option_Colorize_regular_expressions As String =
ServicesVSResources.Colorize_regular_expressions
Public ReadOnly Property Option_Report_invalid_regular_expressions As String =
ServicesVSResources.Report_invalid_regular_expressions
Public ReadOnly Property Option_Highlight_related_components_under_cursor As String =
ServicesVSResources.Highlight_related_components_under_cursor
Public ReadOnly Property Option_Show_completion_list As String =
ServicesVSResources.Show_completion_list
Public ReadOnly Property Option_Editor_Color_Scheme As String =
ServicesVSResources.Editor_Color_Scheme
Public ReadOnly Property Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page As String =
ServicesVSResources.Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page
Public ReadOnly Property Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations As String =
ServicesVSResources.Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations
Public ReadOnly Property Option_Color_Scheme_VisualStudio2019 As String =
ServicesVSResources.Visual_Studio_2019
Public ReadOnly Property Option_Color_Scheme_VisualStudio2017 As String =
ServicesVSResources.Visual_Studio_2017
Public ReadOnly Property Color_Scheme_VisualStudio2019_Tag As SchemeName =
SchemeName.VisualStudio2019
Public ReadOnly Property Color_Scheme_VisualStudio2017_Tag As SchemeName =
SchemeName.VisualStudio2017
Public ReadOnly Property Option_Show_Remove_Unused_References_command_in_Solution_Explorer_experimental As String =
ServicesVSResources.Show_Remove_Unused_References_command_in_Solution_Explorer_experimental
Public ReadOnly Property Enable_all_features_in_opened_files_from_source_generators_experimental As String =
ServicesVSResources.Enable_all_features_in_opened_files_from_source_generators_experimental
Public ReadOnly Property Option_Enable_file_logging_for_diagnostics As String =
ServicesVSResources.Enable_file_logging_for_diagnostics
Public ReadOnly Property Option_Skip_analyzers_for_implicitly_triggered_builds As String =
ServicesVSResources.Skip_analyzers_for_implicitly_triggered_builds
Public ReadOnly Property Show_inheritance_margin As String =
ServicesVSResources.Show_inheritance_margin
Public ReadOnly Property Inheritance_Margin_experimental As String =
ServicesVSResources.Inheritance_Margin_experimental
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.ColorSchemes
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Friend Module AdvancedOptionPageStrings
Public ReadOnly Property Option_AutomaticInsertionOfInterfaceAndMustOverrideMembers As String
Get
Return BasicVSResources.Automatic_insertion_of_Interface_and_MustOverride_members
End Get
End Property
Public ReadOnly Property Option_Analysis As String =
ServicesVSResources.Analysis
Public ReadOnly Property Option_Background_analysis_scope As String =
ServicesVSResources.Background_analysis_scope_colon
Public ReadOnly Property Option_Background_Analysis_Scope_Active_File As String =
ServicesVSResources.Current_document
Public ReadOnly Property Option_Background_Analysis_Scope_Open_Files_And_Projects As String =
ServicesVSResources.Open_documents
Public ReadOnly Property Option_Background_Analysis_Scope_Full_Solution As String =
ServicesVSResources.Entire_solution
Public ReadOnly Property Option_run_code_analysis_in_separate_process As String =
ServicesVSResources.Run_code_analysis_in_separate_process_requires_restart
Public ReadOnly Property Option_DisplayLineSeparators As String =
BasicVSResources.Show_procedure_line_separators
Public ReadOnly Property Option_Underline_reassigned_variables As String =
ServicesVSResources.Underline_reassigned_variables
Public ReadOnly Property Option_Display_all_hints_while_pressing_Alt_F1 As String =
ServicesVSResources.Display_all_hints_while_pressing_Alt_F1
Public ReadOnly Property Option_Color_hints As String =
ServicesVSResources.Color_hints
Public ReadOnly Property Option_Inline_Hints As String =
ServicesVSResources.Inline_Hints
Public ReadOnly Property Option_Display_inline_parameter_name_hints As String =
ServicesVSResources.Display_inline_parameter_name_hints
Public ReadOnly Property Option_Show_hints_for_literals As String =
ServicesVSResources.Show_hints_for_literals
Public ReadOnly Property Option_Show_hints_for_New_expressions As String =
BasicVSResources.Show_hints_for_New_expressions
Public ReadOnly Property Option_Show_hints_for_everything_else As String =
ServicesVSResources.Show_hints_for_everything_else
Public ReadOnly Property Option_Show_hints_for_indexers As String =
ServicesVSResources.Show_hints_for_indexers
Public ReadOnly Property Option_Suppress_hints_when_parameter_name_matches_the_method_s_intent As String =
ServicesVSResources.Suppress_hints_when_parameter_name_matches_the_method_s_intent
Public ReadOnly Property Option_Suppress_hints_when_parameter_names_differ_only_by_suffix As String =
ServicesVSResources.Suppress_hints_when_parameter_names_differ_only_by_suffix
Public ReadOnly Property Option_DontPutOutOrRefOnStruct As String =
BasicVSResources.Don_t_put_ByRef_on_custom_structure
Public ReadOnly Property Option_EditorHelp As String =
BasicVSResources.Editor_Help
Public ReadOnly Property Option_EnableEndConstruct As String =
BasicVSResources.A_utomatic_insertion_of_end_constructs
Public ReadOnly Property Option_EnableHighlightKeywords As String =
BasicVSResources.Highlight_related_keywords_under_cursor
Public ReadOnly Property Option_EnableHighlightReferences As String =
BasicVSResources.Highlight_references_to_symbol_under_cursor
Public ReadOnly Property Option_Quick_Actions As String =
ServicesVSResources.Quick_Actions
Public ReadOnly Property Option_Compute_Quick_Actions_asynchronously_experimental As String =
ServicesVSResources.Compute_Quick_Actions_asynchronously_experimental
Public ReadOnly Property Option_EnableLineCommit As String
Get
Return BasicVSResources.Pretty_listing_reformatting_of_code
End Get
End Property
Public ReadOnly Property Option_EnableOutlining As String
Get
Return BasicVSResources.Enter_outlining_mode_when_files_open
End Get
End Property
Public ReadOnly Property Option_ExtractMethod As String
Get
Return BasicVSResources.Extract_Method
End Get
End Property
Public ReadOnly Property Option_Implement_Interface_or_Abstract_Class As String =
ServicesVSResources.Implement_Interface_or_Abstract_Class
Public ReadOnly Property Option_When_inserting_properties_events_and_methods_place_them As String =
ServicesVSResources.When_inserting_properties_events_and_methods_place_them
Public ReadOnly Property Option_with_other_members_of_the_same_kind As String =
ServicesVSResources.with_other_members_of_the_same_kind
Public ReadOnly Property Option_When_generating_properties As String =
ServicesVSResources.When_generating_properties
Public ReadOnly Property Option_prefer_auto_properties As String =
ServicesVSResources.codegen_prefer_auto_properties
Public ReadOnly Property Option_prefer_throwing_properties As String =
ServicesVSResources.prefer_throwing_properties
Public ReadOnly Property Option_at_the_end As String =
ServicesVSResources.at_the_end
Public ReadOnly Property Option_GenerateXmlDocCommentsForTripleApostrophes As String =
BasicVSResources.Generate_XML_documentation_comments_for
Public ReadOnly Property Option_InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments As String =
BasicVSResources.Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments
Public ReadOnly Property Option_ShowRemarksInQuickInfo As String
Get
Return BasicVSResources.Show_remarks_in_Quick_Info
End Get
End Property
Public ReadOnly Property Option_GoToDefinition As String
Get
Return BasicVSResources.Go_to_Definition
End Get
End Property
Public ReadOnly Property Option_Highlighting As String
Get
Return BasicVSResources.Highlighting
End Get
End Property
Public ReadOnly Property Option_NavigateToObjectBrowser As String
Get
Return BasicVSResources.Navigate_to_Object_Browser_for_symbols_defined_in_metadata
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize As String
Get
Return BasicVSResources.Optimize_for_solution_size
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Small As String
Get
Return BasicVSResources.Small
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Regular As String
Get
Return BasicVSResources.Regular
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Large As String
Get
Return BasicVSResources.Large
End Get
End Property
Public ReadOnly Property Option_Outlining As String = ServicesVSResources.Outlining
Public ReadOnly Property Option_Show_outlining_for_declaration_level_constructs As String =
ServicesVSResources.Show_outlining_for_declaration_level_constructs
Public ReadOnly Property Option_Show_outlining_for_code_level_constructs As String =
ServicesVSResources.Show_outlining_for_code_level_constructs
Public ReadOnly Property Option_Show_outlining_for_comments_and_preprocessor_regions As String =
ServicesVSResources.Show_outlining_for_comments_and_preprocessor_regions
Public ReadOnly Property Option_Collapse_regions_when_collapsing_to_definitions As String =
ServicesVSResources.Collapse_regions_when_collapsing_to_definitions
Public ReadOnly Property Option_Block_Structure_Guides As String =
ServicesVSResources.Block_Structure_Guides
Public ReadOnly Property Option_Comments As String =
ServicesVSResources.Comments
Public ReadOnly Property Option_Show_guides_for_declaration_level_constructs As String =
ServicesVSResources.Show_guides_for_declaration_level_constructs
Public ReadOnly Property Option_Show_guides_for_code_level_constructs As String =
ServicesVSResources.Show_guides_for_code_level_constructs
Public ReadOnly Property Option_Fading As String = ServicesVSResources.Fading
Public ReadOnly Property Option_Fade_out_unused_imports As String = BasicVSResources.Fade_out_unused_imports
Public ReadOnly Property Option_Performance As String
Get
Return BasicVSResources.Performance
End Get
End Property
Public ReadOnly Property Option_Report_invalid_placeholders_in_string_dot_format_calls As String
Get
Return BasicVSResources.Report_invalid_placeholders_in_string_dot_format_calls
End Get
End Property
Public ReadOnly Property Option_RenameTrackingPreview As String
Get
Return BasicVSResources.Show_preview_for_rename_tracking
End Get
End Property
Public ReadOnly Property Option_Import_Directives As String =
BasicVSResources.Import_Directives
Public ReadOnly Property Option_PlaceSystemNamespaceFirst As String =
BasicVSResources.Place_System_directives_first_when_sorting_imports
Public ReadOnly Property Option_SeparateImportGroups As String =
BasicVSResources.Separate_import_directive_groups
Public ReadOnly Property Option_Suggest_imports_for_types_in_reference_assemblies As String =
BasicVSResources.Suggest_imports_for_types_in_reference_assemblies
Public ReadOnly Property Option_Suggest_imports_for_types_in_NuGet_packages As String =
BasicVSResources.Suggest_imports_for_types_in_NuGet_packages
Public ReadOnly Property Option_Add_missing_imports_on_paste As String =
BasicVSResources.Add_missing_imports_on_paste
Public ReadOnly Property Option_Regular_Expressions As String =
ServicesVSResources.Regular_Expressions
Public ReadOnly Property Option_Colorize_regular_expressions As String =
ServicesVSResources.Colorize_regular_expressions
Public ReadOnly Property Option_Report_invalid_regular_expressions As String =
ServicesVSResources.Report_invalid_regular_expressions
Public ReadOnly Property Option_Highlight_related_components_under_cursor As String =
ServicesVSResources.Highlight_related_components_under_cursor
Public ReadOnly Property Option_Show_completion_list As String =
ServicesVSResources.Show_completion_list
Public ReadOnly Property Option_Editor_Color_Scheme As String =
ServicesVSResources.Editor_Color_Scheme
Public ReadOnly Property Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page As String =
ServicesVSResources.Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page
Public ReadOnly Property Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations As String =
ServicesVSResources.Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations
Public ReadOnly Property Option_Color_Scheme_VisualStudio2019 As String =
ServicesVSResources.Visual_Studio_2019
Public ReadOnly Property Option_Color_Scheme_VisualStudio2017 As String =
ServicesVSResources.Visual_Studio_2017
Public ReadOnly Property Color_Scheme_VisualStudio2019_Tag As SchemeName =
SchemeName.VisualStudio2019
Public ReadOnly Property Color_Scheme_VisualStudio2017_Tag As SchemeName =
SchemeName.VisualStudio2017
Public ReadOnly Property Option_Show_Remove_Unused_References_command_in_Solution_Explorer_experimental As String =
ServicesVSResources.Show_Remove_Unused_References_command_in_Solution_Explorer_experimental
Public ReadOnly Property Enable_all_features_in_opened_files_from_source_generators_experimental As String =
ServicesVSResources.Enable_all_features_in_opened_files_from_source_generators_experimental
Public ReadOnly Property Option_Enable_file_logging_for_diagnostics As String =
ServicesVSResources.Enable_file_logging_for_diagnostics
Public ReadOnly Property Option_Skip_analyzers_for_implicitly_triggered_builds As String =
ServicesVSResources.Skip_analyzers_for_implicitly_triggered_builds
Public ReadOnly Property Show_inheritance_margin As String =
ServicesVSResources.Show_inheritance_margin
Public ReadOnly Property Inheritance_Margin_experimental As String =
ServicesVSResources.Inheritance_Margin_experimental
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Tools/ExternalAccess/FSharp/Internal/Diagnostics/FSharpUnusedOpensDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics
{
[Shared]
[ExportLanguageService(typeof(FSharpUnusedOpensDiagnosticAnalyzerService), LanguageNames.FSharp)]
internal class FSharpUnusedOpensDiagnosticAnalyzerService : ILanguageService
{
private readonly IFSharpUnusedOpensDiagnosticAnalyzer _analyzer;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpUnusedOpensDiagnosticAnalyzerService(IFSharpUnusedOpensDiagnosticAnalyzer analyzer)
{
_analyzer = analyzer;
}
public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken)
{
return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken);
}
}
[DiagnosticAnalyzer(LanguageNames.FSharp)]
internal class FSharpUnusedOpensDeclarationsDiagnosticAnalyzer : DocumentDiagnosticAnalyzer
{
private readonly DiagnosticDescriptor _descriptor =
new DiagnosticDescriptor(
IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId,
ExternalAccessFSharpResources.RemoveUnusedOpens,
ExternalAccessFSharpResources.UnusedOpens,
DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor);
public override int Priority => 90; // Default = 50
public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetService<FSharpUnusedOpensDiagnosticAnalyzerService>();
if (analyzer == null)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken);
}
public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
public bool OpenFileOnly(Workspace workspace)
{
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics
{
[Shared]
[ExportLanguageService(typeof(FSharpUnusedOpensDiagnosticAnalyzerService), LanguageNames.FSharp)]
internal class FSharpUnusedOpensDiagnosticAnalyzerService : ILanguageService
{
private readonly IFSharpUnusedOpensDiagnosticAnalyzer _analyzer;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpUnusedOpensDiagnosticAnalyzerService(IFSharpUnusedOpensDiagnosticAnalyzer analyzer)
{
_analyzer = analyzer;
}
public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken)
{
return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken);
}
}
[DiagnosticAnalyzer(LanguageNames.FSharp)]
internal class FSharpUnusedOpensDeclarationsDiagnosticAnalyzer : DocumentDiagnosticAnalyzer
{
private readonly DiagnosticDescriptor _descriptor =
new DiagnosticDescriptor(
IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId,
ExternalAccessFSharpResources.RemoveUnusedOpens,
ExternalAccessFSharpResources.UnusedOpens,
DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor);
public override int Priority => 90; // Default = 50
public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetService<FSharpUnusedOpensDiagnosticAnalyzerService>();
if (analyzer == null)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken);
}
public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
return Task.FromResult(ImmutableArray<Diagnostic>.Empty);
}
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
public bool OpenFileOnly(Workspace workspace)
{
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxNode.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The base class for all nodes in the VB syntax tree.
''' </summary>
Partial Public MustInherit Class VisualBasicSyntaxNode
Inherits SyntaxNode
' Constructor. Called only by derived classes.
Friend Sub New(green As GreenNode, parent As SyntaxNode, position As Integer)
MyBase.New(green, parent, position)
End Sub
''' <summary>
''' Used by structured trivia which has no parent node, so need to know syntax tree explicitly
''' </summary>
Friend Sub New(green As GreenNode, position As Integer, syntaxTree As SyntaxTree)
MyBase.New(green, Nothing, position)
_syntaxTree = syntaxTree
End Sub
'TODO: may be eventually not needed
Friend ReadOnly Property VbGreen As InternalSyntax.VisualBasicSyntaxNode
Get
Return DirectCast(Me.Green, InternalSyntax.VisualBasicSyntaxNode)
End Get
End Property
''' <summary>
''' Returns a non-null SyntaxTree that owns this node.
''' If this node was created with an explicit non-null SyntaxTree, returns that tree.
''' Otherwise, if this node has a non-null parent, then returns the parent's SyntaxTree.
''' Otherwise, returns a newly created SyntaxTree rooted at this node, preserving this node's reference identity.
''' </summary>
Friend Shadows ReadOnly Property SyntaxTree As SyntaxTree
Get
If Me._syntaxTree Is Nothing Then
Dim stack = ArrayBuilder(Of SyntaxNode).GetInstance()
Dim tree As SyntaxTree = Nothing
Dim current As SyntaxNode = Me
Dim rootCandidate As SyntaxNode = Nothing
While current IsNot Nothing
tree = current._syntaxTree
If tree IsNot Nothing Then
Exit While
End If
rootCandidate = current
stack.Push(current)
current = rootCandidate.Parent
End While
If tree Is Nothing Then
Debug.Assert(rootCandidate IsNot Nothing)
tree = VisualBasicSyntaxTree.CreateWithoutClone(DirectCast(rootCandidate, VisualBasicSyntaxNode))
End If
Debug.Assert(tree IsNot Nothing)
While stack.Count > 0
Dim alternativeTree As SyntaxTree = Interlocked.CompareExchange(stack.Pop()._syntaxTree, tree, Nothing)
If alternativeTree IsNot Nothing Then
tree = alternativeTree
End If
End While
stack.Free()
End If
Return Me._syntaxTree
End Get
End Property
Public MustOverride Function Accept(Of TResult)(visitor As VisualBasicSyntaxVisitor(Of TResult)) As TResult
Public MustOverride Sub Accept(visitor As VisualBasicSyntaxVisitor)
''' <summary>
''' Returns the <see cref="SyntaxKind"/> of the node.
''' </summary>
Public Function Kind() As SyntaxKind
Return CType(Me.Green.RawKind, SyntaxKind)
End Function
''' <summary>
''' The language name this node is syntax of.
''' </summary>
Public Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
''' <summary>
''' The parent of this node.
''' </summary>
''' <value>The parent node of this node, or Nothing if this node is the root.</value>
Friend Shadows ReadOnly Property Parent As VisualBasicSyntaxNode
Get
Return DirectCast(MyBase.Parent, VisualBasicSyntaxNode)
End Get
End Property
#Region "Serialization"
''' <summary>
''' Deserialize a syntax node from a byte stream.
''' </summary>
Public Shared Function DeserializeFrom(stream As IO.Stream, Optional cancellationToken As CancellationToken = Nothing) As SyntaxNode
If stream Is Nothing Then
Throw New ArgumentNullException(NameOf(stream))
End If
If Not stream.CanRead Then
Throw New InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeReadFrom)
End If
Using reader = ObjectReader.TryGetReader(stream, leaveOpen:=True, cancellationToken:=cancellationToken)
If reader Is Nothing Then
Throw New ArgumentException(CodeAnalysisResources.Stream_contains_invalid_data, NameOf(stream))
End If
Return DirectCast(reader.ReadValue(), InternalSyntax.VisualBasicSyntaxNode).CreateRed(Nothing, 0)
End Using
End Function
#End Region
''' <summary>
''' Returns True if this node represents a directive.
''' </summary>
Public ReadOnly Property IsDirective As Boolean
Get
Return Me.Green.IsDirective
End Get
End Property
''' <summary>
''' Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>.
''' </summary>
''' <remarks>
''' Slight performance improvement.
''' </remarks>
Public Shadows ReadOnly Property SpanStart As Integer
Get
Return Position + Me.Green.GetLeadingTriviaWidth()
End Get
End Property
''' <summary>
''' Get the preceding trivia nodes of this node. If this node is a token, returns the preceding trivia
''' associated with this node. If this is a non-terminal, returns the preceding trivia of the first token
''' of this node.
''' </summary>
''' <returns>A list of the preceding trivia.</returns>
''' <remarks>If this node is a non-terminal, the parents of the trivia will be the first token of this
''' non-terminal; NOT this node.</remarks>
Public Shadows Function GetLeadingTrivia() As SyntaxTriviaList
Return GetFirstToken(includeZeroWidth:=True).LeadingTrivia
End Function
''' <summary>
''' Get the following trivia nodes of this node. If this node is a token, returns the following trivia
''' associated with this node. If this is a non-terminal, returns the following trivia of the last token
''' of this node.
''' </summary>
''' <returns>A list of the following trivia.</returns>
''' <remarks>If this node is a non-terminal, the parents of the trivia will be the first token of this
''' non-terminal; NOT this node.</remarks>
Public Shadows Function GetTrailingTrivia() As SyntaxTriviaList
Return GetLastToken(includeZeroWidth:=True).TrailingTrivia
End Function
' an empty collection of syntax errors.
Friend Shared EmptyErrorCollection As New ReadOnlyCollection(Of Diagnostic)(Array.Empty(Of Diagnostic))
''' <summary>
''' Get all syntax errors associated with this node, or any child nodes, grand-child nodes, etc. The errors
''' are not in order.
''' </summary>
Friend Function GetSyntaxErrors(tree As SyntaxTree) As ReadOnlyCollection(Of Diagnostic)
Return DoGetSyntaxErrors(tree, Me)
End Function
Friend Shared Function DoGetSyntaxErrors(tree As SyntaxTree, nodeOrToken As SyntaxNodeOrToken) As ReadOnlyCollection(Of Diagnostic)
If Not nodeOrToken.ContainsDiagnostics Then
Return EmptyErrorCollection
Else
' Accumulated a stack of nodes with errors to process.
Dim nodesToProcess As New Stack(Of SyntaxNodeOrToken)
Dim errorList As New List(Of Diagnostic)
nodesToProcess.Push(nodeOrToken)
While nodesToProcess.Count > 0
' Add errors from current node being processed to the list
nodeOrToken = nodesToProcess.Pop()
Dim node = nodeOrToken.UnderlyingNode
If node.ContainsDiagnostics Then
Dim errors = DirectCast(node, Syntax.InternalSyntax.VisualBasicSyntaxNode).GetDiagnostics
If errors IsNot Nothing Then
For i = 0 To errors.Length - 1
Dim greenError = errors(i)
Debug.Assert(greenError IsNot Nothing)
errorList.Add(CreateSyntaxError(tree, nodeOrToken, greenError))
Next
End If
End If
' Children or trivia must have errors too, based on the count. Add them.
If Not nodeOrToken.IsToken Then
PushNodesWithErrors(nodesToProcess, nodeOrToken.ChildNodesAndTokens())
ElseIf nodeOrToken.IsToken Then
ProcessTrivia(tree, errorList, nodesToProcess, nodeOrToken.GetLeadingTrivia())
ProcessTrivia(tree, errorList, nodesToProcess, nodeOrToken.GetTrailingTrivia())
End If
End While
Return New ReadOnlyCollection(Of Diagnostic)(errorList)
End If
End Function
''' <summary>
''' Push any nodes that have errors in the given collection onto a stack
''' </summary>
Private Shared Sub PushNodesWithErrors(stack As Stack(Of SyntaxNodeOrToken), nodes As ChildSyntaxList)
Debug.Assert(stack IsNot Nothing)
For Each n In nodes
Debug.Assert(Not n.IsKind(SyntaxKind.None))
If n.ContainsDiagnostics Then
stack.Push(n)
End If
Next
End Sub
Private Shared Sub ProcessTrivia(tree As SyntaxTree,
errorList As List(Of Diagnostic),
stack As Stack(Of SyntaxNodeOrToken),
nodes As SyntaxTriviaList)
Debug.Assert(stack IsNot Nothing)
For Each n In nodes
Debug.Assert(n.Kind <> SyntaxKind.None)
If n.UnderlyingNode.ContainsDiagnostics Then
If n.HasStructure Then
stack.Push(DirectCast(n.GetStructure, VisualBasicSyntaxNode))
Else
Dim errors = DirectCast(n.UnderlyingNode, InternalSyntax.VisualBasicSyntaxNode).GetDiagnostics
If errors IsNot Nothing Then
For i = 0 To errors.Length - 1
Dim e = errors(i)
errorList.Add(CreateSyntaxError(tree, n, e))
Next
End If
End If
End If
Next
End Sub
''' <summary>
''' Given a error info from this node, create the corresponding syntax error with the right span.
''' </summary>
Private Shared Function CreateSyntaxError(tree As SyntaxTree, nodeOrToken As SyntaxNodeOrToken, errorInfo As DiagnosticInfo) As Diagnostic
Debug.Assert(errorInfo IsNot Nothing)
' Translate the green error offset/width relative to my location.
Return New VBDiagnostic(errorInfo, If(tree Is Nothing, New SourceLocation(tree, nodeOrToken.Span), tree.GetLocation(nodeOrToken.Span)))
End Function
Private Shared Function CreateSyntaxError(tree As SyntaxTree, nodeOrToken As SyntaxTrivia, errorInfo As DiagnosticInfo) As Diagnostic
Debug.Assert(errorInfo IsNot Nothing)
' Translate the green error offset/width relative to my location.
Return New VBDiagnostic(errorInfo, If(tree Is Nothing, New SourceLocation(tree, nodeOrToken.Span), tree.GetLocation(nodeOrToken.Span)))
End Function
''' <summary>
''' Add an error to the given node, creating a new node that is the same except it has no parent,
''' and has the given error attached to it. The error span is the entire span of this node.
''' </summary>
''' <param name="err">The error to attach to this node</param>
''' <returns>A new node, with no parent, that has this error added to it.</returns>
''' <remarks>Since nodes are immutable, the only way to create nodes with errors attached is to create a node without an error,
''' then add an error with this method to create another node.</remarks>
Friend Function AddError(err As DiagnosticInfo) As VisualBasicSyntaxNode
Dim errorInfos() As DiagnosticInfo
' If the green node already has errors, add those on.
If Me.Green.GetDiagnostics Is Nothing Then
errorInfos = {err}
Else
' Add the error to the error list.
errorInfos = Me.Green.GetDiagnostics
Dim length As Integer = errorInfos.Length
ReDim Preserve errorInfos(length)
errorInfos(length) = err
End If
' Get a new green node with the errors added on.
Dim greenWithDiagnostics = Me.Green.SetDiagnostics(errorInfos)
' convert to red node with no parent.
Dim result = greenWithDiagnostics.CreateRed(Nothing, 0)
Debug.Assert(result IsNot Nothing)
Return DirectCast(result, VisualBasicSyntaxNode)
End Function
Public Shadows Function GetFirstToken(Optional includeZeroWidth As Boolean = False,
Optional includeSkipped As Boolean = False,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken
Return CType(MyBase.GetFirstToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments), SyntaxToken)
End Function
Public Shadows Function GetLastToken(Optional includeZeroWidth As Boolean = False,
Optional includeSkipped As Boolean = False,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken
Return CType(MyBase.GetLastToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments), SyntaxToken)
End Function
Public Function GetDirectives(Optional filter As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As IList(Of DirectiveTriviaSyntax)
Return (CType(Me, SyntaxNodeOrToken)).GetDirectives(Of DirectiveTriviaSyntax)(filter)
End Function
Public Function GetFirstDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax
Dim child As SyntaxNodeOrToken
For Each child In Me.ChildNodesAndTokens()
If child.ContainsDirectives Then
If child.IsNode Then
Dim d As DirectiveTriviaSyntax = DirectCast(child.AsNode, VisualBasicSyntaxNode).GetFirstDirective(predicate)
If d IsNot Nothing Then
Return d
End If
Else
Dim tr As SyntaxTrivia
For Each tr In child.AsToken.LeadingTrivia
If tr.IsDirective Then
Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)
If ((predicate Is Nothing) OrElse predicate(d)) Then
Return d
End If
End If
Next
Continue For
End If
End If
Next
Return Nothing
End Function
Public Function GetLastDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax
Dim child As SyntaxNodeOrToken
For Each child In Me.ChildNodesAndTokens().Reverse
If child.ContainsDirectives Then
If child.IsNode Then
Dim d As DirectiveTriviaSyntax = DirectCast(child.AsNode, VisualBasicSyntaxNode).GetLastDirective(predicate)
If d IsNot Nothing Then
Return d
End If
Else
Dim token As SyntaxToken = child.AsToken
For Each tr In token.LeadingTrivia.Reverse()
If tr.IsDirective Then
Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)
If ((predicate Is Nothing) OrElse predicate(d)) Then
Return d
End If
End If
Next
End If
End If
Next
Return Nothing
End Function
#Region "Core Overloads"
Protected Overrides ReadOnly Property SyntaxTreeCore As SyntaxTree
Get
Return Me.SyntaxTree
End Get
End Property
Protected Overrides Function ReplaceCore(Of TNode As SyntaxNode)(
Optional nodes As IEnumerable(Of TNode) = Nothing,
Optional computeReplacementNode As Func(Of TNode, TNode, SyntaxNode) = Nothing,
Optional tokens As IEnumerable(Of SyntaxToken) = Nothing,
Optional computeReplacementToken As Func(Of SyntaxToken, SyntaxToken, SyntaxToken) = Nothing,
Optional trivia As IEnumerable(Of SyntaxTrivia) = Nothing,
Optional computeReplacementTrivia As Func(Of SyntaxTrivia, SyntaxTrivia, SyntaxTrivia) = Nothing) As SyntaxNode
Return SyntaxReplacer.Replace(Me, nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function RemoveNodesCore(nodes As IEnumerable(Of SyntaxNode), options As SyntaxRemoveOptions) As SyntaxNode
Return SyntaxNodeRemover.RemoveNodes(Me, nodes, options).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function ReplaceNodeInListCore(originalNode As SyntaxNode, replacementNodes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxReplacer.ReplaceNodeInList(Me, originalNode, replacementNodes).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function InsertNodesInListCore(nodeInList As SyntaxNode, nodesToInsert As IEnumerable(Of SyntaxNode), insertBefore As Boolean) As SyntaxNode
Return SyntaxReplacer.InsertNodeInList(Me, nodeInList, nodesToInsert, insertBefore).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function ReplaceTokenInListCore(originalToken As SyntaxToken, newTokens As IEnumerable(Of SyntaxToken)) As SyntaxNode
Return SyntaxReplacer.ReplaceTokenInList(Me, originalToken, newTokens).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function InsertTokensInListCore(originalToken As SyntaxToken, newTokens As IEnumerable(Of SyntaxToken), insertBefore As Boolean) As SyntaxNode
Return SyntaxReplacer.InsertTokenInList(Me, originalToken, newTokens, insertBefore).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function ReplaceTriviaInListCore(originalTrivia As SyntaxTrivia, newTrivia As IEnumerable(Of SyntaxTrivia)) As SyntaxNode
Return SyntaxReplacer.ReplaceTriviaInList(Me, originalTrivia, newTrivia).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function InsertTriviaInListCore(originalTrivia As SyntaxTrivia, newTrivia As IEnumerable(Of SyntaxTrivia), insertBefore As Boolean) As SyntaxNode
Return SyntaxReplacer.InsertTriviaInList(Me, originalTrivia, newTrivia, insertBefore).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function NormalizeWhitespaceCore(indentation As String, eol As String, elasticTrivia As Boolean) As SyntaxNode
Return SyntaxNormalizer.Normalize(Me, indentation, eol, elasticTrivia, useDefaultCasing:=False).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
#End Region
''' <summary>
''' Gets the location of this node.
''' </summary>
Public Shadows Function GetLocation() As Location
' Note that we want to return 'no location' for all nodes from embedded syntax trees
If Me.SyntaxTree IsNot Nothing Then
Dim tree = Me.SyntaxTree
If tree.IsEmbeddedSyntaxTree Then
Return New EmbeddedTreeLocation(tree.GetEmbeddedKind, Me.Span)
ElseIf tree.IsMyTemplate Then
Return New MyTemplateLocation(tree, Me.Span)
End If
End If
Return New SourceLocation(Me)
End Function
''' <summary>
''' Gets a SyntaxReference for this syntax node. SyntaxReferences can be used to regain access to a
''' syntax node without keeping the entire tree and source text in memory.
''' </summary>
Friend Shadows Function GetReference() As SyntaxReference
Return SyntaxTree.GetReference(Me)
End Function
''' <summary>
''' Gets a list of all the diagnostics in the sub tree that has this node as its root.
''' This method does not filter diagnostics based on compiler options like nowarn, warnaserror etc.
''' </summary>
Public Shadows Function GetDiagnostics() As IEnumerable(Of Diagnostic)
Return SyntaxTree.GetDiagnostics(Me)
End Function
Protected Overrides Function IsEquivalentToCore(node As SyntaxNode, Optional topLevel As Boolean = False) As Boolean
Return SyntaxFactory.AreEquivalent(Me, DirectCast(node, VisualBasicSyntaxNode), topLevel)
End Function
Friend Overrides Function ShouldCreateWeakList() As Boolean
Return TypeOf Me Is MethodBlockBaseSyntax
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The base class for all nodes in the VB syntax tree.
''' </summary>
Partial Public MustInherit Class VisualBasicSyntaxNode
Inherits SyntaxNode
' Constructor. Called only by derived classes.
Friend Sub New(green As GreenNode, parent As SyntaxNode, position As Integer)
MyBase.New(green, parent, position)
End Sub
''' <summary>
''' Used by structured trivia which has no parent node, so need to know syntax tree explicitly
''' </summary>
Friend Sub New(green As GreenNode, position As Integer, syntaxTree As SyntaxTree)
MyBase.New(green, Nothing, position)
_syntaxTree = syntaxTree
End Sub
'TODO: may be eventually not needed
Friend ReadOnly Property VbGreen As InternalSyntax.VisualBasicSyntaxNode
Get
Return DirectCast(Me.Green, InternalSyntax.VisualBasicSyntaxNode)
End Get
End Property
''' <summary>
''' Returns a non-null SyntaxTree that owns this node.
''' If this node was created with an explicit non-null SyntaxTree, returns that tree.
''' Otherwise, if this node has a non-null parent, then returns the parent's SyntaxTree.
''' Otherwise, returns a newly created SyntaxTree rooted at this node, preserving this node's reference identity.
''' </summary>
Friend Shadows ReadOnly Property SyntaxTree As SyntaxTree
Get
If Me._syntaxTree Is Nothing Then
Dim stack = ArrayBuilder(Of SyntaxNode).GetInstance()
Dim tree As SyntaxTree = Nothing
Dim current As SyntaxNode = Me
Dim rootCandidate As SyntaxNode = Nothing
While current IsNot Nothing
tree = current._syntaxTree
If tree IsNot Nothing Then
Exit While
End If
rootCandidate = current
stack.Push(current)
current = rootCandidate.Parent
End While
If tree Is Nothing Then
Debug.Assert(rootCandidate IsNot Nothing)
tree = VisualBasicSyntaxTree.CreateWithoutClone(DirectCast(rootCandidate, VisualBasicSyntaxNode))
End If
Debug.Assert(tree IsNot Nothing)
While stack.Count > 0
Dim alternativeTree As SyntaxTree = Interlocked.CompareExchange(stack.Pop()._syntaxTree, tree, Nothing)
If alternativeTree IsNot Nothing Then
tree = alternativeTree
End If
End While
stack.Free()
End If
Return Me._syntaxTree
End Get
End Property
Public MustOverride Function Accept(Of TResult)(visitor As VisualBasicSyntaxVisitor(Of TResult)) As TResult
Public MustOverride Sub Accept(visitor As VisualBasicSyntaxVisitor)
''' <summary>
''' Returns the <see cref="SyntaxKind"/> of the node.
''' </summary>
Public Function Kind() As SyntaxKind
Return CType(Me.Green.RawKind, SyntaxKind)
End Function
''' <summary>
''' The language name this node is syntax of.
''' </summary>
Public Overrides ReadOnly Property Language As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
''' <summary>
''' The parent of this node.
''' </summary>
''' <value>The parent node of this node, or Nothing if this node is the root.</value>
Friend Shadows ReadOnly Property Parent As VisualBasicSyntaxNode
Get
Return DirectCast(MyBase.Parent, VisualBasicSyntaxNode)
End Get
End Property
#Region "Serialization"
''' <summary>
''' Deserialize a syntax node from a byte stream.
''' </summary>
Public Shared Function DeserializeFrom(stream As IO.Stream, Optional cancellationToken As CancellationToken = Nothing) As SyntaxNode
If stream Is Nothing Then
Throw New ArgumentNullException(NameOf(stream))
End If
If Not stream.CanRead Then
Throw New InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeReadFrom)
End If
Using reader = ObjectReader.TryGetReader(stream, leaveOpen:=True, cancellationToken:=cancellationToken)
If reader Is Nothing Then
Throw New ArgumentException(CodeAnalysisResources.Stream_contains_invalid_data, NameOf(stream))
End If
Return DirectCast(reader.ReadValue(), InternalSyntax.VisualBasicSyntaxNode).CreateRed(Nothing, 0)
End Using
End Function
#End Region
''' <summary>
''' Returns True if this node represents a directive.
''' </summary>
Public ReadOnly Property IsDirective As Boolean
Get
Return Me.Green.IsDirective
End Get
End Property
''' <summary>
''' Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>.
''' </summary>
''' <remarks>
''' Slight performance improvement.
''' </remarks>
Public Shadows ReadOnly Property SpanStart As Integer
Get
Return Position + Me.Green.GetLeadingTriviaWidth()
End Get
End Property
''' <summary>
''' Get the preceding trivia nodes of this node. If this node is a token, returns the preceding trivia
''' associated with this node. If this is a non-terminal, returns the preceding trivia of the first token
''' of this node.
''' </summary>
''' <returns>A list of the preceding trivia.</returns>
''' <remarks>If this node is a non-terminal, the parents of the trivia will be the first token of this
''' non-terminal; NOT this node.</remarks>
Public Shadows Function GetLeadingTrivia() As SyntaxTriviaList
Return GetFirstToken(includeZeroWidth:=True).LeadingTrivia
End Function
''' <summary>
''' Get the following trivia nodes of this node. If this node is a token, returns the following trivia
''' associated with this node. If this is a non-terminal, returns the following trivia of the last token
''' of this node.
''' </summary>
''' <returns>A list of the following trivia.</returns>
''' <remarks>If this node is a non-terminal, the parents of the trivia will be the first token of this
''' non-terminal; NOT this node.</remarks>
Public Shadows Function GetTrailingTrivia() As SyntaxTriviaList
Return GetLastToken(includeZeroWidth:=True).TrailingTrivia
End Function
' an empty collection of syntax errors.
Friend Shared EmptyErrorCollection As New ReadOnlyCollection(Of Diagnostic)(Array.Empty(Of Diagnostic))
''' <summary>
''' Get all syntax errors associated with this node, or any child nodes, grand-child nodes, etc. The errors
''' are not in order.
''' </summary>
Friend Function GetSyntaxErrors(tree As SyntaxTree) As ReadOnlyCollection(Of Diagnostic)
Return DoGetSyntaxErrors(tree, Me)
End Function
Friend Shared Function DoGetSyntaxErrors(tree As SyntaxTree, nodeOrToken As SyntaxNodeOrToken) As ReadOnlyCollection(Of Diagnostic)
If Not nodeOrToken.ContainsDiagnostics Then
Return EmptyErrorCollection
Else
' Accumulated a stack of nodes with errors to process.
Dim nodesToProcess As New Stack(Of SyntaxNodeOrToken)
Dim errorList As New List(Of Diagnostic)
nodesToProcess.Push(nodeOrToken)
While nodesToProcess.Count > 0
' Add errors from current node being processed to the list
nodeOrToken = nodesToProcess.Pop()
Dim node = nodeOrToken.UnderlyingNode
If node.ContainsDiagnostics Then
Dim errors = DirectCast(node, Syntax.InternalSyntax.VisualBasicSyntaxNode).GetDiagnostics
If errors IsNot Nothing Then
For i = 0 To errors.Length - 1
Dim greenError = errors(i)
Debug.Assert(greenError IsNot Nothing)
errorList.Add(CreateSyntaxError(tree, nodeOrToken, greenError))
Next
End If
End If
' Children or trivia must have errors too, based on the count. Add them.
If Not nodeOrToken.IsToken Then
PushNodesWithErrors(nodesToProcess, nodeOrToken.ChildNodesAndTokens())
ElseIf nodeOrToken.IsToken Then
ProcessTrivia(tree, errorList, nodesToProcess, nodeOrToken.GetLeadingTrivia())
ProcessTrivia(tree, errorList, nodesToProcess, nodeOrToken.GetTrailingTrivia())
End If
End While
Return New ReadOnlyCollection(Of Diagnostic)(errorList)
End If
End Function
''' <summary>
''' Push any nodes that have errors in the given collection onto a stack
''' </summary>
Private Shared Sub PushNodesWithErrors(stack As Stack(Of SyntaxNodeOrToken), nodes As ChildSyntaxList)
Debug.Assert(stack IsNot Nothing)
For Each n In nodes
Debug.Assert(Not n.IsKind(SyntaxKind.None))
If n.ContainsDiagnostics Then
stack.Push(n)
End If
Next
End Sub
Private Shared Sub ProcessTrivia(tree As SyntaxTree,
errorList As List(Of Diagnostic),
stack As Stack(Of SyntaxNodeOrToken),
nodes As SyntaxTriviaList)
Debug.Assert(stack IsNot Nothing)
For Each n In nodes
Debug.Assert(n.Kind <> SyntaxKind.None)
If n.UnderlyingNode.ContainsDiagnostics Then
If n.HasStructure Then
stack.Push(DirectCast(n.GetStructure, VisualBasicSyntaxNode))
Else
Dim errors = DirectCast(n.UnderlyingNode, InternalSyntax.VisualBasicSyntaxNode).GetDiagnostics
If errors IsNot Nothing Then
For i = 0 To errors.Length - 1
Dim e = errors(i)
errorList.Add(CreateSyntaxError(tree, n, e))
Next
End If
End If
End If
Next
End Sub
''' <summary>
''' Given a error info from this node, create the corresponding syntax error with the right span.
''' </summary>
Private Shared Function CreateSyntaxError(tree As SyntaxTree, nodeOrToken As SyntaxNodeOrToken, errorInfo As DiagnosticInfo) As Diagnostic
Debug.Assert(errorInfo IsNot Nothing)
' Translate the green error offset/width relative to my location.
Return New VBDiagnostic(errorInfo, If(tree Is Nothing, New SourceLocation(tree, nodeOrToken.Span), tree.GetLocation(nodeOrToken.Span)))
End Function
Private Shared Function CreateSyntaxError(tree As SyntaxTree, nodeOrToken As SyntaxTrivia, errorInfo As DiagnosticInfo) As Diagnostic
Debug.Assert(errorInfo IsNot Nothing)
' Translate the green error offset/width relative to my location.
Return New VBDiagnostic(errorInfo, If(tree Is Nothing, New SourceLocation(tree, nodeOrToken.Span), tree.GetLocation(nodeOrToken.Span)))
End Function
''' <summary>
''' Add an error to the given node, creating a new node that is the same except it has no parent,
''' and has the given error attached to it. The error span is the entire span of this node.
''' </summary>
''' <param name="err">The error to attach to this node</param>
''' <returns>A new node, with no parent, that has this error added to it.</returns>
''' <remarks>Since nodes are immutable, the only way to create nodes with errors attached is to create a node without an error,
''' then add an error with this method to create another node.</remarks>
Friend Function AddError(err As DiagnosticInfo) As VisualBasicSyntaxNode
Dim errorInfos() As DiagnosticInfo
' If the green node already has errors, add those on.
If Me.Green.GetDiagnostics Is Nothing Then
errorInfos = {err}
Else
' Add the error to the error list.
errorInfos = Me.Green.GetDiagnostics
Dim length As Integer = errorInfos.Length
ReDim Preserve errorInfos(length)
errorInfos(length) = err
End If
' Get a new green node with the errors added on.
Dim greenWithDiagnostics = Me.Green.SetDiagnostics(errorInfos)
' convert to red node with no parent.
Dim result = greenWithDiagnostics.CreateRed(Nothing, 0)
Debug.Assert(result IsNot Nothing)
Return DirectCast(result, VisualBasicSyntaxNode)
End Function
Public Shadows Function GetFirstToken(Optional includeZeroWidth As Boolean = False,
Optional includeSkipped As Boolean = False,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken
Return CType(MyBase.GetFirstToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments), SyntaxToken)
End Function
Public Shadows Function GetLastToken(Optional includeZeroWidth As Boolean = False,
Optional includeSkipped As Boolean = False,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken
Return CType(MyBase.GetLastToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments), SyntaxToken)
End Function
Public Function GetDirectives(Optional filter As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As IList(Of DirectiveTriviaSyntax)
Return (CType(Me, SyntaxNodeOrToken)).GetDirectives(Of DirectiveTriviaSyntax)(filter)
End Function
Public Function GetFirstDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax
Dim child As SyntaxNodeOrToken
For Each child In Me.ChildNodesAndTokens()
If child.ContainsDirectives Then
If child.IsNode Then
Dim d As DirectiveTriviaSyntax = DirectCast(child.AsNode, VisualBasicSyntaxNode).GetFirstDirective(predicate)
If d IsNot Nothing Then
Return d
End If
Else
Dim tr As SyntaxTrivia
For Each tr In child.AsToken.LeadingTrivia
If tr.IsDirective Then
Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)
If ((predicate Is Nothing) OrElse predicate(d)) Then
Return d
End If
End If
Next
Continue For
End If
End If
Next
Return Nothing
End Function
Public Function GetLastDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax
Dim child As SyntaxNodeOrToken
For Each child In Me.ChildNodesAndTokens().Reverse
If child.ContainsDirectives Then
If child.IsNode Then
Dim d As DirectiveTriviaSyntax = DirectCast(child.AsNode, VisualBasicSyntaxNode).GetLastDirective(predicate)
If d IsNot Nothing Then
Return d
End If
Else
Dim token As SyntaxToken = child.AsToken
For Each tr In token.LeadingTrivia.Reverse()
If tr.IsDirective Then
Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax)
If ((predicate Is Nothing) OrElse predicate(d)) Then
Return d
End If
End If
Next
End If
End If
Next
Return Nothing
End Function
#Region "Core Overloads"
Protected Overrides ReadOnly Property SyntaxTreeCore As SyntaxTree
Get
Return Me.SyntaxTree
End Get
End Property
Protected Overrides Function ReplaceCore(Of TNode As SyntaxNode)(
Optional nodes As IEnumerable(Of TNode) = Nothing,
Optional computeReplacementNode As Func(Of TNode, TNode, SyntaxNode) = Nothing,
Optional tokens As IEnumerable(Of SyntaxToken) = Nothing,
Optional computeReplacementToken As Func(Of SyntaxToken, SyntaxToken, SyntaxToken) = Nothing,
Optional trivia As IEnumerable(Of SyntaxTrivia) = Nothing,
Optional computeReplacementTrivia As Func(Of SyntaxTrivia, SyntaxTrivia, SyntaxTrivia) = Nothing) As SyntaxNode
Return SyntaxReplacer.Replace(Me, nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function RemoveNodesCore(nodes As IEnumerable(Of SyntaxNode), options As SyntaxRemoveOptions) As SyntaxNode
Return SyntaxNodeRemover.RemoveNodes(Me, nodes, options).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function ReplaceNodeInListCore(originalNode As SyntaxNode, replacementNodes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return SyntaxReplacer.ReplaceNodeInList(Me, originalNode, replacementNodes).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function InsertNodesInListCore(nodeInList As SyntaxNode, nodesToInsert As IEnumerable(Of SyntaxNode), insertBefore As Boolean) As SyntaxNode
Return SyntaxReplacer.InsertNodeInList(Me, nodeInList, nodesToInsert, insertBefore).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function ReplaceTokenInListCore(originalToken As SyntaxToken, newTokens As IEnumerable(Of SyntaxToken)) As SyntaxNode
Return SyntaxReplacer.ReplaceTokenInList(Me, originalToken, newTokens).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function InsertTokensInListCore(originalToken As SyntaxToken, newTokens As IEnumerable(Of SyntaxToken), insertBefore As Boolean) As SyntaxNode
Return SyntaxReplacer.InsertTokenInList(Me, originalToken, newTokens, insertBefore).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function ReplaceTriviaInListCore(originalTrivia As SyntaxTrivia, newTrivia As IEnumerable(Of SyntaxTrivia)) As SyntaxNode
Return SyntaxReplacer.ReplaceTriviaInList(Me, originalTrivia, newTrivia).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function InsertTriviaInListCore(originalTrivia As SyntaxTrivia, newTrivia As IEnumerable(Of SyntaxTrivia), insertBefore As Boolean) As SyntaxNode
Return SyntaxReplacer.InsertTriviaInList(Me, originalTrivia, newTrivia, insertBefore).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
Protected Overrides Function NormalizeWhitespaceCore(indentation As String, eol As String, elasticTrivia As Boolean) As SyntaxNode
Return SyntaxNormalizer.Normalize(Me, indentation, eol, elasticTrivia, useDefaultCasing:=False).AsRootOfNewTreeWithOptionsFrom(Me.SyntaxTree)
End Function
#End Region
''' <summary>
''' Gets the location of this node.
''' </summary>
Public Shadows Function GetLocation() As Location
' Note that we want to return 'no location' for all nodes from embedded syntax trees
If Me.SyntaxTree IsNot Nothing Then
Dim tree = Me.SyntaxTree
If tree.IsEmbeddedSyntaxTree Then
Return New EmbeddedTreeLocation(tree.GetEmbeddedKind, Me.Span)
ElseIf tree.IsMyTemplate Then
Return New MyTemplateLocation(tree, Me.Span)
End If
End If
Return New SourceLocation(Me)
End Function
''' <summary>
''' Gets a SyntaxReference for this syntax node. SyntaxReferences can be used to regain access to a
''' syntax node without keeping the entire tree and source text in memory.
''' </summary>
Friend Shadows Function GetReference() As SyntaxReference
Return SyntaxTree.GetReference(Me)
End Function
''' <summary>
''' Gets a list of all the diagnostics in the sub tree that has this node as its root.
''' This method does not filter diagnostics based on compiler options like nowarn, warnaserror etc.
''' </summary>
Public Shadows Function GetDiagnostics() As IEnumerable(Of Diagnostic)
Return SyntaxTree.GetDiagnostics(Me)
End Function
Protected Overrides Function IsEquivalentToCore(node As SyntaxNode, Optional topLevel As Boolean = False) As Boolean
Return SyntaxFactory.AreEquivalent(Me, DirectCast(node, VisualBasicSyntaxNode), topLevel)
End Function
Friend Overrides Function ShouldCreateWeakList() As Boolean
Return TypeOf Me Is MethodBlockBaseSyntax
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Test/Core/Syntax/ISyntaxNodeKindProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Text;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public interface ISyntaxNodeKindProvider
{
string Kind(object node);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public interface ISyntaxNodeKindProvider
{
string Kind(object node);
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenFunctionPointersTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.CSharp.UnitTests.FunctionPointerUtilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenFunctionPointersTests : CSharpTestBase
{
private CompilationVerifier CompileAndVerifyFunctionPointers(
CSharpTestSource sources,
MetadataReference[]? references = null,
Action<ModuleSymbol>? symbolValidator = null,
string? expectedOutput = null,
TargetFramework targetFramework = TargetFramework.Standard,
CSharpCompilationOptions? options = null)
{
var comp = CreateCompilation(
sources,
references,
parseOptions: TestOptions.Regular9,
options: options ?? (expectedOutput is null ? TestOptions.UnsafeReleaseDll : TestOptions.UnsafeReleaseExe),
targetFramework: targetFramework);
return CompileAndVerify(comp, symbolValidator: symbolValidator, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
private static CSharpCompilation CreateCompilationWithFunctionPointers(CSharpTestSource source, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null, TargetFramework? targetFramework = null)
{
return CreateCompilation(source, references: references, options: options ?? TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, targetFramework: targetFramework ?? TargetFramework.NetCoreApp);
}
private CompilationVerifier CompileAndVerifyFunctionPointersWithIl(string source, string ilStub, Action<ModuleSymbol>? symbolValidator = null, string? expectedOutput = null)
{
var comp = CreateCompilationWithIL(source, ilStub, parseOptions: TestOptions.Regular9, options: expectedOutput is null ? TestOptions.UnsafeReleaseDll : TestOptions.UnsafeReleaseExe);
return CompileAndVerify(comp, expectedOutput: expectedOutput, symbolValidator: symbolValidator, verify: Verification.Skipped);
}
private static CSharpCompilation CreateCompilationWithFunctionPointersAndIl(string source, string ilStub, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null)
{
return CreateCompilationWithIL(source, ilStub, references: references, options: options ?? TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
}
[Theory]
[InlineData("", CallingConvention.Default)]
[InlineData("managed", CallingConvention.Default)]
[InlineData("unmanaged[Cdecl]", CallingConvention.CDecl)]
[InlineData("unmanaged[Thiscall]", CallingConvention.ThisCall)]
[InlineData("unmanaged[Stdcall]", CallingConvention.Standard)]
[InlineData("unmanaged[Fastcall]", CallingConvention.FastCall)]
[InlineData("unmanaged[@Cdecl]", CallingConvention.CDecl)]
[InlineData("unmanaged[@Thiscall]", CallingConvention.ThisCall)]
[InlineData("unmanaged[@Stdcall]", CallingConvention.Standard)]
[InlineData("unmanaged[@Fastcall]", CallingConvention.FastCall)]
[InlineData("unmanaged", CallingConvention.Unmanaged)]
internal void CallingConventions(string conventionString, CallingConvention expectedConvention)
{
var verifier = CompileAndVerifyFunctionPointers($@"
class C
{{
public unsafe delegate* {conventionString}<string, int> M() => throw null;
}}", symbolValidator: symbolValidator, targetFramework: TargetFramework.NetCoreApp);
symbolValidator(GetSourceModule(verifier));
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ReturnType;
VerifyFunctionPointerSymbol(funcPtr, expectedConvention,
(RefKind.None, IsSpecialType(SpecialType.System_Int32)),
(RefKind.None, IsSpecialType(SpecialType.System_String)));
}
}
[Fact]
public void MultipleCallingConventions()
{
var comp = CompileAndVerifyFunctionPointers(@"
#pragma warning disable CS0168
unsafe class C
{
public delegate* unmanaged[Thiscall, Stdcall]<void> M() => throw null;
}", symbolValidator: symbolValidator, targetFramework: TargetFramework.NetCoreApp);
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ReturnType;
AssertEx.Equal("delegate* unmanaged[Thiscall, Stdcall]<System.Void modopt(System.Runtime.CompilerServices.CallConvThiscall) modopt(System.Runtime.CompilerServices.CallConvStdcall)>", funcPtr.ToTestDisplayString());
Assert.Equal(CallingConvention.Unmanaged, ((FunctionPointerTypeSymbol)funcPtr).Signature.CallingConvention);
}
}
[Fact]
public void RefParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
class C
{
public unsafe void M(delegate*<ref C, ref string, ref int[]> param1) => throw null;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ParameterTypesWithAnnotations[0].Type;
VerifyFunctionPointerSymbol(funcPtr, CallingConvention.Default,
(RefKind.Ref, IsArrayType(IsSpecialType(SpecialType.System_Int32))),
(RefKind.Ref, IsTypeName("C")),
(RefKind.Ref, IsSpecialType(SpecialType.System_String)));
}
}
[Fact]
public void OutParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
class C
{
public unsafe void M(delegate*<out C, out string, ref int[]> param1) => throw null;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ParameterTypesWithAnnotations[0].Type;
VerifyFunctionPointerSymbol(funcPtr, CallingConvention.Default,
(RefKind.Ref, IsArrayType(IsSpecialType(SpecialType.System_Int32))),
(RefKind.Out, IsTypeName("C")),
(RefKind.Out, IsSpecialType(SpecialType.System_String)));
}
}
[Fact]
public void NestedFunctionPointers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public class C
{
public unsafe delegate* unmanaged[Cdecl]<delegate* unmanaged[Stdcall]<int, void>, void> M(delegate*<C, delegate*<S>> param1) => throw null;
}
public struct S
{
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var returnType = m.ReturnType;
VerifyFunctionPointerSymbol(returnType, CallingConvention.CDecl,
(RefKind.None, IsVoidType()),
(RefKind.None, IsFunctionPointerTypeSymbol(CallingConvention.Standard,
(RefKind.None, IsVoidType()),
(RefKind.None, IsSpecialType(SpecialType.System_Int32)))
));
var paramType = m.Parameters[0].Type;
VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
(RefKind.None, IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsTypeName("S")))),
(RefKind.None, IsTypeName("C")));
}
}
[Fact]
public void InModifier()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public class C
{
public unsafe void M(delegate*<in string, in int, ref readonly bool> param) {}
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var paramType = m.Parameters[0].Type;
VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Boolean)),
(RefKind.In, IsSpecialType(SpecialType.System_String)),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
}
}
[Fact]
public void BadReturnModReqs()
{
var il = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field public method int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& *() 'Field1'
.field public method int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field2'
.field public method int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field3'
.field public method int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field4'
.field public method int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field5'
.field public method int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)& *() 'Field6'
.field public method int32 modreq([mscorlib]System.Object)& *() 'Field7'
.field public method int32& modreq([mscorlib]System.Object) *() 'Field8'
.field static public method method int32 modreq([mscorlib]System.Object) *() *() 'Field9'
}
";
var source = @"
class D
{
void M(C c)
{
ref int i1 = ref c.Field1();
ref int i2 = ref c.Field2();
c.Field1 = c.Field1;
c.Field2 = c.Field2;
}
}";
var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
comp.VerifyDiagnostics(
// (6,26): error CS0570: 'delegate*<ref int>' is not supported by the language
// ref int i1 = ref c.Field1();
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1()").WithArguments("delegate*<ref int>").WithLocation(6, 26),
// (6,28): error CS0570: 'C.Field1' is not supported by the language
// ref int i1 = ref c.Field1();
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(6, 28),
// (7,26): error CS0570: 'delegate*<ref int>' is not supported by the language
// ref int i2 = ref c.Field2();
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field2()").WithArguments("delegate*<ref int>").WithLocation(7, 26),
// (7,28): error CS0570: 'C.Field2' is not supported by the language
// ref int i2 = ref c.Field2();
Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(7, 28),
// (8,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 11),
// (8,22): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 22),
// (9,11): error CS0570: 'C.Field2' is not supported by the language
// c.Field2 = c.Field2;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(9, 11),
// (9,22): error CS0570: 'C.Field2' is not supported by the language
// c.Field2 = c.Field2;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(9, 22)
);
var c = comp.GetTypeByMetadataName("C");
for (int i = 1; i <= 9; i++)
{
var field = c.GetField($"Field{i}");
Assert.True(field.HasUseSiteError);
Assert.True(field.HasUnsupportedMetadata);
Assert.Equal(TypeKind.FunctionPointer, field.Type.TypeKind);
var signature = ((FunctionPointerTypeSymbol)field.Type).Signature;
Assert.True(signature.HasUseSiteError);
Assert.True(signature.HasUnsupportedMetadata);
Assert.True(field.Type.HasUseSiteError);
Assert.True(field.Type.HasUnsupportedMetadata);
}
}
[Fact]
public void BadParamModReqs()
{
var il = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field1'
.field public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field2'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field3'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field4'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)&) 'Field5'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)&) 'Field6'
.field public method void *(int32& modreq([mscorlib]System.Object)) 'Field7'
.field public method void *(int32 modreq([mscorlib]System.Object)&) 'Field8'
.field public method void *(method void *(int32 modreq([mscorlib]System.Object))) 'Field9'
}
";
var source = @"
class D
{
void M(C c)
{
int i = 1;
c.Field1(ref i);
c.Field1(in i);
c.Field1(out i);
c.Field1 = c.Field1;
}
}";
var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
comp.VerifyDiagnostics(
// (7,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
// c.Field1(ref i);
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(ref i)").WithArguments("delegate*<in int, void>").WithLocation(7, 9),
// (7,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1(ref i);
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(7, 11),
// (8,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
// c.Field1(in i);
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(in i)").WithArguments("delegate*<in int, void>").WithLocation(8, 9),
// (8,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1(in i);
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 11),
// (9,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
// c.Field1(out i);
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(out i)").WithArguments("delegate*<in int, void>").WithLocation(9, 9),
// (9,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1(out i);
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(9, 11),
// (10,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(10, 11),
// (10,22): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(10, 22)
);
var c = comp.GetTypeByMetadataName("C");
for (int i = 1; i <= 9; i++)
{
var field = c.GetField($"Field{i}");
Assert.True(field.HasUseSiteError);
Assert.True(field.HasUnsupportedMetadata);
Assert.Equal(TypeKind.FunctionPointer, field.Type.TypeKind);
var signature = ((FunctionPointerTypeSymbol)field.Type).Signature;
Assert.True(signature.HasUseSiteError);
Assert.True(signature.HasUnsupportedMetadata);
Assert.True(field.Type.HasUseSiteError);
Assert.True(field.Type.HasUnsupportedMetadata);
}
}
[Fact]
public void ValidModReqsAndOpts()
{
var il = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field static public method int32& modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field1'
.field static public method int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field2'
.field static public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modopt([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field3'
.field static public method void *(int32& modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field4'
.field static public method void *(int32& modopt([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field5'
.field static public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field6'
}
";
var source = @"
using System;
unsafe class D
{
static int i = 1;
static ref readonly int M()
{
return ref i;
}
static void MIn(in int param)
{
Console.Write(param);
}
static void MOut(out int param)
{
param = i;
}
static void Main()
{
TestRefReadonly();
TestOut();
TestIn();
}
static void TestRefReadonly()
{
C.Field1 = &M;
ref readonly int local1 = ref C.Field1();
Console.Write(local1);
i = 2;
Console.Write(local1);
C.Field2 = &M;
i = 3;
ref readonly int local2 = ref C.Field2();
Console.Write(local2);
i = 4;
Console.Write(local2);
}
static void TestOut()
{
C.Field3 = &MOut;
i = 5;
C.Field3(out int local);
Console.Write(local);
C.Field5 = &MOut;
i = 6;
C.Field5(out local);
Console.Write(local);
}
static void TestIn()
{
i = 7;
C.Field4 = &MIn;
C.Field4(in i);
i = 8;
C.Field6 = &MIn;
C.Field6(in i);
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "12345678");
verifier.VerifyIL("D.TestRefReadonly", @"
{
// Code size 87 (0x57)
.maxstack 2
IL_0000: ldftn ""ref readonly int D.M()""
IL_0006: stsfld ""delegate*<ref readonly int> C.Field1""
IL_000b: ldsfld ""delegate*<ref readonly int> C.Field1""
IL_0010: calli ""delegate*<ref readonly int>""
IL_0015: dup
IL_0016: ldind.i4
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ldc.i4.2
IL_001d: stsfld ""int D.i""
IL_0022: ldind.i4
IL_0023: call ""void System.Console.Write(int)""
IL_0028: ldftn ""ref readonly int D.M()""
IL_002e: stsfld ""delegate*<ref readonly int> C.Field2""
IL_0033: ldc.i4.3
IL_0034: stsfld ""int D.i""
IL_0039: ldsfld ""delegate*<ref readonly int> C.Field2""
IL_003e: calli ""delegate*<ref readonly int>""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: call ""void System.Console.Write(int)""
IL_004a: ldc.i4.4
IL_004b: stsfld ""int D.i""
IL_0050: ldind.i4
IL_0051: call ""void System.Console.Write(int)""
IL_0056: ret
}
");
verifier.VerifyIL("D.TestOut", @"
{
// Code size 75 (0x4b)
.maxstack 2
.locals init (int V_0, //local
delegate*<out int, void> V_1,
delegate*<out int, void> V_2)
IL_0000: ldftn ""void D.MOut(out int)""
IL_0006: stsfld ""delegate*<out int, void> C.Field3""
IL_000b: ldc.i4.5
IL_000c: stsfld ""int D.i""
IL_0011: ldsfld ""delegate*<out int, void> C.Field3""
IL_0016: stloc.1
IL_0017: ldloca.s V_0
IL_0019: ldloc.1
IL_001a: calli ""delegate*<out int, void>""
IL_001f: ldloc.0
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ldftn ""void D.MOut(out int)""
IL_002b: stsfld ""delegate*<out int, void> C.Field5""
IL_0030: ldc.i4.6
IL_0031: stsfld ""int D.i""
IL_0036: ldsfld ""delegate*<out int, void> C.Field5""
IL_003b: stloc.2
IL_003c: ldloca.s V_0
IL_003e: ldloc.2
IL_003f: calli ""delegate*<out int, void>""
IL_0044: ldloc.0
IL_0045: call ""void System.Console.Write(int)""
IL_004a: ret
}
");
verifier.VerifyIL("D.TestIn", @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (delegate*<in int, void> V_0,
delegate*<in int, void> V_1)
IL_0000: ldc.i4.7
IL_0001: stsfld ""int D.i""
IL_0006: ldftn ""void D.MIn(in int)""
IL_000c: stsfld ""delegate*<in int, void> C.Field4""
IL_0011: ldsfld ""delegate*<in int, void> C.Field4""
IL_0016: stloc.0
IL_0017: ldsflda ""int D.i""
IL_001c: ldloc.0
IL_001d: calli ""delegate*<in int, void>""
IL_0022: ldc.i4.8
IL_0023: stsfld ""int D.i""
IL_0028: ldftn ""void D.MIn(in int)""
IL_002e: stsfld ""delegate*<in int, void> C.Field6""
IL_0033: ldsfld ""delegate*<in int, void> C.Field6""
IL_0038: stloc.1
IL_0039: ldsflda ""int D.i""
IL_003e: ldloc.1
IL_003f: calli ""delegate*<in int, void>""
IL_0044: ret
}
");
var c = ((CSharpCompilation)verifier.Compilation).GetTypeByMetadataName("C");
var field = c.GetField("Field1");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field2");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field3");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.Out, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field4");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field5");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.Out, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field6");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
}
[Fact]
public void RefReadonlyIsDoneByRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
private static int i = 0;
static ref readonly int GetI() => ref i;
static void Main()
{
delegate*<ref readonly int> d = &GetI;
ref readonly int local = ref d();
Console.Write(local);
i = 1;
Console.Write(local);
}
}
", expectedOutput: "01");
verifier.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
IL_0000: ldftn ""ref readonly int C.GetI()""
IL_0006: calli ""delegate*<ref readonly int>""
IL_000b: dup
IL_000c: ldind.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: ldc.i4.1
IL_0013: stsfld ""int C.i""
IL_0018: ldind.i4
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ret
}
");
}
[Fact]
public void NestedPointerTypes()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public class C
{
public unsafe delegate* unmanaged[Cdecl]<ref delegate*<ref readonly string>, void> M(delegate*<in delegate* unmanaged[Stdcall]<delegate*<void>>, delegate*<int>> param) => throw null;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var returnType = m.ReturnType;
var paramType = m.Parameters[0].Type;
VerifyFunctionPointerSymbol(returnType, CallingConvention.CDecl,
(RefKind.None, IsVoidType()),
(RefKind.Ref,
IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_String)))));
VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
(RefKind.None,
IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsSpecialType(SpecialType.System_Int32)))),
(RefKind.In,
IsFunctionPointerTypeSymbol(CallingConvention.Standard,
(RefKind.None,
IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsVoidType()))))));
}
}
[Fact]
public void RandomModOptsFromIl()
{
var ilSource = @"
.class public auto ansi beforefieldinit Test1
extends[mscorlib] System.Object
{
.method public hidebysig instance void M(method bool modopt([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.ComImport) *(int32 modopt([mscorlib]System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.PreserveSigAttribute)) param) cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method Test::M
}
";
var compilation = CreateCompilationWithIL(source: "", ilSource, parseOptions: TestOptions.Regular9);
var testClass = compilation.GetTypeByMetadataName("Test1")!;
var m = testClass.GetMethod("M");
Assert.NotNull(m);
var param = (FunctionPointerTypeSymbol)m.Parameters[0].Type;
VerifyFunctionPointerSymbol(param, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Boolean)),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
var returnModifiers = param.Signature.ReturnTypeWithAnnotations.CustomModifiers;
verifyMod(1, "OutAttribute", returnModifiers);
var returnRefModifiers = param.Signature.RefCustomModifiers;
verifyMod(2, "ComImport", returnRefModifiers);
var paramModifiers = param.Signature.ParameterTypesWithAnnotations[0].CustomModifiers;
verifyMod(1, "AllowReversePInvokeCallsAttribute", paramModifiers);
var paramRefModifiers = param.Signature.Parameters[0].RefCustomModifiers;
verifyMod(2, "PreserveSigAttribute", paramRefModifiers);
static void verifyMod(int length, string expectedTypeName, ImmutableArray<CustomModifier> customMods)
{
Assert.Equal(length, customMods.Length);
var firstMod = customMods[0];
Assert.True(firstMod.IsOptional);
Assert.Equal(expectedTypeName, ((CSharpCustomModifier)firstMod).ModifierSymbol.Name);
if (length > 1)
{
Assert.Equal(2, customMods.Length);
var inMod = customMods[1];
Assert.False(inMod.IsOptional);
Assert.True(((CSharpCustomModifier)inMod).ModifierSymbol.IsWellKnownTypeInAttribute());
}
}
}
[Fact]
public void MultipleFunctionPointerArguments()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public unsafe class C
{
public void M(delegate*<ref int, ref bool> param1,
delegate*<ref int, ref bool> param2,
delegate*<ref int, ref bool> param3,
delegate*<ref int, ref bool> param4,
delegate*<ref int, ref bool> param5) {}
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
foreach (var param in m.Parameters)
{
VerifyFunctionPointerSymbol(param.Type, CallingConvention.Default,
(RefKind.Ref, IsSpecialType(SpecialType.System_Boolean)),
(RefKind.Ref, IsSpecialType(SpecialType.System_Int32)));
}
}
}
[Fact]
public void FunctionPointersInProperties()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public unsafe class C
{
public delegate*<string, void> Prop1 { get; set; }
public delegate* unmanaged[Stdcall]<int> Prop2 { get => throw null; set => throw null; }
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
verifier.VerifyIL("C.Prop1.get", expectedIL: @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""delegate*<string, void> C.<Prop1>k__BackingField""
IL_0006: ret
}
");
verifier.VerifyIL("C.Prop1.set", expectedIL: @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""delegate*<string, void> C.<Prop1>k__BackingField""
IL_0007: ret
}
");
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
validateProperty((PropertySymbol)c.GetProperty((string)"Prop1"), IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.None, IsSpecialType(SpecialType.System_String))));
validateProperty(c.GetProperty("Prop2"), IsFunctionPointerTypeSymbol(CallingConvention.Standard,
(RefKind.None, IsSpecialType(SpecialType.System_Int32))));
static void validateProperty(PropertySymbol property, Action<TypeSymbol> verifier)
{
verifier(property.Type);
verifier(property.GetMethod.ReturnType);
verifier(property.SetMethod.GetParameterType(0));
}
}
}
[Fact]
public void FunctionPointersInFields()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public unsafe class C
{
public readonly delegate*<C, C> _field;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
VerifyFunctionPointerSymbol(c.GetField("_field").Type, CallingConvention.Default,
(RefKind.None, IsTypeName("C")),
(RefKind.None, IsTypeName("C")));
}
}
[Fact]
public void CustomModifierOnReturnType()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends[mscorlib] System.Object
{
.method public hidebysig newslot virtual instance method bool modopt([mscorlib]System.Object)& *(int32&) M() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::M
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
}
";
var source = @"
class D : C
{
public unsafe override delegate*<ref int, ref bool> M() => throw null;
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub: ilSource, symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var d = module.GlobalNamespace.GetMember<NamedTypeSymbol>("D");
var m = d.GetMethod("M");
var returnTypeWithAnnotations = ((FunctionPointerTypeSymbol)m.ReturnType).Signature.ReturnTypeWithAnnotations;
Assert.Equal(1, returnTypeWithAnnotations.CustomModifiers.Length);
Assert.Equal(SpecialType.System_Object, returnTypeWithAnnotations.CustomModifiers[0].Modifier.SpecialType);
}
}
[Fact]
public void UnsupportedCallingConventionInMetadata()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field public method vararg void*() 'Field'
.field private method vararg void *() '<Prop>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 )
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
.method public hidebysig specialname instance method vararg void *()
get_Prop() cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld method vararg void *() C::'<Prop>k__BackingField'
IL_0006: ret
} // end of method C::get_Prop
.method public hidebysig specialname instance void
set_Prop(method vararg void *() 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld method vararg void *() C::'<Prop>k__BackingField'
IL_0007: ret
} // end of method C::set_Prop
.property instance method vararg void *()
Prop()
{
.get instance method vararg void *() C::get_Prop()
.set instance void C::set_Prop(method vararg void *())
} // end of property C::Prop
} // end of class C
";
var source = @"
unsafe class D
{
void M(C c)
{
c.Field(__arglist(1, 2));
c.Field(1, 2, 3);
c.Field();
c.Field = c.Field;
c.Prop();
c.Prop = c.Prop;
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(source, ilSource);
comp.VerifyDiagnostics(
// (6,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(__arglist(1, 2));
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Field(__arglist(1, 2))").WithArguments("delegate* unmanaged[]<void>").WithLocation(6, 9),
// (6,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(__arglist(1, 2));
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(6, 11),
// (7,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(1, 2, 3);
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Field(1, 2, 3)").WithArguments("delegate* unmanaged[]<void>").WithLocation(7, 9),
// (7,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(1, 2, 3);
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(7, 11),
// (8,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Field()").WithArguments("delegate* unmanaged[]<void>").WithLocation(8, 9),
// (8,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(8, 11),
// (9,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field = c.Field;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(9, 11),
// (9,21): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field = c.Field;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(9, 21),
// (10,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Prop()").WithArguments("delegate* unmanaged[]<void>").WithLocation(10, 9),
// (10,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(10, 11),
// (11,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop = c.Prop;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(11, 11),
// (11,20): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop = c.Prop;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(11, 20)
);
var c = comp.GetTypeByMetadataName("C");
var prop = c.GetProperty("Prop");
VerifyFunctionPointerSymbol(prop.Type, CallingConvention.ExtraArguments,
(RefKind.None, IsVoidType()));
Assert.True(prop.Type.HasUseSiteError);
var field = c.GetField("Field");
var type = (FunctionPointerTypeSymbol)field.Type;
VerifyFunctionPointerSymbol(type, CallingConvention.ExtraArguments,
(RefKind.None, IsVoidType()));
Assert.True(type.HasUseSiteError);
Assert.True(type.Signature.IsVararg);
}
[Fact]
public void StructWithFunctionPointerThatReferencesStruct()
{
CompileAndVerifyFunctionPointers(@"
unsafe struct S
{
public delegate*<S, S> Field;
public delegate*<S, S> Property { get; set; }
}");
}
[Fact]
public void CalliOnParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *() LoadPtr () cil managed
{
nop
ldftn void Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
void Called () cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
class Caller
{
public unsafe static void Main()
{
Call(Program.LoadPtr());
}
public unsafe static void Call(delegate*<void> ptr)
{
ptr();
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
verifier.VerifyIL("Caller.Call(delegate*<void>)", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: calli ""delegate*<void>""
IL_0006: ret
}");
}
[Fact]
public void CalliOnFieldNoArgs()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *() LoadPtr () cil managed
{
nop
ldftn void Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
void Called () cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
unsafe class Caller
{
static delegate*<void> _field;
public unsafe static void Main()
{
_field = Program.LoadPtr();
Call();
}
public unsafe static void Call()
{
_field();
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
verifier.VerifyIL("Caller.Call()", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldsfld ""delegate*<void> Caller._field""
IL_0005: calli ""delegate*<void>""
IL_000a: ret
}");
}
[Fact]
public void CalliOnFieldArgs()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *(string) LoadPtr () cil managed
{
nop
ldftn void Program::Called(string)
ret
} // end of method Program::Main
.method private hidebysig static
void Called (string arg) cil managed
{
nop
ldarg.0
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
unsafe class Caller
{
static delegate*<string, void> _field;
public unsafe static void Main()
{
_field = Program.LoadPtr();
Call();
}
public unsafe static void Call()
{
_field(""Called"");
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
verifier.VerifyIL("Caller.Call()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (delegate*<string, void> V_0)
IL_0000: ldsfld ""delegate*<string, void> Caller._field""
IL_0005: stloc.0
IL_0006: ldstr ""Called""
IL_000b: ldloc.0
IL_000c: calli ""delegate*<string, void>""
IL_0011: ret
}");
}
[Theory]
[InlineData("Cdecl", "Cdecl")]
[InlineData("Stdcall", "StdCall")]
public void UnmanagedCallingConventions(string unmanagedConvention, string enumConvention)
{
// Use IntPtr Marshal.GetFunctionPointerForDelegate<TDelegate>(TDelegate delegate) to
// get a function pointer around a native calling convention
var source = $@"
using System;
using System.Runtime.InteropServices;
public unsafe class UnmanagedFunctionPointer
{{
[UnmanagedFunctionPointer(CallingConvention.{enumConvention})]
public delegate string CombineStrings(string s1, string s2);
private static string CombineStringsImpl(string s1, string s2)
{{
return s1 + s2;
}}
public static delegate* unmanaged[{unmanagedConvention}]<string, string, string> GetFuncPtr(out CombineStrings del)
{{
del = CombineStringsImpl;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[{unmanagedConvention}]<string, string, string>)ptr;
}}
}}
class Caller
{{
public unsafe static void Main()
{{
Call(UnmanagedFunctionPointer.GetFuncPtr(out var del));
GC.KeepAlive(del);
}}
public unsafe static void Call(delegate* unmanaged[{unmanagedConvention}]<string, string, string> ptr)
{{
Console.WriteLine(ptr(""Hello"", "" World""));
}}
}}";
var verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "Hello World");
verifier.VerifyIL($"Caller.Call", $@"
{{
// Code size 24 (0x18)
.maxstack 3
.locals init (delegate* unmanaged[{unmanagedConvention}]<string, string, string> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldstr ""Hello""
IL_0007: ldstr "" World""
IL_000c: ldloc.0
IL_000d: calli ""delegate* unmanaged[{unmanagedConvention}]<string, string, string>""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}}");
}
[ConditionalTheory(typeof(CoreClrOnly))]
[InlineData("", "")]
[InlineData("[Cdecl]", "typeof(System.Runtime.CompilerServices.CallConvCdecl)")]
[InlineData("[Stdcall]", "typeof(System.Runtime.CompilerServices.CallConvStdcall)")]
public void UnmanagedCallingConventions_UnmanagedCallersOnlyAttribute(string delegateConventionString, string attributeArgumentString)
{
var verifier = CompileAndVerifyFunctionPointers(new[] { $@"
using System;
using System.Runtime.InteropServices;
unsafe
{{
delegate* unmanaged{delegateConventionString}<void> ptr = &M;
ptr();
[UnmanagedCallersOnly(CallConvs = new Type[] {{ {attributeArgumentString} }})]
static void M() => Console.Write(1);
}}
", UnmanagedCallersOnlyAttribute }, expectedOutput: "1", targetFramework: TargetFramework.NetCoreApp);
verifier.VerifyIL("<top-level-statements-entry-point>", $@"
{{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void Program.<<Main>$>g__M|0_0()""
IL_0006: calli ""delegate* unmanaged{delegateConventionString}<void>""
IL_000b: ret
}}
");
}
[Fact]
public void FastCall()
{
// Use IntPtr Marshal.GetFunctionPointerForDelegate<TDelegate>(TDelegate delegate) to
// get a function pointer around a native calling convention
var source = @"
using System;
using System.Runtime.InteropServices;
public unsafe class UnmanagedFunctionPointer
{
[UnmanagedFunctionPointer(CallingConvention.FastCall)]
public delegate string CombineStrings(string s1, string s2);
private static string CombineStringsImpl(string s1, string s2)
{
return s1 + s2;
}
public static delegate* unmanaged[Fastcall]<string, string, string> GetFuncPtr(out CombineStrings del)
{
del = CombineStringsImpl;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Fastcall]<string, string, string>)ptr;
}
}
class Caller
{
public unsafe static void Main()
{
Call(UnmanagedFunctionPointer.GetFuncPtr(out var del));
GC.KeepAlive(del);
}
public unsafe static void Call(delegate* unmanaged[Fastcall]<string, string, string> ptr)
{
Console.WriteLine(ptr(""Hello"", "" World""));
}
}";
// Fastcall is only supported by Mono on Windows x86, which we do not have a test leg for.
// Therefore, we just verify that the emitted IL is what we expect.
var verifier = CompileAndVerifyFunctionPointers(source);
verifier.VerifyIL($"Caller.Call(delegate* unmanaged[Fastcall]<string, string, string>)", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (delegate* unmanaged[Fastcall]<string, string, string> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldstr ""Hello""
IL_0007: ldstr "" World""
IL_000c: ldloc.0
IL_000d: calli ""delegate* unmanaged[Fastcall]<string, string, string>""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}");
}
[Fact]
public void ThiscallSimpleReturn()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
using System.Runtime.InteropServices;
unsafe struct S
{
public int i;
public static int GetInt(S* s)
{
return s->i;
}
public static int GetReturn(S* s, int i)
{
return s->i + i;
}
}
unsafe class UnmanagedFunctionPointer
{
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate int SingleParam(S* s);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate int MultipleParams(S* s, int i);
public static delegate* unmanaged[Thiscall]<S*, int> GetFuncPtrSingleParam(out SingleParam del)
{
del = S.GetInt;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, int>)ptr;
}
public static delegate* unmanaged[Thiscall]<S*, int, int> GetFuncPtrMultipleParams(out MultipleParams del)
{
del = S.GetReturn;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, int, int>)ptr;
}
}
unsafe class C
{
public static void Main()
{
TestSingle();
TestMultiple();
}
public static void TestSingle()
{
S s = new S();
s.i = 1;
var i = UnmanagedFunctionPointer.GetFuncPtrSingleParam(out var del)(&s);
Console.Write(i);
GC.KeepAlive(del);
}
public static void TestMultiple()
{
S s = new S();
s.i = 2;
var i = UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out var del)(&s, 3);
Console.Write(i);
GC.KeepAlive(del);
}
}", expectedOutput: @"15");
verifier.VerifyIL("C.TestSingle()", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (S V_0, //s
UnmanagedFunctionPointer.SingleParam V_1, //del
delegate* unmanaged[Thiscall]<S*, int> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, int> UnmanagedFunctionPointer.GetFuncPtrSingleParam(out UnmanagedFunctionPointer.SingleParam)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldloc.2
IL_001c: calli ""delegate* unmanaged[Thiscall]<S*, int>""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ldloc.1
IL_0027: call ""void System.GC.KeepAlive(object)""
IL_002c: ret
}
");
verifier.VerifyIL("C.TestMultiple()", @"
{
// Code size 46 (0x2e)
.maxstack 3
.locals init (S V_0, //s
UnmanagedFunctionPointer.MultipleParams V_1, //del
delegate* unmanaged[Thiscall]<S*, int, int> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.2
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, int, int> UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out UnmanagedFunctionPointer.MultipleParams)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldc.i4.3
IL_001c: ldloc.2
IL_001d: calli ""delegate* unmanaged[Thiscall]<S*, int, int>""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ldloc.1
IL_0028: call ""void System.GC.KeepAlive(object)""
IL_002d: ret
}
");
}
[ConditionalFact(typeof(CoreClrOnly))]
public void Thiscall_UnmanagedCallersOnly()
{
var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
unsafe
{
TestSingle();
TestMultiple();
static void TestSingle()
{
S s = new S();
s.i = 1;
delegate* unmanaged[Thiscall]<S*, int> ptr = &S.GetInt;
Console.Write(ptr(&s));
}
static void TestMultiple()
{
S s = new S();
s.i = 2;
delegate* unmanaged[Thiscall]<S*, int, int> ptr = &S.GetReturn;
Console.Write(ptr(&s, 3));
}
}
unsafe struct S
{
public int i;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
public static int GetInt(S* s)
{
return s->i;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
public static int GetReturn(S* s, int i)
{
return s->i + i;
}
}
", UnmanagedCallersOnlyAttribute }, expectedOutput: "15", targetFramework: TargetFramework.NetCoreApp);
verifier.VerifyIL(@"Program.<<Main>$>g__TestSingle|0_0()", @"
{
// Code size 38 (0x26)
.maxstack 2
.locals init (S V_0, //s
delegate* unmanaged[Thiscall]<S*, int> V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.i""
IL_0010: ldftn ""int S.GetInt(S*)""
IL_0016: stloc.1
IL_0017: ldloca.s V_0
IL_0019: conv.u
IL_001a: ldloc.1
IL_001b: calli ""delegate* unmanaged[Thiscall]<S*, int>""
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ret
}
");
verifier.VerifyIL(@"Program.<<Main>$>g__TestMultiple|0_1()", @"
{
// Code size 39 (0x27)
.maxstack 3
.locals init (S V_0, //s
delegate* unmanaged[Thiscall]<S*, int, int> V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.2
IL_000b: stfld ""int S.i""
IL_0010: ldftn ""int S.GetReturn(S*, int)""
IL_0016: stloc.1
IL_0017: ldloca.s V_0
IL_0019: conv.u
IL_001a: ldc.i4.3
IL_001b: ldloc.1
IL_001c: calli ""delegate* unmanaged[Thiscall]<S*, int, int>""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ret
}
");
}
[Fact]
public void ThiscallBlittable()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
using System.Runtime.InteropServices;
struct IntWrapper
{
public int i;
public IntWrapper(int i)
{
this.i = i;
}
}
struct ReturnWrapper
{
public int i1;
public float f2;
public ReturnWrapper(int i1, float f2)
{
this.i1 = i1;
this.f2 = f2;
}
}
unsafe struct S
{
public int i;
public static IntWrapper GetInt(S* s)
{
return new IntWrapper(s->i);
}
public static ReturnWrapper GetReturn(S* s, float f)
{
return new ReturnWrapper(s->i, f);
}
}
unsafe class UnmanagedFunctionPointer
{
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate IntWrapper SingleParam(S* s);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate ReturnWrapper MultipleParams(S* s, float f);
public static delegate* unmanaged[Thiscall]<S*, IntWrapper> GetFuncPtrSingleParam(out SingleParam del)
{
del = S.GetInt;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, IntWrapper>)ptr;
}
public static delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> GetFuncPtrMultipleParams(out MultipleParams del)
{
del = S.GetReturn;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper>)ptr;
}
}
unsafe class C
{
public static void Main()
{
TestSingle();
TestMultiple();
}
public static void TestSingle()
{
S s = new S();
s.i = 1;
var intWrapper = UnmanagedFunctionPointer.GetFuncPtrSingleParam(out var del)(&s);
Console.WriteLine(intWrapper.i);
GC.KeepAlive(del);
}
public static void TestMultiple()
{
S s = new S();
s.i = 2;
var returnWrapper = UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out var del)(&s, 3.5f);
Console.Write(returnWrapper.i1);
Console.Write(returnWrapper.f2);
GC.KeepAlive(del);
}
}", expectedOutput: @"
1
23.5
");
verifier.VerifyIL("C.TestSingle()", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (S V_0, //s
UnmanagedFunctionPointer.SingleParam V_1, //del
delegate* unmanaged[Thiscall]<S*, IntWrapper> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, IntWrapper> UnmanagedFunctionPointer.GetFuncPtrSingleParam(out UnmanagedFunctionPointer.SingleParam)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldloc.2
IL_001c: calli ""delegate* unmanaged[Thiscall]<S*, IntWrapper>""
IL_0021: ldfld ""int IntWrapper.i""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: ldloc.1
IL_002c: call ""void System.GC.KeepAlive(object)""
IL_0031: ret
}
");
verifier.VerifyIL("C.TestMultiple()", @"
{
// Code size 66 (0x42)
.maxstack 3
.locals init (S V_0, //s
UnmanagedFunctionPointer.MultipleParams V_1, //del
delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.2
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out UnmanagedFunctionPointer.MultipleParams)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldc.r4 3.5
IL_0020: ldloc.2
IL_0021: calli ""delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper>""
IL_0026: dup
IL_0027: ldfld ""int ReturnWrapper.i1""
IL_002c: call ""void System.Console.Write(int)""
IL_0031: ldfld ""float ReturnWrapper.f2""
IL_0036: call ""void System.Console.Write(float)""
IL_003b: ldloc.1
IL_003c: call ""void System.GC.KeepAlive(object)""
IL_0041: ret
}");
}
[Fact]
public void InvocationOrder()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *(string, string) LoadPtr () cil managed
{
nop
ldftn void Program::Called(string, string)
ret
} // end of method Program::Main
.method private hidebysig static
void Called (
string arg1,
string arg2) cil managed
{
nop
ldarg.0
ldarg.1
call string [mscorlib]System.String::Concat(string, string)
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib]
System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}";
var source = @"
using System;
unsafe class C
{
static delegate*<string, string, void> Prop
{
get
{
Console.WriteLine(""Getter"");
return Program.LoadPtr();
}
}
static delegate*<string, string, void> Method()
{
Console.WriteLine(""Method"");
return Program.LoadPtr();
}
static string GetArg(string val)
{
Console.WriteLine($""Getting {val}"");
return val;
}
static void PropertyOrder()
{
Prop(GetArg(""1""), GetArg(""2""));
}
static void MethodOrder()
{
Method()(GetArg(""3""), GetArg(""4""));
}
static void Main()
{
Console.WriteLine(""Property Access"");
PropertyOrder();
Console.WriteLine(""Method Access"");
MethodOrder();
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Property Access
Getter
Getting 1
Getting 2
12
Method Access
Method
Getting 3
Getting 4
34");
verifier.VerifyIL("C.PropertyOrder", expectedIL: @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (delegate*<string, string, void> V_0)
IL_0000: call ""delegate*<string, string, void> C.Prop.get""
IL_0005: stloc.0
IL_0006: ldstr ""1""
IL_000b: call ""string C.GetArg(string)""
IL_0010: ldstr ""2""
IL_0015: call ""string C.GetArg(string)""
IL_001a: ldloc.0
IL_001b: calli ""delegate*<string, string, void>""
IL_0020: ret
}");
verifier.VerifyIL("C.MethodOrder()", expectedIL: @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (delegate*<string, string, void> V_0)
IL_0000: call ""delegate*<string, string, void> C.Method()""
IL_0005: stloc.0
IL_0006: ldstr ""3""
IL_000b: call ""string C.GetArg(string)""
IL_0010: ldstr ""4""
IL_0015: call ""string C.GetArg(string)""
IL_001a: ldloc.0
IL_001b: calli ""delegate*<string, string, void>""
IL_0020: ret
}");
}
[Fact]
public void ReturnValueUsed()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method string *(string) LoadPtr () cil managed
{
nop
ldftn string Program::Called(string)
ret
} // end of method Program::Main
.method private hidebysig static
string Called (string arg) cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
var retValue = Program.LoadPtr()(""Returned"");
Console.WriteLine(retValue);
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called
Returned");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (delegate*<string, string> V_0)
IL_0000: call ""delegate*<string, string> Program.LoadPtr()""
IL_0005: stloc.0
IL_0006: ldstr ""Returned""
IL_000b: ldloc.0
IL_000c: calli ""delegate*<string, string>""
IL_0011: call ""void System.Console.WriteLine(string)""
IL_0016: ret
}");
}
[Fact]
public void ReturnValueUnused()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method string *(string) LoadPtr () cil managed
{
nop
ldftn string Program::Called(string)
ret
} // end of method Program::Main
.method private hidebysig static
string Called (string arg) cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
Program.LoadPtr()(""Unused"");
Console.WriteLine(""Constant"");
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called
Constant");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<string, string> V_0)
IL_0000: call ""delegate*<string, string> Program.LoadPtr()""
IL_0005: stloc.0
IL_0006: ldstr ""Unused""
IL_000b: ldloc.0
IL_000c: calli ""delegate*<string, string>""
IL_0011: pop
IL_0012: ldstr ""Constant""
IL_0017: call ""void System.Console.WriteLine(string)""
IL_001c: ret
}");
}
[Fact]
public void FunctionPointerReturningFunctionPointer()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method method string *(string) *() LoadPtr () cil managed
{
nop
ldftn method string *(string) Program::Called1()
ret
} // end of method Program::LoadPtr
.method private hidebysig static
method string *(string) Called1 () cil managed
{
nop
ldstr ""Outer pointer""
call void [mscorlib]System.Console::WriteLine(string)
ldftn string Program::Called2(string)
ret
} // end of Program::Called1
.method private hidebysig static
string Called2 (string arg) cil managed
{
nop
ldstr ""Inner pointer""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
ret
} // end of Program::Called2
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
public static void Main()
{
var outer = Program.LoadPtr();
var inner = outer();
Console.WriteLine(inner(""Returned""));
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Outer pointer
Inner pointer
Returned");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (delegate*<string, string> V_0)
IL_0000: call ""delegate*<delegate*<string, string>> Program.LoadPtr()""
IL_0005: calli ""delegate*<delegate*<string, string>>""
IL_000a: stloc.0
IL_000b: ldstr ""Returned""
IL_0010: ldloc.0
IL_0011: calli ""delegate*<string, string>""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: ret
}");
}
[Fact]
public void UserDefinedConversionParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.field public string '_field'
// Methods
.method public hidebysig static
method void *(class Program) LoadPtr () cil managed
{
nop
ldstr ""LoadPtr""
call void [mscorlib]System.Console::WriteLine(string)
ldftn void Program::Called(class Program)
ret
} // end of method Program::LoadPtr
.method private hidebysig static
void Called (class Program arg1) cil managed
{
nop
ldarg.0
ldfld string Program::'_field'
call void [mscorlib]System.Console::WriteLine(string)
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
public static void Main()
{
Program.LoadPtr()(new C());
}
public static implicit operator Program(C c)
{
var p = new Program();
p._field = ""Implicit conversion"";
return p;
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
LoadPtr
Implicit conversion
");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (delegate*<Program, void> V_0)
IL_0000: call ""delegate*<Program, void> Program.LoadPtr()""
IL_0005: stloc.0
IL_0006: newobj ""C..ctor()""
IL_000b: call ""Program C.op_Implicit(C)""
IL_0010: ldloc.0
IL_0011: calli ""delegate*<Program, void>""
IL_0016: ret
}");
}
[Fact]
public void RefParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *(string&) LoadPtr () cil managed
{
nop
ldftn void Program::Called(string&)
ret
} // end of method Program::Main
.method private hidebysig static
void Called (string& arg) cil managed
{
nop
ldarg.0
ldstr ""Ref set""
stind.ref
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
delegate*<ref string, void> pointer = Program.LoadPtr();
string str = ""Unset"";
pointer(ref str);
Console.WriteLine(str);
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Ref set");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (string V_0, //str
delegate*<ref string, void> V_1)
IL_0000: call ""delegate*<ref string, void> Program.LoadPtr()""
IL_0005: ldstr ""Unset""
IL_000a: stloc.0
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: ldloc.1
IL_000f: calli ""delegate*<ref string, void>""
IL_0014: ldloc.0
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}");
}
[Fact]
public void RefReturnUsedByValue()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.field public static string 'field'
// Methods
.method public hidebysig static
method string& *() LoadPtr () cil managed
{
nop
ldftn string& Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
string& Called () cil managed
{
nop
ldsflda string Program::'field'
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
Program.field = ""Field"";
delegate*<ref string> pointer = Program.LoadPtr();
Console.WriteLine(pointer());
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Field");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 1
IL_0000: ldstr ""Field""
IL_0005: stsfld ""string Program.field""
IL_000a: call ""delegate*<ref string> Program.LoadPtr()""
IL_000f: calli ""delegate*<ref string>""
IL_0014: ldind.ref
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}");
}
[Fact]
public void RefReturnUsed()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.field public static string 'field'
// Methods
.method public hidebysig static
method string& *() LoadPtr () cil managed
{
nop
ldftn string& Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
string& Called () cil managed
{
nop
ldsflda string Program::'field'
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
Program.LoadPtr()() = ""Field"";
Console.WriteLine(Program.field);
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Field");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: call ""delegate*<ref string> Program.LoadPtr()""
IL_0005: calli ""delegate*<ref string>""
IL_000a: ldstr ""Field""
IL_000f: stind.ref
IL_0010: ldsfld ""string Program.field""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}
");
}
[Fact]
public void ModifiedReceiverInParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method string *(string) LoadPtr1 () cil managed
{
nop
ldftn string Program::Called1(string)
ret
} // end of method Program::LoadPtr1
.method public hidebysig static
method string *(string) LoadPtr2 () cil managed
{
nop
ldftn string Program::Called2(string)
ret
} // end of method Program::LoadPtr2
.method private hidebysig static
string Called1 (string) cil managed
{
nop
ldstr ""Called Function 1""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
call void [mscorlib]System.Console::WriteLine(string)
ldstr ""Returned From Function 1""
ret
} // end of Program::Called1
.method private hidebysig static
string Called2 (string) cil managed
{
nop
ldstr ""Called Function 2""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
call void [mscorlib]System.Console::WriteLine(string)
ldstr ""Returned From Function 2""
ret
} // end of Program::Called2
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
public static void Main()
{
var ptr = Program.LoadPtr1();
Console.WriteLine(ptr((ptr = Program.LoadPtr2())(""Argument To Function 2"")));
Console.WriteLine(ptr(""Argument To Function 2""));
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called Function 2
Argument To Function 2
Called Function 1
Returned From Function 2
Returned From Function 1
Called Function 2
Argument To Function 2
Returned From Function 2");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (delegate*<string, string> V_0, //ptr
delegate*<string, string> V_1,
delegate*<string, string> V_2)
IL_0000: call ""delegate*<string, string> Program.LoadPtr1()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: stloc.1
IL_0008: call ""delegate*<string, string> Program.LoadPtr2()""
IL_000d: dup
IL_000e: stloc.0
IL_000f: stloc.2
IL_0010: ldstr ""Argument To Function 2""
IL_0015: ldloc.2
IL_0016: calli ""delegate*<string, string>""
IL_001b: ldloc.1
IL_001c: calli ""delegate*<string, string>""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ldloc.0
IL_0027: stloc.1
IL_0028: ldstr ""Argument To Function 2""
IL_002d: ldloc.1
IL_002e: calli ""delegate*<string, string>""
IL_0033: call ""void System.Console.WriteLine(string)""
IL_0038: ret
}");
}
[Fact]
public void Typeof()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
class C
{
static void Main()
{
var t = typeof(delegate*<void>);
Console.WriteLine(t.ToString());
}
}
", expectedOutput: "System.IntPtr");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 21 (0x15)
.maxstack 1
IL_0000: ldtoken ""delegate*<void>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: callvirt ""string object.ToString()""
IL_000f: call ""void System.Console.WriteLine(string)""
IL_0014: ret
}");
}
private const string NoPiaInterfaces = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface I1
{
string GetStr();
}
[ComImport]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58270"")]
public interface I2{}";
[Fact]
public void NoPiaInSignature()
{
var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);
CompileAndVerifyFunctionPointers(@"
unsafe class C
{
public delegate*<I2, I1> M() => throw null;
}", references: new[] { nopiaReference }, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
Assert.Equal(1, module.ReferencedAssemblies.Length);
Assert.NotEqual(nopiaReference.Display, module.ReferencedAssemblies[0].Name);
var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
Assert.NotNull(i1);
Assert.Equal(module, i1.ContainingModule);
var i2 = module.GlobalNamespace.GetTypeMembers("I2").Single();
Assert.NotNull(i2);
Assert.Equal(module, i2.ContainingModule);
var c = module.GlobalNamespace.GetTypeMembers("C").Single();
var m = c.GetMethod("M");
var returnType = (FunctionPointerTypeSymbol)m.ReturnType;
Assert.Equal(i1, returnType.Signature.ReturnType);
Assert.Equal(i2, returnType.Signature.ParameterTypesWithAnnotations[0].Type);
}
}
[Fact]
public void NoPiaInTypeOf()
{
var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);
CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public Type M() => typeof(delegate*<I1, I2>);
}", references: new[] { nopiaReference }, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
Assert.Equal(1, module.ReferencedAssemblies.Length);
Assert.NotEqual(nopiaReference.Display, module.ReferencedAssemblies[0].Name);
var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
Assert.NotNull(i1);
Assert.Equal(module, i1.ContainingModule);
var i2 = module.GlobalNamespace.GetTypeMembers("I2").Single();
Assert.NotNull(i2);
Assert.Equal(module, i2.ContainingModule);
}
}
[Fact]
public void NoPiaInCall()
{
var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);
var intermediate = CreateCompilation(@"
using System;
public unsafe class C
{
public delegate*<I1> M() => throw null;
}", references: new[] { nopiaReference }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
CompileAndVerifyFunctionPointers(@"
unsafe class C2
{
public void M(C c)
{
_ = c.M()();
}
}", references: new[] { nopiaReference, intermediate }, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
Assert.Equal(2, module.ReferencedAssemblies.Length);
Assert.DoesNotContain(nopiaReference.Display, module.ReferencedAssemblies.Select(a => a.Name));
Assert.Equal(intermediate.Display, module.ReferencedAssemblies[1].Name);
var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
Assert.NotNull(i1);
Assert.Equal(module, i1.ContainingModule);
}
}
[Fact]
public void InternalsVisibleToAccessChecks_01()
{
var aRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""B"")]
internal class A {}", assemblyName: "A").EmitToImageReference();
var bRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""C"")]
internal class B
{
internal unsafe delegate*<A> M() => throw null;
}", references: new[] { aRef }, assemblyName: "B", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
var cComp = CreateCompilation(@"
internal class C
{
internal unsafe void CM(B b)
{
b.M()();
}
}", references: new[] { aRef, bRef }, assemblyName: "C", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
cComp.VerifyDiagnostics(
// (6,9): error CS0122: 'B.M()' is inaccessible due to its protection level
// b.M()();
Diagnostic(ErrorCode.ERR_BadAccess, "b.M").WithArguments("B.M()").WithLocation(6, 9));
}
[Fact]
public void InternalsVisibleToAccessChecks_02()
{
var aRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
public class A {}", assemblyName: "A").EmitToImageReference();
var bRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""C"")]
internal class B
{
internal unsafe delegate*<A> M() => throw null;
}", references: new[] { aRef }, assemblyName: "B", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
var cComp = CreateCompilation(@"
internal class C
{
internal unsafe void CM(B b)
{
b.M()();
}
}", references: new[] { aRef, bRef }, assemblyName: "C", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
cComp.VerifyDiagnostics();
}
[Fact]
public void AddressOf_Initializer_VoidReturnNoParams()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M() => Console.Write(""1"");
static void Main()
{
delegate*<void> ptr = &M;
ptr();
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void C.M()""
IL_0006: calli ""delegate*<void>""
IL_000b: ret
}");
}
[Fact]
public void AddressOf_Initializer_VoidReturnValueParams()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(string s, int i) => Console.Write(s + i.ToString());
static void Main()
{
delegate*<string, int, void> ptr = &M;
ptr(""1"", 2);
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (delegate*<string, int, void> V_0)
IL_0000: ldftn ""void C.M(string, int)""
IL_0006: stloc.0
IL_0007: ldstr ""1""
IL_000c: ldc.i4.2
IL_000d: ldloc.0
IL_000e: calli ""delegate*<string, int, void>""
IL_0013: ret
}");
}
[Fact]
public void AddressOf_Initializer_VoidReturnRefParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(ref string s, in int i, out object o)
{
Console.Write(s + i.ToString());
s = ""3"";
o = ""4"";
}
static void Main()
{
delegate*<ref string, in int, out object, void> ptr = &M;
string s = ""1"";
int i = 2;
ptr(ref s, in i, out var o);
Console.Write(s);
Console.Write(o);
}
}", expectedOutput: "1234");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 4
.locals init (string V_0, //s
int V_1, //i
object V_2, //o
delegate*<ref string, in int, out object, void> V_3)
IL_0000: ldftn ""void C.M(ref string, in int, out object)""
IL_0006: ldstr ""1""
IL_000b: stloc.0
IL_000c: ldc.i4.2
IL_000d: stloc.1
IL_000e: stloc.3
IL_000f: ldloca.s V_0
IL_0011: ldloca.s V_1
IL_0013: ldloca.s V_2
IL_0015: ldloc.3
IL_0016: calli ""delegate*<ref string, in int, out object, void>""
IL_001b: ldloc.0
IL_001c: call ""void System.Console.Write(string)""
IL_0021: ldloc.2
IL_0022: call ""void System.Console.Write(object)""
IL_0027: ret
}");
}
[Fact]
public void AddressOf_Initializer_ReturnStruct()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe struct S
{
int i;
public S(int i)
{
this.i = i;
}
void M() => Console.Write(i);
static S MakeS(int i) => new S(i);
public static void Main()
{
delegate*<int, S> ptr = &MakeS;
ptr(1).M();
}
}", expectedOutput: "1");
verifier.VerifyIL("S.Main()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (delegate*<int, S> V_0,
S V_1)
IL_0000: ldftn ""S S.MakeS(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, S>""
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: call ""void S.M()""
IL_0016: ret
}");
}
[Fact]
public void AddressOf_Initializer_ReturnClass()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
int i;
public C(int i)
{
this.i = i;
}
void M() => Console.Write(i);
static C MakeC(int i) => new C(i);
public static void Main()
{
delegate*<int, C> ptr = &MakeC;
ptr(1).M();
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
.locals init (delegate*<int, C> V_0)
IL_0000: ldftn ""C C.MakeC(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, C>""
IL_000e: callvirt ""void C.M()""
IL_0013: ret
}");
}
[Fact]
public void AddressOf_Initializer_ContravariantParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(object o, void* i) => Console.Write(o.ToString() + (*((int*)i)).ToString());
static void Main()
{
delegate*<string, int*, void> ptr = &M;
int i = 2;
ptr(""1"", &i);
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //i
delegate*<string, int*, void> V_1)
IL_0000: ldftn ""void C.M(object, void*)""
IL_0006: ldc.i4.2
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldstr ""1""
IL_000e: ldloca.s V_0
IL_0010: conv.u
IL_0011: ldloc.1
IL_0012: calli ""delegate*<string, int*, void>""
IL_0017: ret
}");
}
[Fact]
public void AddressOf_Initializer_CovariantReturns()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
public unsafe class C
{
static string M1() => ""1"";
static int i = 2;
static int* M2()
{
fixed (int* i1 = &i)
{
return i1;
}
}
static void Main()
{
delegate*<object> ptr1 = &M1;
Console.Write(ptr1());
delegate*<void*> ptr2 = &M2;
Console.Write(*(int*)ptr2());
}
}
", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 34 (0x22)
.maxstack 1
IL_0000: ldftn ""string C.M1()""
IL_0006: calli ""delegate*<object>""
IL_000b: call ""void System.Console.Write(object)""
IL_0010: ldftn ""int* C.M2()""
IL_0016: calli ""delegate*<void*>""
IL_001b: ldind.i4
IL_001c: call ""void System.Console.Write(int)""
IL_0021: ret
}");
}
[Fact]
public void AddressOf_FunctionPointerConversionReturn()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static string ToStringer(object o) => o.ToString();
static delegate*<object, string> Returner() => &ToStringer;
public static void Main()
{
delegate*<delegate*<string, object>> ptr = &Returner;
Console.Write(ptr()(""1""));
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<string, object> V_0)
IL_0000: ldftn ""delegate*<object, string> C.Returner()""
IL_0006: calli ""delegate*<delegate*<string, object>>""
IL_000b: stloc.0
IL_000c: ldstr ""1""
IL_0011: ldloc.0
IL_0012: calli ""delegate*<string, object>""
IL_0017: call ""void System.Console.Write(object)""
IL_001c: ret
}
");
}
[Theory]
[InlineData("in")]
[InlineData("ref")]
public void AddressOf_Initializer_Overloads(string refType)
{
var verifier = CompileAndVerifyFunctionPointers($@"
using System;
unsafe class C
{{
static void M(object o) => Console.Write(""object"" + o.ToString());
static void M(string s) => Console.Write(""string"" + s);
static void M({refType} string s) {{ Console.Write(""{refType}"" + s); }}
static void M(int i) => Console.Write(""int"" + i.ToString());
static void Main()
{{
delegate*<string, void> ptr = &M;
ptr(""1"");
string s = ""2"";
delegate*<{refType} string, void> ptr2 = &M;
ptr2({refType} s);
}}
}}", expectedOutput: $"string1{refType}2");
verifier.VerifyIL("C.Main()", expectedIL: $@"
{{
// Code size 40 (0x28)
.maxstack 2
.locals init (string V_0, //s
delegate*<string, void> V_1,
delegate*<{refType} string, void> V_2)
IL_0000: ldftn ""void C.M(string)""
IL_0006: stloc.1
IL_0007: ldstr ""1""
IL_000c: ldloc.1
IL_000d: calli ""delegate*<string, void>""
IL_0012: ldstr ""2""
IL_0017: stloc.0
IL_0018: ldftn ""void C.M({refType} string)""
IL_001e: stloc.2
IL_001f: ldloca.s V_0
IL_0021: ldloc.2
IL_0022: calli ""delegate*<{refType} string, void>""
IL_0027: ret
}}
");
}
[Fact]
public void AddressOf_Initializer_Overloads_Out()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(object o) => Console.Write(""object"" + o.ToString());
static void M(string s) => Console.Write(""string"" + s);
static void M(out string s) { s = ""2""; }
static void M(int i) => Console.Write(""int"" + i.ToString());
static void Main()
{
delegate*<string, void> ptr = &M;
ptr(""1"");
delegate*<out string, void> ptr2 = &M;
ptr2(out string s);
Console.Write(s);
}
}", expectedOutput: $"string12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (string V_0, //s
delegate*<string, void> V_1,
delegate*<out string, void> V_2)
IL_0000: ldftn ""void C.M(string)""
IL_0006: stloc.1
IL_0007: ldstr ""1""
IL_000c: ldloc.1
IL_000d: calli ""delegate*<string, void>""
IL_0012: ldftn ""void C.M(out string)""
IL_0018: stloc.2
IL_0019: ldloca.s V_0
IL_001b: ldloc.2
IL_001c: calli ""delegate*<out string, void>""
IL_0021: ldloc.0
IL_0022: call ""void System.Console.Write(string)""
IL_0027: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var addressOfs = syntaxTree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[0],
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.String, System.Void>",
expectedSymbol: "void C.M(System.String s)");
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[1],
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<out modreq(System.Runtime.InteropServices.OutAttribute) System.String, System.Void>",
expectedSymbol: "void C.M(out System.String s)");
string[] expectedMembers = new[] {
"void C.M(System.Object o)",
"void C.M(System.String s)",
"void C.M(out System.String s)",
"void C.M(System.Int32 i)"
};
AssertEx.Equal(expectedMembers, model.GetMemberGroup(addressOfs[0].Operand).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
AssertEx.Equal(expectedMembers, model.GetMemberGroup(addressOfs[1].Operand).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
}
[Fact]
public void AddressOf_Initializer_Overloads_NoMostSpecific()
{
var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
static class IHelpers
{
public static void M(I1 i1) {}
public static void M(I2 i2) {}
}
class C : I1, I2
{
unsafe static void Main()
{
delegate*<C, void> ptr = &IHelpers.M;
}
}");
comp.VerifyDiagnostics(
// (13,35): error CS0121: The call is ambiguous between the following methods or properties: 'IHelpers.M(I1)' and 'IHelpers.M(I2)'
// delegate*<C, void> ptr = &IHelpers.M;
Diagnostic(ErrorCode.ERR_AmbigCall, "IHelpers.M").WithArguments("IHelpers.M(I1)", "IHelpers.M(I2)").WithLocation(13, 35)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var addressOf = syntaxTree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
expectedSyntax: "&IHelpers.M",
expectedType: null,
expectedConvertedType: "delegate*<C, System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void IHelpers.M(I1 i1)", "void IHelpers.M(I2 i2)" });
}
[Fact]
public void AddressOf_Initializer_Overloads_RefNotCovariant()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
void M1(ref object o) {}
void M2(in object o) {}
void M3(out string s) => throw null;
void M()
{
delegate*<ref string, void> ptr1 = &M1;
delegate*<string, void> ptr2 = &M1;
delegate*<in string, void> ptr3 = &M2;
delegate*<string, void> ptr4 = &M2;
delegate*<out object, void> ptr5 = &M3;
delegate*<string, void> ptr6 = &M3;
}
}");
comp.VerifyDiagnostics(
// (9,44): error CS8757: No overload for 'M1' matches function pointer 'delegate*<ref string, void>'
// delegate*<ref string, void> ptr1 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<ref string, void>").WithLocation(9, 44),
// (10,40): error CS8757: No overload for 'M1' matches function pointer 'delegate*<string, void>'
// delegate*<string, void> ptr2 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<string, void>").WithLocation(10, 40),
// (11,43): error CS8757: No overload for 'M2' matches function pointer 'delegate*<in string, void>'
// delegate*<in string, void> ptr3 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<in string, void>").WithLocation(11, 43),
// (12,40): error CS8757: No overload for 'M2' matches function pointer 'delegate*<string, void>'
// delegate*<string, void> ptr4 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<string, void>").WithLocation(12, 40),
// (13,44): error CS8757: No overload for 'M3' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr5 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<out object, void>").WithLocation(13, 44),
// (14,40): error CS8757: No overload for 'M3' matches function pointer 'delegate*<string, void>'
// delegate*<string, void> ptr6 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<string, void>").WithLocation(14, 40)
);
}
[Fact]
public void AddressOf_RefsMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
void M1(ref object o) {}
void M2(in object o) {}
void M3(out object s) => throw null;
void M4(object s) => throw null;
ref object M5() => throw null;
ref readonly object M6() => throw null;
object M7() => throw null!;
void M()
{
delegate*<object, void> ptr1 = &M1;
delegate*<object, void> ptr2 = &M2;
delegate*<object, void> ptr3 = &M3;
delegate*<ref object, void> ptr4 = &M2;
delegate*<ref object, void> ptr5 = &M3;
delegate*<ref object, void> ptr6 = &M4;
delegate*<in object, void> ptr7 = &M1;
delegate*<in object, void> ptr8 = &M3;
delegate*<in object, void> ptr9 = &M4;
delegate*<out object, void> ptr10 = &M1;
delegate*<out object, void> ptr11 = &M2;
delegate*<out object, void> ptr12 = &M4;
delegate*<object> ptr13 = &M5;
delegate*<object> ptr14 = &M6;
delegate*<ref object> ptr15 = &M6;
delegate*<ref object> ptr16 = &M7;
delegate*<ref readonly object> ptr17 = &M5;
delegate*<ref readonly object> ptr18 = &M7;
}
}");
comp.VerifyDiagnostics(
// (13,40): error CS8757: No overload for 'M1' matches function pointer 'delegate*<object, void>'
// delegate*<object, void> ptr1 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<object, void>").WithLocation(13, 40),
// (14,40): error CS8757: No overload for 'M2' matches function pointer 'delegate*<object, void>'
// delegate*<object, void> ptr2 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<object, void>").WithLocation(14, 40),
// (15,40): error CS8757: No overload for 'M3' matches function pointer 'delegate*<object, void>'
// delegate*<object, void> ptr3 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<object, void>").WithLocation(15, 40),
// (16,44): error CS8757: No overload for 'M2' matches function pointer 'delegate*<ref object, void>'
// delegate*<ref object, void> ptr4 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<ref object, void>").WithLocation(16, 44),
// (17,44): error CS8757: No overload for 'M3' matches function pointer 'delegate*<ref object, void>'
// delegate*<ref object, void> ptr5 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<ref object, void>").WithLocation(17, 44),
// (18,44): error CS8757: No overload for 'M4' matches function pointer 'delegate*<ref object, void>'
// delegate*<ref object, void> ptr6 = &M4;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<ref object, void>").WithLocation(18, 44),
// (19,43): error CS8757: No overload for 'M1' matches function pointer 'delegate*<in object, void>'
// delegate*<in object, void> ptr7 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<in object, void>").WithLocation(19, 43),
// (20,43): error CS8757: No overload for 'M3' matches function pointer 'delegate*<in object, void>'
// delegate*<in object, void> ptr8 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<in object, void>").WithLocation(20, 43),
// (21,43): error CS8757: No overload for 'M4' matches function pointer 'delegate*<in object, void>'
// delegate*<in object, void> ptr9 = &M4;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<in object, void>").WithLocation(21, 43),
// (22,45): error CS8757: No overload for 'M1' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr10 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<out object, void>").WithLocation(22, 45),
// (23,45): error CS8757: No overload for 'M2' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr11 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<out object, void>").WithLocation(23, 45),
// (24,45): error CS8757: No overload for 'M4' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr12 = &M4;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<out object, void>").WithLocation(24, 45),
// (25,36): error CS8758: Ref mismatch between 'C.M5()' and function pointer 'delegate*<object>'
// delegate*<object> ptr13 = &M5;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M5").WithArguments("C.M5()", "delegate*<object>").WithLocation(25, 36),
// (26,36): error CS8758: Ref mismatch between 'C.M6()' and function pointer 'delegate*<object>'
// delegate*<object> ptr14 = &M6;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M6").WithArguments("C.M6()", "delegate*<object>").WithLocation(26, 36),
// (27,40): error CS8758: Ref mismatch between 'C.M6()' and function pointer 'delegate*<ref object>'
// delegate*<ref object> ptr15 = &M6;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M6").WithArguments("C.M6()", "delegate*<ref object>").WithLocation(27, 40),
// (28,40): error CS8758: Ref mismatch between 'C.M7()' and function pointer 'delegate*<ref object>'
// delegate*<ref object> ptr16 = &M7;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M7").WithArguments("C.M7()", "delegate*<ref object>").WithLocation(28, 40),
// (29,49): error CS8758: Ref mismatch between 'C.M5()' and function pointer 'delegate*<ref readonly object>'
// delegate*<ref readonly object> ptr17 = &M5;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M5").WithArguments("C.M5()", "delegate*<ref readonly object>").WithLocation(29, 49),
// (30,49): error CS8758: Ref mismatch between 'C.M7()' and function pointer 'delegate*<ref readonly object>'
// delegate*<ref readonly object> ptr18 = &M7;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M7").WithArguments("C.M7()", "delegate*<ref readonly object>").WithLocation(30, 49)
);
}
[Theory]
[InlineData("unmanaged[Cdecl]", "CDecl")]
[InlineData("unmanaged[Stdcall]", "Standard")]
[InlineData("unmanaged[Thiscall]", "ThisCall")]
public void AddressOf_CallingConventionMustMatch(string callingConventionKeyword, string callingConvention)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
static void M1() {{}}
static void M()
{{
delegate* {callingConventionKeyword}<void> ptr = &M1;
}}
}}");
comp.VerifyDiagnostics(
// (7,41): error CS8786: Calling convention of 'C.M1()' is not compatible with '{callingConvention}'.
// delegate* {callingConventionKeyword}<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1").WithArguments("C.M1()", callingConvention).WithLocation(7, 33 + callingConventionKeyword.Length));
}
[Fact]
public void AddressOf_Assignment()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static string Convert(int i) => i.ToString();
static void Main()
{
delegate*<int, string> ptr;
ptr = &Convert;
Console.Write(ptr(1));
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
.locals init (delegate*<int, string> V_0)
IL_0000: ldftn ""string C.Convert(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, string>""
IL_000e: call ""void System.Console.Write(string)""
IL_0013: ret
}");
}
[Fact]
public void AddressOf_NonStaticMethods()
{
var comp = CreateCompilationWithFunctionPointers(@"
public class C
{
public unsafe void M()
{
delegate*<void> ptr1 = &M;
int? i = null;
delegate*<int> ptr2 = &i.GetValueOrDefault;
}
}", targetFramework: TargetFramework.Standard);
comp.VerifyDiagnostics(
// (6,33): error CS8759: Cannot bind function pointer to 'C.M()' because it is not a static method
// delegate*<void> ptr1 = &M;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "M").WithArguments("C.M()").WithLocation(6, 33),
// (8,32): error CS8759: Cannot bind function pointer to 'int?.GetValueOrDefault()' because it is not a static method
// delegate*<int> ptr2 = &i.GetValueOrDefault;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "i.GetValueOrDefault").WithArguments("int?.GetValueOrDefault()").WithLocation(8, 32)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var declarators = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Initializer!.Value.IsKind(SyntaxKind.AddressOfExpression)).ToArray();
var addressOfs = declarators.Select(d => d.Initializer!.Value).ToArray();
Assert.Equal(2, addressOfs.Length);
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[0],
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
VerifyOperationTreeForNode(comp, model, declarators[0], expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Void> ptr1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr1 = &M')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Void>, IsInvalid, IsImplicit) (Syntax: '&M')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[1],
expectedSyntax: "&i.GetValueOrDefault",
expectedType: null,
expectedConvertedType: "delegate*<System.Int32>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "System.Int32 System.Int32?.GetValueOrDefault()", "System.Int32 System.Int32?.GetValueOrDefault(System.Int32 defaultValue)" });
VerifyOperationTreeForNode(comp, model, declarators[1], expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Int32> ptr2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr2 = &i.G ... ueOrDefault')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &i.GetValueOrDefault')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Int32>, IsInvalid, IsImplicit) (Syntax: '&i.GetValueOrDefault')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&i.GetValueOrDefault')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i.GetValueOrDefault')
Children(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32?, IsInvalid) (Syntax: 'i')
");
}
[Fact]
public void AddressOf_MultipleInvalidOverloads()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static int M(string s) => throw null;
static int M(ref int i) => throw null;
static void M1()
{
delegate*<int, int> ptr = &M;
}
}");
comp.VerifyDiagnostics(
// (9,35): error CS8757: No overload for 'M' matches function pointer 'delegate*<int, int>'
// delegate*<int, int> ptr = &M;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M").WithArguments("M", "delegate*<int, int>").WithLocation(9, 35)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var declarator = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var addressOf = declarator.Initializer!.Value;
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.Int32, System.Int32>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "System.Int32 C.M(System.String s)", "System.Int32 C.M(ref System.Int32 i)" });
VerifyOperationTreeForNode(comp, model, declarator, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Int32, System.Int32> ptr) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr = &M')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Int32, System.Int32>, IsInvalid, IsImplicit) (Syntax: '&M')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
}
[Fact]
public void AddressOf_AmbiguousBestMethod()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M(string s, object o) {}
static void M(object o, string s) {}
static void M1()
{
delegate*<string, string, void> ptr = &M;
}
}");
comp.VerifyDiagnostics(
// (8,48): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(string, object)' and 'C.M(object, string)'
// delegate*<string, string, void> ptr = &M;
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(string, object)", "C.M(object, string)").WithLocation(8, 48)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var declarator = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var addressOf = declarator.Initializer!.Value;
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.String, System.String, System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M(System.String s, System.Object o)", "void C.M(System.Object o, System.String s)" });
VerifyOperationTreeForNode(comp, model, declarator, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.String, System.String, System.Void> ptr) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr = &M')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.String, System.String, System.Void>, IsInvalid, IsImplicit) (Syntax: '&M')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
}
[Fact]
public void AddressOf_AsLvalue()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M() {}
static void M1()
{
delegate*<void> ptr = &M;
&M = ptr;
M2(&M);
M2(ref &M);
ref delegate*<void> ptr2 = ref &M;
}
static void M2(ref delegate*<void> ptr) {}
}");
comp.VerifyDiagnostics(
// (8,9): error CS1656: Cannot assign to 'M' because it is a '&method group'
// &M = ptr;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(8, 9),
// (9,12): error CS1503: Argument 1: cannot convert from '&method group' to 'ref delegate*<void>'
// M2(&M);
Diagnostic(ErrorCode.ERR_BadArgType, "&M").WithArguments("1", "&method group", "ref delegate*<void>").WithLocation(9, 12),
// (10,16): error CS1657: Cannot use 'M' as a ref or out value because it is a '&method group'
// M2(ref &M);
Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(10, 16),
// (11,40): error CS1657: Cannot use 'M' as a ref or out value because it is a '&method group'
// ref delegate*<void> ptr2 = ref &M;
Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(11, 40)
);
}
[Fact]
public void AddressOf_MethodParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(string s) => Console.Write(s);
static void Caller(delegate*<string, void> ptr) => ptr(""1"");
static void Main()
{
Caller(&M);
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void C.M(string)""
IL_0006: call ""void C.Caller(delegate*<string, void>)""
IL_000b: ret
}
");
}
[Fact]
[WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
public void AddressOf_CannotAssignToVoidStar()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M()
{
void* ptr1 = &M;
void* ptr2 = (void*)&M;
}
}");
comp.VerifyDiagnostics(
// (6,22): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'void*'.
// void* ptr1 = &M;
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "void*").WithLocation(6, 22),
// (7,22): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'void*'.
// void* ptr2 = (void*)&M;
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "(void*)&M").WithArguments("M", "void*").WithLocation(7, 22)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[0].Initializer!.Value,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "System.Void*",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
[WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
public void AddressOf_ToDelegateType()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
class C
{
unsafe void M()
{
// This actually gets bound as a binary expression: (Action) & M
Action ptr1 = (Action)&M;
Action ptr2 = (Action)(&M);
Action ptr3 = &M;
}
}");
comp.VerifyDiagnostics(
// (8,24): error CS0119: 'Action' is a type, which is not valid in the given context
// Action ptr1 = (Action)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "Action").WithArguments("System.Action", "type").WithLocation(8, 24),
// (8,24): error CS0119: 'Action' is a type, which is not valid in the given context
// Action ptr1 = (Action)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "Action").WithArguments("System.Action", "type").WithLocation(8, 24),
// (9,23): error CS8811: Cannot convert &method group 'M' to delegate type 'M'.
// Action ptr2 = (Action)(&M);
Diagnostic(ErrorCode.ERR_CannotConvertAddressOfToDelegate, "(Action)(&M)").WithArguments("M", "System.Action").WithLocation(9, 23),
// (10,23): error CS8811: Cannot convert &method group 'M' to delegate type 'M'.
// Action ptr3 = &M;
Diagnostic(ErrorCode.ERR_CannotConvertAddressOfToDelegate, "&M").WithArguments("M", "System.Action").WithLocation(10, 23)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
expectedSyntax: "(&M)",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[2].Initializer!.Value,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "System.Action",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
[WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
public void AddressOf_ToNonDelegateOrPointerType()
{
var comp = CreateCompilationWithFunctionPointers(@"
class C
{
unsafe void M()
{
// This actually gets bound as a binary expression: (C) & M
C ptr1 = (C)&M;
C ptr2 = (C)(&M);
C ptr3 = &M;
}
}");
comp.VerifyDiagnostics(
// (7,19): error CS0119: 'C' is a type, which is not valid in the given context
// C ptr1 = (C)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 19),
// (7,19): error CS0119: 'C' is a type, which is not valid in the given context
// C ptr1 = (C)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 19),
// (8,18): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'C'.
// C ptr2 = (C)(&M);
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "(C)(&M)").WithArguments("M", "C").WithLocation(8, 18),
// (9,18): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'C'.
// C ptr3 = &M;
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "C").WithLocation(9, 18)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
expectedSyntax: "(&M)",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[2].Initializer!.Value,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "C",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
public void AddressOf_ExplicitCastToNonCompatibleFunctionPointerType()
{
var comp = CreateCompilationWithFunctionPointers(@"
class C
{
unsafe void M()
{
var ptr = (delegate*<string>)&M;
}
}
");
comp.VerifyDiagnostics(
// (6,19): error CS8757: No overload for 'M' matches function pointer 'delegate*<string>'
// var ptr = (delegate*<string>)&M;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<string>)&M").WithArguments("M", "delegate*<string>").WithLocation(6, 19)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[0].Initializer!.Value).Expression,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
public void AddressOf_DisallowedInExpressionTree()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
using System.Linq.Expressions;
unsafe class C
{
static string M1(delegate*<string> ptr) => ptr();
static string M2() => string.Empty;
static void M()
{
Expression<Func<string>> a = () => M1(&M2);
Expression<Func<string>> b = () => (&M2)();
}
}");
comp.VerifyDiagnostics(
// (11,47): error CS1944: An expression tree may not contain an unsafe pointer operation
// Expression<Func<string>> a = () => M1(&M2);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&M2").WithLocation(11, 47),
// (11,48): error CS8810: '&' on method groups cannot be used in expression trees
// Expression<Func<string>> a = () => M1(&M2);
Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "M2").WithLocation(11, 48),
// (12,44): error CS0149: Method name expected
// Expression<Func<string>> b = () => (&M2)();
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(&M2)").WithLocation(12, 44)
);
}
[Fact]
public void FunctionPointerTypeUsageInExpressionTree()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
using System.Linq.Expressions;
unsafe class C
{
void M1(delegate*<void> ptr)
{
Expression<Action> a = () => M2(ptr);
}
void M2(void* ptr) {}
}
");
comp.VerifyDiagnostics(
// (8,41): error CS1944: An expression tree may not contain an unsafe pointer operation
// Expression<Action> a = () => M2(ptr);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "ptr").WithLocation(8, 41)
);
}
[Fact]
public void AmbiguousApplicableMethodsAreFilteredForStatic()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
interface I1{}
interface I2
{
string Prop { get; }
}
public unsafe class C : I1, I2 {
void M(I1 i) {}
static void M(I2 i) => Console.Write(i.Prop);
public static void Main() {
delegate*<C, void> a = &M;
a(new C());
}
public string Prop { get => ""I2""; }
}", expectedOutput: "I2");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (delegate*<C, void> V_0)
IL_0000: ldftn ""void C.M(I2)""
IL_0006: stloc.0
IL_0007: newobj ""C..ctor()""
IL_000c: ldloc.0
IL_000d: calli ""delegate*<C, void>""
IL_0012: ret
}
");
}
[Fact]
public void TypeArgumentNotSpecifiedNotInferred()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M1<T>(int i) {}
static T M2<T>() => throw null;
static void M()
{
delegate*<int, void> ptr1 = &C.M1;
delegate*<string> ptr2 = &C.M2;
}
}");
comp.VerifyDiagnostics(
// (9,38): error CS0411: The type arguments for method 'C.M1<T>(int)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// delegate*<int, void> ptr1 = &C.M1;
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "C.M1").WithArguments("C.M1<T>(int)").WithLocation(9, 38),
// (10,35): error CS0411: The type arguments for method 'C.M2<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// delegate*<string> ptr2 = &C.M2;
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "C.M2").WithArguments("C.M2<T>()").WithLocation(10, 35)
);
}
[Fact]
public void TypeArgumentSpecifiedOrInferred()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M1<T>(T t) => Console.Write(t);
static void Main()
{
delegate*<int, void> ptr = &C.M1<int>;
ptr(1);
ptr = &C.M1;
ptr(2);
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<int, void> V_0)
IL_0000: ldftn ""void C.M1<int>(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, void>""
IL_000e: ldftn ""void C.M1<int>(int)""
IL_0014: stloc.0
IL_0015: ldc.i4.2
IL_0016: ldloc.0
IL_0017: calli ""delegate*<int, void>""
IL_001c: ret
}
");
}
[Fact]
public void ReducedExtensionMethod()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe static class CHelper
{
public static void M1(this C c) {}
}
unsafe class C
{
static void M(C c)
{
delegate*<C, void> ptr1 = &c.M1;
delegate*<void> ptr2 = &c.M1;
}
}");
comp.VerifyDiagnostics(
// (10,35): error CS8757: No overload for 'M1' matches function pointer 'delegate*<C, void>'
// delegate*<C, void> ptr1 = &c.M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&c.M1").WithArguments("M1", "delegate*<C, void>").WithLocation(10, 35),
// (11,32): error CS8788: Cannot use an extension method with a receiver as the target of a '&' operator.
// delegate*<void> ptr2 = &c.M1;
Diagnostic(ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, "&c.M1").WithLocation(11, 32)
);
}
[Fact]
public void UnreducedExtensionMethod()
{
var verifier = CompileAndVerifyFunctionPointers(@"
#pragma warning suppress CS0414 // Field never used
using System;
unsafe static class CHelper
{
public static void M1(this C c) => Console.Write(c.i);
}
unsafe class C
{
public int i;
static void Main()
{
delegate*<C, void> ptr = &CHelper.M1;
var c = new C();
c.i = 1;
ptr(c);
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (C V_0, //c
delegate*<C, void> V_1)
IL_0000: ldftn ""void CHelper.M1(C)""
IL_0006: newobj ""C..ctor()""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: stfld ""int C.i""
IL_0013: stloc.1
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: calli ""delegate*<C, void>""
IL_001b: ret
}
");
}
[Fact]
public void BadScenariosDontCrash()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M1() {}
static void M2()
{
&delegate*<void> ptr = &M1;
}
}
");
comp.VerifyDiagnostics(
// (7,18): error CS1514: { expected
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_LbraceExpected, "*").WithLocation(7, 18),
// (7,19): error CS1525: Invalid expression term '<'
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(7, 19),
// (7,20): error CS1525: Invalid expression term 'void'
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "void").WithArguments("void").WithLocation(7, 20),
// (7,26): error CS0103: The name 'ptr' does not exist in the current context
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_NameNotInContext, "ptr").WithArguments("ptr").WithLocation(7, 26)
);
}
[Fact]
public void EmptyMethodGroups()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M1()
{
delegate*<C, void> ptr1 = &C.NonExistent;
delegate*<C, void> ptr2 = &NonExistent;
}
}
");
comp.VerifyDiagnostics(
// (6,38): error CS0117: 'C' does not contain a definition for 'NonExistent'
// delegate*<C, void> ptr1 = &C.NonExistent;
Diagnostic(ErrorCode.ERR_NoSuchMember, "NonExistent").WithArguments("C", "NonExistent").WithLocation(6, 38),
// (7,36): error CS0103: The name 'NonExistent' does not exist in the current context
// delegate*<C, void> ptr2 = &NonExistent;
Diagnostic(ErrorCode.ERR_NameNotInContext, "NonExistent").WithArguments("NonExistent").WithLocation(7, 36)
);
}
[Fact]
public void MultipleApplicableMethods()
{
// This is analogous to MethodBodyModelTests.MethodGroupToDelegate04, where both methods
// are applicable even though D(delegate*<int, void>) is not compatible.
var comp = CreateCompilationWithFunctionPointers(@"
public unsafe class Program1
{
static void Y(long x) { }
static void D(delegate*<int, void> o) { }
static void D(delegate*<long, void> o) { }
void T()
{
D(&Y);
}
}
");
comp.VerifyDiagnostics(
// (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program1.D(delegate*<int, void>)' and 'Program1.D(delegate*<long, void>)'
// D(&Y);
Diagnostic(ErrorCode.ERR_AmbigCall, "D").WithArguments("Program1.D(delegate*<int, void>)", "Program1.D(delegate*<long, void>)").WithLocation(11, 9)
);
}
[Fact]
public void InvalidTopAttributeErrors()
{
using var peStream = new MemoryStream();
var ilBuilder = new BlobBuilder();
var metadataBuilder = new MetadataBuilder();
// SignatureAttributes has the following values:
// 0x00 - default
// 0x10 - Generic
// 0x20 - Instance
// 0x40 - ExplicitThis
// There is no defined meaning for 0x80, the 8th bit here, so this signature is invalid.
// ldftn throws an invalid signature exception at runtime, so we error here for function
// pointers.
DefineInvalidSignatureAttributeIL(metadataBuilder, ilBuilder, headerToUseForM: new SignatureHeader(SignatureKind.Method, SignatureCallingConvention.Default, ((SignatureAttributes)0x80)));
WritePEImage(peStream, metadataBuilder, ilBuilder);
peStream.Position = 0;
var invalidAttributeReference = MetadataReference.CreateFromStream(peStream);
var comp = CreateCompilationWithFunctionPointers(@"
using ConsoleApplication;
unsafe class C
{
static void Main()
{
delegate*<void> ptr = &Program.M;
}
}", references: new[] { invalidAttributeReference });
comp.VerifyEmitDiagnostics(
// (7,32): error CS8776: Calling convention of 'Program.M()' is not compatible with 'Default'.
// delegate*<void> ptr = &Program.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "Program.M").WithArguments("ConsoleApplication.Program.M()", "Default").WithLocation(7, 32)
);
}
[Fact]
public void MissingAddressOf()
{
var comp = CreateCompilationWithFunctionPointers(@"
class C
{
static void M1() {}
static unsafe void M2(delegate*<void> b)
{
delegate*<void> a = M1;
M2(M1);
}
}");
comp.VerifyDiagnostics(
// (7,29): error CS8787: Cannot convert method group to function pointer (Are you missing a '&'?)
// delegate*<void> a = M1;
Diagnostic(ErrorCode.ERR_MissingAddressOf, "M1").WithLocation(7, 29),
// (8,12): error CS8787: Cannot convert method group to function pointer (Are you missing a '&'?)
// M2(M1);
Diagnostic(ErrorCode.ERR_MissingAddressOf, "M1").WithLocation(8, 12)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var variableDeclaratorSyntax = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var methodGroup1 = variableDeclaratorSyntax.Initializer!.Value;
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, methodGroup1,
expectedSyntax: "M1",
expectedType: null,
expectedConvertedType: "delegate*<System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M1()" });
AssertEx.Equal(new[] { "void C.M1()" }, model.GetMemberGroup(methodGroup1).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
VerifyOperationTreeForNode(comp, model, variableDeclaratorSyntax, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Void> a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Void>, IsInvalid, IsImplicit) (Syntax: 'M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M1')
");
}
[Fact]
public void NestedFunctionPointerVariantConversion()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void Printer(object o) => Console.Write(o);
public static void PrintWrapper(delegate*<string, void> printer, string o) => printer(o);
static void Main()
{
delegate*<delegate*<object, void>, string, void> wrapper = &PrintWrapper;
delegate*<object, void> printer = &Printer;
wrapper(printer, ""1"");
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 3
.locals init (delegate*<object, void> V_0, //printer
delegate*<delegate*<object, void>, string, void> V_1)
IL_0000: ldftn ""void C.PrintWrapper(delegate*<string, void>, string)""
IL_0006: ldftn ""void C.Printer(object)""
IL_000c: stloc.0
IL_000d: stloc.1
IL_000e: ldloc.0
IL_000f: ldstr ""1""
IL_0014: ldloc.1
IL_0015: calli ""delegate*<delegate*<object, void>, string, void>""
IL_001a: ret
}
");
}
[Fact]
public void ArraysSupport()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void M(string s) => Console.Write(s);
public static void Main()
{
delegate*<string, void>[] ptrs = new delegate*<string, void>[] { &M, &M };
for (int i = 0; i < ptrs.Length; i++)
{
ptrs[i](i.ToString());
}
}
}", expectedOutput: "01");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (delegate*<string, void>[] V_0, //ptrs
int V_1, //i
delegate*<string, void> V_2)
IL_0000: ldc.i4.2
IL_0001: newarr ""delegate*<string, void>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldftn ""void C.M(string)""
IL_000e: stelem.i
IL_000f: dup
IL_0010: ldc.i4.1
IL_0011: ldftn ""void C.M(string)""
IL_0017: stelem.i
IL_0018: stloc.0
IL_0019: ldc.i4.0
IL_001a: stloc.1
IL_001b: br.s IL_0032
IL_001d: ldloc.0
IL_001e: ldloc.1
IL_001f: ldelem.i
IL_0020: stloc.2
IL_0021: ldloca.s V_1
IL_0023: call ""string int.ToString()""
IL_0028: ldloc.2
IL_0029: calli ""delegate*<string, void>""
IL_002e: ldloc.1
IL_002f: ldc.i4.1
IL_0030: add
IL_0031: stloc.1
IL_0032: ldloc.1
IL_0033: ldloc.0
IL_0034: ldlen
IL_0035: conv.i4
IL_0036: blt.s IL_001d
IL_0038: ret
}
");
}
[Fact]
public void ArrayElementRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void Print() => Console.Write(1);
public static void M(delegate*<void>[] a)
{
ref delegate*<void> ptr = ref a[0];
ptr = &Print;
}
public static void Main()
{
var a = new delegate*<void>[1];
M(a);
a[0]();
}
}");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema ""delegate*<void>""
IL_0007: ldftn ""void C.Print()""
IL_000d: stind.i
IL_000e: ret
}
");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: newarr ""delegate*<void>""
IL_0006: dup
IL_0007: call ""void C.M(delegate*<void>[])""
IL_000c: ldc.i4.0
IL_000d: ldelem.i
IL_000e: calli ""delegate*<void>""
IL_0013: ret
}
");
}
[Fact]
public void FixedSizeBufferOfFunctionPointers()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe struct S
{
fixed delegate*<void> ptrs[1];
}");
comp.VerifyDiagnostics(
// (4,11): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double
// fixed delegate*<void> ptrs[1];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "delegate*<void>").WithLocation(4, 11)
);
}
[Fact]
public void IndirectLoadsAndStores()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static delegate*<void> field;
static void Printer() => Console.Write(1);
static ref delegate*<void> Getter() => ref field;
static void Main()
{
ref var printer = ref Getter();
printer = &Printer;
printer();
field();
}
}", expectedOutput: "11");
verifier.VerifyIL(@"C.Main", expectedIL: @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: call ""ref delegate*<void> C.Getter()""
IL_0005: dup
IL_0006: ldftn ""void C.Printer()""
IL_000c: stind.i
IL_000d: ldind.i
IL_000e: calli ""delegate*<void>""
IL_0013: ldsfld ""delegate*<void> C.field""
IL_0018: calli ""delegate*<void>""
IL_001d: ret
}
");
}
[Fact]
public void Foreach()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void M(string s) => Console.Write(s);
public static void Main()
{
delegate*<string, void>[] ptrs = new delegate*<string, void>[] { &M, &M };
int i = 0;
foreach (delegate*<string, void> ptr in ptrs)
{
ptr(i++.ToString());
}
}
}", expectedOutput: "01");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 66 (0x42)
.maxstack 4
.locals init (int V_0, //i
delegate*<string, void>[] V_1,
int V_2,
delegate*<string, void> V_3,
int V_4)
IL_0000: ldc.i4.2
IL_0001: newarr ""delegate*<string, void>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldftn ""void C.M(string)""
IL_000e: stelem.i
IL_000f: dup
IL_0010: ldc.i4.1
IL_0011: ldftn ""void C.M(string)""
IL_0017: stelem.i
IL_0018: ldc.i4.0
IL_0019: stloc.0
IL_001a: stloc.1
IL_001b: ldc.i4.0
IL_001c: stloc.2
IL_001d: br.s IL_003b
IL_001f: ldloc.1
IL_0020: ldloc.2
IL_0021: ldelem.i
IL_0022: stloc.3
IL_0023: ldloc.0
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: add
IL_0027: stloc.0
IL_0028: stloc.s V_4
IL_002a: ldloca.s V_4
IL_002c: call ""string int.ToString()""
IL_0031: ldloc.3
IL_0032: calli ""delegate*<string, void>""
IL_0037: ldloc.2
IL_0038: ldc.i4.1
IL_0039: add
IL_003a: stloc.2
IL_003b: ldloc.2
IL_003c: ldloc.1
IL_003d: ldlen
IL_003e: conv.i4
IL_003f: blt.s IL_001f
IL_0041: ret
}
");
}
[Fact]
public void FieldInitializers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
delegate*<string, void>[] arr1;
delegate*<string, void>[] arr2 = new delegate*<string, void>[1];
static void Print(string s) => Console.Write(s);
static void Main()
{
var c = new C()
{
arr1 = new delegate*<string, void>[] { &Print },
arr2 = { [0] = &Print }
};
c.arr1[0](""1"");
c.arr2[0](""2"");
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 82 (0x52)
.maxstack 5
.locals init (C V_0,
delegate*<string, void> V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: newarr ""delegate*<string, void>""
IL_000d: dup
IL_000e: ldc.i4.0
IL_000f: ldftn ""void C.Print(string)""
IL_0015: stelem.i
IL_0016: stfld ""delegate*<string, void>[] C.arr1""
IL_001b: ldloc.0
IL_001c: ldfld ""delegate*<string, void>[] C.arr2""
IL_0021: ldc.i4.0
IL_0022: ldftn ""void C.Print(string)""
IL_0028: stelem.i
IL_0029: ldloc.0
IL_002a: dup
IL_002b: ldfld ""delegate*<string, void>[] C.arr1""
IL_0030: ldc.i4.0
IL_0031: ldelem.i
IL_0032: stloc.1
IL_0033: ldstr ""1""
IL_0038: ldloc.1
IL_0039: calli ""delegate*<string, void>""
IL_003e: ldfld ""delegate*<string, void>[] C.arr2""
IL_0043: ldc.i4.0
IL_0044: ldelem.i
IL_0045: stloc.1
IL_0046: ldstr ""2""
IL_004b: ldloc.1
IL_004c: calli ""delegate*<string, void>""
IL_0051: ret
}
");
}
[Fact]
public void InitializeFunctionPointerWithNull()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Main()
{
delegate*<string, void>[] ptrs = new delegate*<string, void>[] { null, null, null };
Console.Write(ptrs[0] is null);
}
}", expectedOutput: "True");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 33 (0x21)
.maxstack 4
IL_0000: ldc.i4.3
IL_0001: newarr ""delegate*<string, void>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: stelem.i
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.0
IL_000e: conv.u
IL_000f: stelem.i
IL_0010: dup
IL_0011: ldc.i4.2
IL_0012: ldc.i4.0
IL_0013: conv.u
IL_0014: stelem.i
IL_0015: ldc.i4.0
IL_0016: ldelem.i
IL_0017: ldc.i4.0
IL_0018: conv.u
IL_0019: ceq
IL_001b: call ""void System.Console.Write(bool)""
IL_0020: ret
}
");
}
[Fact]
public void InferredArrayInitializer_ParameterVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(object o) => Console.Write(o);
static void Print(string s) => Console.Write(s);
static void Main()
{
delegate*<string, void> ptr1 = &Print;
delegate*<object, void> ptr2 = &Print;
var ptrs = new[] { ptr1, ptr2 };
ptrs[0](""1"");
ptrs[1](""2"");
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 58 (0x3a)
.maxstack 4
.locals init (delegate*<string, void> V_0, //ptr1
delegate*<object, void> V_1, //ptr2
delegate*<string, void> V_2)
IL_0000: ldftn ""void C.Print(string)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.Print(object)""
IL_000d: stloc.1
IL_000e: ldc.i4.2
IL_000f: newarr ""delegate*<string, void>""
IL_0014: dup
IL_0015: ldc.i4.0
IL_0016: ldloc.0
IL_0017: stelem.i
IL_0018: dup
IL_0019: ldc.i4.1
IL_001a: ldloc.1
IL_001b: stelem.i
IL_001c: dup
IL_001d: ldc.i4.0
IL_001e: ldelem.i
IL_001f: stloc.2
IL_0020: ldstr ""1""
IL_0025: ldloc.2
IL_0026: calli ""delegate*<string, void>""
IL_002b: ldc.i4.1
IL_002c: ldelem.i
IL_002d: stloc.2
IL_002e: ldstr ""2""
IL_0033: ldloc.2
IL_0034: calli ""delegate*<string, void>""
IL_0039: ret
}
");
}
[Fact]
public void InferredArrayInitializer_ReturnVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object GetObject() => 1.ToString();
static string GetString() => 2.ToString();
static void Print(delegate*<object>[] ptrs)
{
Console.Write(""Object"");
foreach (var ptr in ptrs)
{
Console.Write(ptr());
}
}
static void Print(delegate*<string>[] ptrs)
{
Console.Write(""String"");
foreach (var ptr in ptrs)
{
Console.Write(ptr());
}
}
static void Main()
{
delegate*<object> ptr1 = &GetObject;
delegate*<string> ptr2 = &GetString;
Print(new[] { ptr1, ptr2 });
}
}", expectedOutput: "Object12");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 34 (0x22)
.maxstack 4
.locals init (delegate*<object> V_0, //ptr1
delegate*<string> V_1) //ptr2
IL_0000: ldftn ""object C.GetObject()""
IL_0006: stloc.0
IL_0007: ldftn ""string C.GetString()""
IL_000d: stloc.1
IL_000e: ldc.i4.2
IL_000f: newarr ""delegate*<object>""
IL_0014: dup
IL_0015: ldc.i4.0
IL_0016: ldloc.0
IL_0017: stelem.i
IL_0018: dup
IL_0019: ldc.i4.1
IL_001a: ldloc.1
IL_001b: stelem.i
IL_001c: call ""void C.Print(delegate*<object>[])""
IL_0021: ret
}
");
}
[Fact]
public void BestTypeForConditional_ParameterVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(object o) => Console.Write(o + ""Object"");
static void Print(string s) => Console.Write(s + ""String"");
static void M(bool b)
{
delegate*<object, void> ptr1 = &Print;
delegate*<string, void> ptr2 = &Print;
var ptr3 = b ? ptr1 : ptr2;
ptr3(""1"");
ptr3 = b ? ptr2 : ptr1;
ptr3(""2"");
}
static void Main() => M(true);
}", expectedOutput: "1Object2String");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 53 (0x35)
.maxstack 2
.locals init (delegate*<object, void> V_0, //ptr1
delegate*<string, void> V_1, //ptr2
delegate*<string, void> V_2)
IL_0000: ldftn ""void C.Print(object)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.Print(string)""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.1
IL_0012: br.s IL_0015
IL_0014: ldloc.0
IL_0015: stloc.2
IL_0016: ldstr ""1""
IL_001b: ldloc.2
IL_001c: calli ""delegate*<string, void>""
IL_0021: ldarg.0
IL_0022: brtrue.s IL_0027
IL_0024: ldloc.0
IL_0025: br.s IL_0028
IL_0027: ldloc.1
IL_0028: stloc.2
IL_0029: ldstr ""2""
IL_002e: ldloc.2
IL_002f: calli ""delegate*<string, void>""
IL_0034: ret
}
");
}
[Fact]
public void BestTypeForConditional_ReturnVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object GetObject() => 1.ToString();
static string GetString() => 2.ToString();
static void Print(delegate*<object> ptr)
{
Console.Write(ptr());
Console.Write(""Object"");
}
static void Print(delegate*<string> ptr)
{
Console.Write(ptr());
Console.Write(""String"");
}
static void M(bool b)
{
delegate*<object> ptr1 = &GetObject;
delegate*<string> ptr2 = &GetString;
Print(b ? ptr1 : ptr2);
Print(b ? ptr2 : ptr1);
}
static void Main() => M(true);
}", expectedOutput: "1Object2Object");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init (delegate*<object> V_0, //ptr1
delegate*<string> V_1) //ptr2
IL_0000: ldftn ""object C.GetObject()""
IL_0006: stloc.0
IL_0007: ldftn ""string C.GetString()""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.1
IL_0012: br.s IL_0015
IL_0014: ldloc.0
IL_0015: call ""void C.Print(delegate*<object>)""
IL_001a: ldarg.0
IL_001b: brtrue.s IL_0020
IL_001d: ldloc.0
IL_001e: br.s IL_0021
IL_0020: ldloc.1
IL_0021: call ""void C.Print(delegate*<object>)""
IL_0026: ret
}
");
}
[Fact]
public void BestTypeForConditional_NestedParameterVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(object o)
{
Console.Write(o);
}
static void PrintObject(delegate*<object, void> ptr, string o)
{
ptr(o);
}
static void PrintString(delegate*<string, void> ptr, string s)
{
ptr(s);
}
static void Invoke(delegate*<delegate*<object, void>, string, void> ptr, string s)
{
Console.Write(""Object"");
delegate*<object, void> print = &Print;
ptr(print, s);
}
static void Invoke(delegate*<delegate*<string, void>, string, void> ptr, string s)
{
Console.Write(""String"");
delegate*<string, void> print = &Print;
ptr(print, s);
}
static void M(bool b)
{
delegate*<delegate*<object, void>, string, void> printObject = &PrintObject;
delegate*<delegate*<string, void>, string, void> printString = &PrintString;
Invoke(b ? printObject : printString, ""1"");
}
static void Main() => M(true);
}", expectedOutput: "Object1");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (delegate*<delegate*<object, void>, string, void> V_0, //printObject
delegate*<delegate*<string, void>, string, void> V_1) //printString
IL_0000: ldftn ""void C.PrintObject(delegate*<object, void>, string)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.PrintString(delegate*<string, void>, string)""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.1
IL_0012: br.s IL_0015
IL_0014: ldloc.0
IL_0015: ldstr ""1""
IL_001a: call ""void C.Invoke(delegate*<delegate*<object, void>, string, void>, string)""
IL_001f: ret
}
");
}
[Fact]
public void BestTypeForConditional_NestedParameterRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(ref object o1, object o2)
{
o1 = o2;
}
static void PrintObject(delegate*<ref object, object, void> ptr, ref object o, object arg)
{
ptr(ref o, arg);
}
static void PrintString(delegate*<ref object, string, void> ptr, ref object o, string arg)
{
ptr(ref o, arg);
}
static void Invoke(delegate*<delegate*<ref object, object, void>, ref object, string, void> ptr, ref object s, object arg)
{
Console.Write(""Object"");
delegate*<ref object, object, void> print = &Print;
ptr(print, ref s, arg.ToString());
}
static void Invoke(delegate*<delegate*<ref object, string, void>, ref object, string, void> ptr, ref object s, string arg)
{
Console.Write(""String"");
delegate*<ref object, string, void> print = &Print;
ptr(print, ref s, arg);
}
static void M(bool b)
{
delegate*<delegate*<ref object, object, void>, ref object, string, void> printObject1 = &PrintObject;
delegate*<delegate*<ref object, string, void>, ref object, string, void> printObject2 = &PrintString;
object o = null;
Invoke(b ? printObject1 : printObject2, ref o, ""1"");
Console.Write(o);
}
static void Main() => M(true);
}", expectedOutput: "Object1");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (delegate*<delegate*<ref object, object, void>, ref object, string, void> V_0, //printObject1
delegate*<delegate*<ref object, string, void>, ref object, string, void> V_1, //printObject2
object V_2) //o
IL_0000: ldftn ""void C.PrintObject(delegate*<ref object, object, void>, ref object, object)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.PrintString(delegate*<ref object, string, void>, ref object, string)""
IL_000d: stloc.1
IL_000e: ldnull
IL_000f: stloc.2
IL_0010: ldarg.0
IL_0011: brtrue.s IL_0016
IL_0013: ldloc.1
IL_0014: br.s IL_0017
IL_0016: ldloc.0
IL_0017: ldloca.s V_2
IL_0019: ldstr ""1""
IL_001e: call ""void C.Invoke(delegate*<delegate*<ref object, object, void>, ref object, string, void>, ref object, object)""
IL_0023: ldloc.2
IL_0024: call ""void System.Console.Write(object)""
IL_0029: ret
}
");
}
[Fact]
public void DefaultOfFunctionPointerType()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Main()
{
delegate*<void> ptr = default;
Console.Write(ptr is null);
}
}", expectedOutput: "True");
verifier.VerifyIL("C.Main", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: ldc.i4.0
IL_0003: conv.u
IL_0004: ceq
IL_0006: call ""void System.Console.Write(bool)""
IL_000b: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model,
syntaxTree.GetRoot()
.DescendantNodes()
.OfType<LiteralExpressionSyntax>()
.Where(l => l.IsKind(SyntaxKind.DefaultLiteralExpression))
.Single(),
expectedSyntax: "default",
expectedType: "delegate*<System.Void>",
expectedSymbol: null,
expectedSymbolCandidates: null);
}
[Fact]
public void ParamsArrayOfFunctionPointers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
static void Params(params delegate*<void>[] funcs)
{
foreach (var f in funcs)
{
f();
}
}
static void Main()
{
Params();
}
}", expectedOutput: "");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: newarr ""delegate*<void>""
IL_0006: call ""void C.Params(params delegate*<void>[])""
IL_000b: ret
}
");
}
[Fact]
public void StackallocOfFunctionPointers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
static unsafe class C
{
static int Getter(int i) => i;
static void Print(delegate*<int, int>* p)
{
for (int i = 0; i < 3; i++)
Console.Write(p[i](i));
}
static void Main()
{
delegate*<int, int>* p = stackalloc delegate*<int, int>[] { &Getter, &Getter, &Getter };
Print(p);
}
}
", expectedOutput: "012");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 58 (0x3a)
.maxstack 4
IL_0000: ldc.i4.3
IL_0001: conv.u
IL_0002: sizeof ""delegate*<int, int>""
IL_0008: mul.ovf.un
IL_0009: localloc
IL_000b: dup
IL_000c: ldftn ""int C.Getter(int)""
IL_0012: stind.i
IL_0013: dup
IL_0014: sizeof ""delegate*<int, int>""
IL_001a: add
IL_001b: ldftn ""int C.Getter(int)""
IL_0021: stind.i
IL_0022: dup
IL_0023: ldc.i4.2
IL_0024: conv.i
IL_0025: sizeof ""delegate*<int, int>""
IL_002b: mul
IL_002c: add
IL_002d: ldftn ""int C.Getter(int)""
IL_0033: stind.i
IL_0034: call ""void C.Print(delegate*<int, int>*)""
IL_0039: ret
}
");
}
[Fact]
public void FunctionPointerCannotBeUsedAsSpanArgument()
{
var comp = CreateCompilationWithSpan(@"
using System;
static unsafe class C
{
static void Main()
{
Span<delegate*<int, int>> p = stackalloc delegate*<int, int>[1];
}
}
", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,14): error CS0306: The type 'delegate*<int, int>' may not be used as a type argument
// Span<delegate*<int, int>> p = stackalloc delegate*<int, int>[1];
Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, int>").WithArguments("delegate*<int, int>").WithLocation(7, 14)
);
}
[Fact]
public void RecursivelyUsedTypeInFunctionPointer()
{
var verifier = CompileAndVerifyFunctionPointers(@"
namespace Interop
{
public unsafe struct PROPVARIANT
{
public CAPROPVARIANT ca;
}
public unsafe struct CAPROPVARIANT
{
public uint cElems;
public delegate*<PROPVARIANT> pElems;
public delegate*<PROPVARIANT> pElemsProp { get; }
}
}");
}
[Fact]
public void VolatileFunctionPointerField()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static volatile delegate*<void> ptr;
static void Print() => Console.Write(1);
static void Main()
{
ptr = &Print;
ptr();
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: ldftn ""void C.Print()""
IL_0006: volatile.
IL_0008: stsfld ""delegate*<void> C.ptr""
IL_000d: volatile.
IL_000f: ldsfld ""delegate*<void> C.ptr""
IL_0014: calli ""delegate*<void>""
IL_0019: ret
}
");
}
[Fact]
public void SupportedBinaryOperators()
{
var verifier = CompileAndVerifyFunctionPointers(@"
#pragma warning disable CS8909 // Function pointers should not be compared
using System;
unsafe class C
{
static (bool, bool, bool, bool, bool, bool) DoCompare(delegate*<void> func_1a, delegate*<string, void> func_1b)
{
return (func_1a == func_1b,
func_1a != func_1b,
func_1a > func_1b,
func_1a >= func_1b,
func_1a < func_1b,
func_1a <= func_1b);
}
static void M(delegate*<void> func_1a, delegate*<string, void> func_1b, delegate*<int> func_2, int* int_1, int* int_2)
{
var compareResults = DoCompare(func_1a, func_1b);
Console.WriteLine(""func_1a == func_1b: "" + compareResults.Item1);
Console.WriteLine(""func_1a != func_1b: "" + compareResults.Item2);
Console.WriteLine(""func_1a > func_1b: "" + compareResults.Item3);
Console.WriteLine(""func_1a >= func_1b: "" + compareResults.Item4);
Console.WriteLine(""func_1a < func_1b: "" + compareResults.Item5);
Console.WriteLine(""func_1a <= func_1b: "" + compareResults.Item6);
Console.WriteLine(""func_1a == func_2: "" + (func_1a == func_2));
Console.WriteLine(""func_1a != func_2: "" + (func_1a != func_2));
Console.WriteLine(""func_1a > func_2: "" + (func_1a > func_2));
Console.WriteLine(""func_1a >= func_2: "" + (func_1a >= func_2));
Console.WriteLine(""func_1a < func_2: "" + (func_1a < func_2));
Console.WriteLine(""func_1a <= func_2: "" + (func_1a <= func_2));
Console.WriteLine(""func_1a == int_1: "" + (func_1a == int_1));
Console.WriteLine(""func_1a != int_1: "" + (func_1a != int_1));
Console.WriteLine(""func_1a > int_1: "" + (func_1a > int_1));
Console.WriteLine(""func_1a >= int_1: "" + (func_1a >= int_1));
Console.WriteLine(""func_1a < int_1: "" + (func_1a < int_1));
Console.WriteLine(""func_1a <= int_1: "" + (func_1a <= int_1));
Console.WriteLine(""func_1a == int_2: "" + (func_1a == int_2));
Console.WriteLine(""func_1a != int_2: "" + (func_1a != int_2));
Console.WriteLine(""func_1a > int_2: "" + (func_1a > int_2));
Console.WriteLine(""func_1a >= int_2: "" + (func_1a >= int_2));
Console.WriteLine(""func_1a < int_2: "" + (func_1a < int_2));
Console.WriteLine(""func_1a <= int_2: "" + (func_1a <= int_2));
}
static void Main()
{
delegate*<void> func_1a = (delegate*<void>)1;
delegate*<string, void> func_1b = (delegate*<string, void>)1;
delegate*<int> func_2 = (delegate*<int>)2;
int* int_1 = (int*)1;
int* int_2 = (int*)2;
M(func_1a, func_1b, func_2, int_1, int_2);
}
}", expectedOutput: @"
func_1a == func_1b: True
func_1a != func_1b: False
func_1a > func_1b: False
func_1a >= func_1b: True
func_1a < func_1b: False
func_1a <= func_1b: True
func_1a == func_2: False
func_1a != func_2: True
func_1a > func_2: False
func_1a >= func_2: False
func_1a < func_2: True
func_1a <= func_2: True
func_1a == int_1: True
func_1a != int_1: False
func_1a > int_1: False
func_1a >= int_1: True
func_1a < int_1: False
func_1a <= int_1: True
func_1a == int_2: False
func_1a != int_2: True
func_1a > int_2: False
func_1a >= int_2: False
func_1a < int_2: True
func_1a <= int_2: True");
verifier.VerifyIL("C.DoCompare", expectedIL: @"
{
// Code size 39 (0x27)
.maxstack 7
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ceq
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: ceq
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: ldarg.0
IL_000c: ldarg.1
IL_000d: cgt.un
IL_000f: ldarg.0
IL_0010: ldarg.1
IL_0011: clt.un
IL_0013: ldc.i4.0
IL_0014: ceq
IL_0016: ldarg.0
IL_0017: ldarg.1
IL_0018: clt.un
IL_001a: ldarg.0
IL_001b: ldarg.1
IL_001c: cgt.un
IL_001e: ldc.i4.0
IL_001f: ceq
IL_0021: newobj ""System.ValueTuple<bool, bool, bool, bool, bool, bool>..ctor(bool, bool, bool, bool, bool, bool)""
IL_0026: ret
}
");
}
[Theory, WorkItem(48919, "https://github.com/dotnet/roslyn/issues/48919")]
[InlineData("==")]
[InlineData("!=")]
[InlineData(">=")]
[InlineData(">")]
[InlineData("<=")]
[InlineData("<")]
public void BinaryComparisonWarnings(string @operator)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe
{{
delegate*<void> a = null, b = null;
_ = a {@operator} b;
}}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (5,9): error CS8909: Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct.
// _ = a {@operator} b;
Diagnostic(ErrorCode.WRN_DoNotCompareFunctionPointers, @operator).WithLocation(5, 11)
);
}
[Theory, WorkItem(48919, "https://github.com/dotnet/roslyn/issues/48919")]
[InlineData("==")]
[InlineData("!=")]
[InlineData(">=")]
[InlineData(">")]
[InlineData("<=")]
[InlineData("<")]
public void BinaryComparisonCastToVoidStar_NoWarning(string @operator)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe
{{
delegate*<void> a = null, b = null;
_ = (void*)a {@operator} b;
_ = a {@operator} (void*)b;
}}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData("+")]
[InlineData("-")]
[InlineData("*")]
[InlineData("/")]
[InlineData("%")]
[InlineData("<<")]
[InlineData(">>")]
[InlineData("&&")]
[InlineData("||")]
[InlineData("&")]
[InlineData("|")]
[InlineData("^")]
public void UnsupportedBinaryOps(string op)
{
bool isLogical = op == "&&" || op == "||";
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
static void M(delegate*<void> ptr1, delegate*<void> ptr2, int* ptr3)
{{
_ = ptr1 {op} ptr2;
_ = ptr1 {op} ptr3;
_ = ptr1 {op} 1;
{(isLogical ? "" : $@"ptr1 {op}= ptr2;
ptr1 {op}= ptr3;
ptr1 {op}= 1;")}
}}
}}");
var expectedDiagnostics = ArrayBuilder<DiagnosticDescription>.GetInstance();
expectedDiagnostics.AddRange(
// (6,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'delegate*<void>'
// _ = ptr1 op ptr2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} ptr2").WithArguments(op, "delegate*<void>", "delegate*<void>").WithLocation(6, 13),
// (7,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'int*'
// _ = ptr1 op ptr3;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} ptr3").WithArguments(op, "delegate*<void>", "int*").WithLocation(7, 13),
// (8,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'int'
// _ = ptr1 op 1;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} 1").WithArguments(op, "delegate*<void>", "int").WithLocation(8, 13));
if (!isLogical)
{
expectedDiagnostics.AddRange(
// (9,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'delegate*<void>'
// ptr1 op= ptr2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= ptr2").WithArguments($"{op}=", "delegate*<void>", "delegate*<void>").WithLocation(9, 9),
// (10,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'int*'
// ptr1 op= ptr3;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= ptr3").WithArguments($"{op}=", "delegate*<void>", "int*").WithLocation(10, 9),
// (11,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'int'
// ptr1 op= 1;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= 1").WithArguments($"{op}=", "delegate*<void>", "int").WithLocation(11, 9));
}
comp.VerifyDiagnostics(expectedDiagnostics.ToArrayAndFree());
}
[Theory]
[InlineData("+")]
[InlineData("++")]
[InlineData("-")]
[InlineData("--")]
[InlineData("!")]
[InlineData("~")]
public void UnsupportedPrefixUnaryOps(string op)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
public static void M(delegate*<void> ptr)
{{
_ = {op}ptr;
}}
}}");
comp.VerifyDiagnostics(
// (6,13): error CS0023: Operator 'op' cannot be applied to operand of type 'delegate*<void>'
// _ = {op}ptr;
Diagnostic(ErrorCode.ERR_BadUnaryOp, $"{op}ptr").WithArguments(op, "delegate*<void>").WithLocation(6, 13)
);
}
[Theory]
[InlineData("++")]
[InlineData("--")]
public void UnsupportedPostfixUnaryOps(string op)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
public static void M(delegate*<void> ptr)
{{
_ = ptr{op};
}}
}}");
comp.VerifyDiagnostics(
// (6,13): error CS0023: Operator 'op' cannot be applied to operand of type 'delegate*<void>'
// _ = ptr{op};
Diagnostic(ErrorCode.ERR_BadUnaryOp, $"ptr{op}").WithArguments(op, "delegate*<void>").WithLocation(6, 13)
);
}
[Fact]
public void FunctionPointerReturnTypeConstrainedCallVirtIfRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
void M1() {}
void M<T>(delegate*<ref T> ptr1, delegate*<T> ptr2) where T : C
{
ptr1().M1();
ptr2().M1();
}
}");
verifier.VerifyIL(@"C.M<T>(delegate*<ref T>, delegate*<T>)", @"
{
// Code size 34 (0x22)
.maxstack 1
IL_0000: ldarg.1
IL_0001: calli ""delegate*<ref T>""
IL_0006: constrained. ""T""
IL_000c: callvirt ""void C.M1()""
IL_0011: ldarg.2
IL_0012: calli ""delegate*<T>""
IL_0017: box ""T""
IL_001c: callvirt ""void C.M1()""
IL_0021: ret
}
");
}
[Fact]
public void NullableAnnotationsInMetadata()
{
var source = @"
public unsafe class C
{
public delegate*<string, object, C> F1;
public delegate*<string?, object, C> F2;
public delegate*<string, object?, C> F3;
public delegate*<string, object, C?> F4;
public delegate*<string?, object?, C?> F5;
public delegate*<delegate*<string, int*>, delegate*<string?>, delegate*<void*, string>> F6;
}";
var comp = CreateCompilationWithFunctionPointers(source, options: WithNullableEnable(TestOptions.UnsafeReleaseDll));
comp.VerifyDiagnostics();
verifySymbolNullabilities(comp.GetTypeByMetadataName("C")!);
CompileAndVerify(comp, symbolValidator: symbolValidator, verify: Verification.Skipped);
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetTypeMember("C");
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 1, 1})", getAttribute("F1"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 2, 1})", getAttribute("F2"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 1, 2})", getAttribute("F3"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 2, 1, 1})", getAttribute("F4"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 2, 2, 2})", getAttribute("F5"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 0, 1, 0, 0, 0, 1, 0, 2})", getAttribute("F6"));
verifySymbolNullabilities(c);
string getAttribute(string fieldName) => c.GetField(fieldName).GetAttributes().Single().ToString()!;
}
static void verifySymbolNullabilities(NamedTypeSymbol c)
{
assertExpected("delegate*<System.String!, System.Object!, C!>", "F1");
assertExpected("delegate*<System.String?, System.Object!, C!>", "F2");
assertExpected("delegate*<System.String!, System.Object?, C!>", "F3");
assertExpected("delegate*<System.String!, System.Object!, C?>", "F4");
assertExpected("delegate*<System.String?, System.Object?, C?>", "F5");
assertExpected("delegate*<delegate*<System.String!, System.Int32*>, delegate*<System.String?>, delegate*<System.Void*, System.String!>>", "F6");
void assertExpected(string expectedType, string fieldName)
{
var type = (FunctionPointerTypeSymbol)c.GetField(fieldName).Type;
CommonVerifyFunctionPointer(type);
Assert.Equal(expectedType, type.ToTestDisplayString(includeNonNullable: true));
}
}
}
[Theory]
[InlineData("delegate*<Z, Z, (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
[InlineData("delegate*<(Z a, Z b), Z, Z>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
[InlineData("delegate*<Z, (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
[InlineData("delegate*<(Z c, Z d), (Z e, Z f), (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b"", ""c"", ""d"", ""e"", ""f""})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b"", null, null, null, null})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z a, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", null, null, null, null, null})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, ""b"", null, null, null, null})")]
[InlineData("delegate*<(Z c, Z d), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, ""c"", ""d"", null, null})")]
[InlineData("delegate*<(Z c, Z), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, ""c"", null, null, null})")]
[InlineData("delegate*<(Z, Z d), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, ""d"", null, null})")]
[InlineData("delegate*<(Z, Z), (Z e, Z f), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, ""e"", ""f""})")]
[InlineData("delegate*<(Z, Z), (Z e, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, ""e"", null})")]
[InlineData("delegate*<(Z, Z), (Z, Z f), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, null, ""f""})")]
[InlineData("delegate*<(Z a, (Z b, Z c) d), (Z e, Z f)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""e"", ""f"", ""a"", ""d"", ""b"", ""c""})")]
[InlineData("delegate*<(Z a, Z b), ((Z c, Z d) e, Z f)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""e"", ""f"", ""c"", ""d"", ""a"", ""b""})")]
[InlineData("delegate*<delegate*<(Z a, Z b), Z>, delegate*<Z, (Z d, Z e)>>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""d"", ""e"", ""a"", ""b""})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z, Z)>", null)]
public void TupleNamesInMetadata(string type, string? expectedAttribute)
{
var comp = CompileAndVerifyFunctionPointers($@"
#pragma warning disable CS0649 // Unassigned field
unsafe class Z
{{
public {type} F;
}}
", symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetTypeMember("Z");
var field = c.GetField("F");
if (expectedAttribute == null)
{
Assert.Empty(field.GetAttributes());
}
else
{
Assert.Equal(expectedAttribute, field.GetAttributes().Single().ToString());
}
CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type);
Assert.Equal(type, field.Type.ToTestDisplayString());
}
}
[Fact]
public void DynamicTypeAttributeInMetadata()
{
var comp = CompileAndVerifyFunctionPointers(@"
#pragma warning disable CS0649 // Unassigned field
unsafe class C
{
public delegate*<dynamic, dynamic, dynamic> F1;
public delegate*<object, object, dynamic> F2;
public delegate*<dynamic, object, object> F3;
public delegate*<object, dynamic, object> F4;
public delegate*<object, object, object> F5;
public delegate*<object, object, ref dynamic> F6;
public delegate*<ref dynamic, object, object> F7;
public delegate*<object, ref dynamic, object> F8;
public delegate*<ref object, ref object, dynamic> F9;
public delegate*<dynamic, ref object, ref object> F10;
public delegate*<ref object, dynamic, ref object> F11;
public delegate*<object, ref readonly dynamic> F12;
public delegate*<in dynamic, object> F13;
public delegate*<out dynamic, object> F14;
public D<delegate*<dynamic>[], dynamic> F15;
public delegate*<A<object>.B<dynamic>> F16;
}
class D<T, U> { }
class A<T>
{
public class B<U> {}
}
", symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetTypeMember("C");
assertField("F1", "System.Runtime.CompilerServices.DynamicAttribute({false, true, true, true})", "delegate*<dynamic, dynamic, dynamic>");
assertField("F2", "System.Runtime.CompilerServices.DynamicAttribute({false, true, false, false})", "delegate*<System.Object, System.Object, dynamic>");
assertField("F3", "System.Runtime.CompilerServices.DynamicAttribute({false, false, true, false})", "delegate*<dynamic, System.Object, System.Object>");
assertField("F4", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "delegate*<System.Object, dynamic, System.Object>");
assertField("F5", null, "delegate*<System.Object, System.Object, System.Object>");
assertField("F6", "System.Runtime.CompilerServices.DynamicAttribute({false, false, true, false, false})", "delegate*<System.Object, System.Object, ref dynamic>");
assertField("F7", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false})", "delegate*<ref dynamic, System.Object, System.Object>");
assertField("F8", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<System.Object, ref dynamic, System.Object>");
assertField("F9", "System.Runtime.CompilerServices.DynamicAttribute({false, true, false, false, false, false})", "delegate*<ref System.Object, ref System.Object, dynamic>");
assertField("F10", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false, false})", "delegate*<dynamic, ref System.Object, ref System.Object>");
assertField("F11", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, false, true})", "delegate*<ref System.Object, dynamic, ref System.Object>");
assertField("F12", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false})", "delegate*<System.Object, ref readonly modreq(System.Runtime.InteropServices.InAttribute) dynamic>");
assertField("F13", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<in modreq(System.Runtime.InteropServices.InAttribute) dynamic, System.Object>");
assertField("F14", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<out modreq(System.Runtime.InteropServices.OutAttribute) dynamic, System.Object>");
// https://github.com/dotnet/roslyn/issues/44160 tracks fixing this. We're not encoding dynamic correctly for function pointers as type parameters
assertField("F15", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "D<delegate*<System.Object>[], System.Object>");
assertField("F16", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "delegate*<A<System.Object>.B<dynamic>>");
void assertField(string field, string? expectedAttribute, string expectedType)
{
var f = c.GetField(field);
if (expectedAttribute is null)
{
Assert.Empty(f.GetAttributes());
}
else
{
Assert.Equal(expectedAttribute, f.GetAttributes().Single().ToString());
}
if (f.Type is FunctionPointerTypeSymbol ptrType)
{
CommonVerifyFunctionPointer(ptrType);
}
Assert.Equal(expectedType, f.Type.ToTestDisplayString());
}
}
}
[Fact]
public void DynamicOverriddenWithCustomModifiers()
{
var il = @"
.class public A
{
.method public hidebysig newslot virtual
instance void M(method class [mscorlib]System.Object modopt([mscorlib]System.Object) & modopt([mscorlib]System.Object) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *(class [mscorlib]System.Object modopt([mscorlib]System.Object)) a) managed
{
.param [1]
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 08 00 00 00 00 00 00 00 00 01 00 01 00 00 )
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
var source = @"
unsafe class B : A
{
public override void M(delegate*<dynamic, ref readonly dynamic> a) {}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var b = module.GlobalNamespace.GetTypeMember("B");
var m = b.GetMethod("M");
var param = m.Parameters.Single();
Assert.Equal("System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, false, true, false, true})", param.GetAttributes().Single().ToString());
CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)param.Type);
Assert.Equal("delegate*<dynamic modopt(System.Object), ref readonly modreq(System.Runtime.InteropServices.InAttribute) modopt(System.Object) dynamic modopt(System.Object)>", param.Type.ToTestDisplayString());
}
}
[Fact]
public void BadDynamicAttributes()
{
var il = @"
.class public A
{
.method public hidebysig static void TooManyFlags(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void TooFewFlags_MissingParam(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 )
ret
}
.method public hidebysig static void TooFewFlags_MissingReturn(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{false}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 )
ret
}
.method public hidebysig static void PtrTypeIsTrue(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void NonObjectIsTrue(method class [mscorlib]System.String *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 )
ret
}
.method public hidebysig static void RefIsTrue_Return(method class [mscorlib]System.Object& *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void RefIsTrue_Param(method class [mscorlib]System.Object *(class [mscorlib]System.Object&) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_Return(method class [mscorlib]System.Object modopt([mscorlib]System.Object) *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_Param(method class [mscorlib]System.Object *(class [mscorlib]System.Object modopt([mscorlib]System.Object)) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_RefReturn(method class [mscorlib]System.Object & modopt([mscorlib]System.Object) *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 05 00 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_RefParam(method class [mscorlib]System.Object *(class [mscorlib]System.Object & modopt([mscorlib]System.Object)) a)
{
.param [1]
//{false, true, false, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 05 00 00 00 00 01 00 01 01 00 00 )
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl("", il);
var a = comp.GetTypeByMetadataName("A");
assert("TooManyFlags", "delegate*<System.Object, System.Object>");
assert("TooFewFlags_MissingParam", "delegate*<System.Object, System.Object>");
assert("TooFewFlags_MissingReturn", "delegate*<System.Object, System.Object>");
assert("PtrTypeIsTrue", "delegate*<System.Object, System.Object>");
assert("NonObjectIsTrue", "delegate*<System.Object, System.String>");
assert("RefIsTrue_Return", "delegate*<System.Object, ref System.Object>");
assert("RefIsTrue_Param", "delegate*<ref System.Object, System.Object>");
assert("ModIsTrue_Return", "delegate*<System.Object, System.Object modopt(System.Object)>");
assert("ModIsTrue_Param", "delegate*<System.Object modopt(System.Object), System.Object>");
assert("ModIsTrue_RefReturn", "delegate*<System.Object, ref modopt(System.Object) System.Object>");
assert("ModIsTrue_RefParam", "delegate*<ref modopt(System.Object) System.Object, System.Object>");
void assert(string methodName, string expectedType)
{
var method = a.GetMethod(methodName);
var param = method.Parameters.Single();
CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)param.Type);
Assert.Equal(expectedType, param.Type.ToTestDisplayString());
}
}
[Fact]
public void BetterFunctionMember_BreakTiesByCustomModifierCount_TypeMods()
{
var il = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
void RetModifiers (method void modopt([mscorlib]System.Object) modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void RetModifiers (method void modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32 modopt([mscorlib]System.Object) modopt([mscorlib]System.Object))) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32) modopt([mscorlib]System.Object)) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
}";
var source = @"
unsafe class C
{
static void Main()
{
delegate*<void> ptr1 = null;
Program.RetModifiers(ptr1);
delegate*<int, void> ptr2 = null;
Program.ParamModifiers(ptr2);
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "LL");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (delegate*<void> V_0, //ptr1
delegate*<int, void> V_1) //ptr2
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call ""void Program.RetModifiers(delegate*<void>)""
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: call ""void Program.ParamModifiers(delegate*<int, void>)""
IL_0012: ret
}
");
}
[Fact]
public void BetterFunctionMember_BreakTiesByCustomModifierCount_Ref()
{
var il = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
void RetModifiers (method int32 & modopt([mscorlib]System.Object) modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void RetModifiers (method int32 & modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32 & modopt([mscorlib]System.Object) modopt([mscorlib]System.Object))) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32 & modopt([mscorlib]System.Object))) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
}
";
var source = @"
unsafe class C
{
static void Main()
{
delegate*<ref int> ptr1 = null;
Program.RetModifiers(ptr1);
delegate*<ref int, void> ptr2 = null;
Program.ParamModifiers(ptr2);
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "LL");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (delegate*<ref int> V_0, //ptr1
delegate*<ref int, void> V_1) //ptr2
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call ""void Program.RetModifiers(delegate*<ref int>)""
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: call ""void Program.ParamModifiers(delegate*<ref int, void>)""
IL_0012: ret
}
");
}
[Fact]
public void Overloading_ReturnTypes()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(delegate*<void> ptr) => ptr();
static void M(delegate*<object> ptr) => Console.WriteLine(ptr());
static void M(delegate*<string> ptr) => Console.WriteLine(ptr());
static void Ptr_Void() => Console.WriteLine(""Void"");
static object Ptr_Obj() => ""Object"";
static string Ptr_Str() => ""String"";
static void Main()
{
M(&Ptr_Void);
M(&Ptr_Obj);
M(&Ptr_Str);
}
}
", expectedOutput: @"
Void
Object
String");
verifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 1
IL_0000: ldftn ""void C.Ptr_Void()""
IL_0006: call ""void C.M(delegate*<void>)""
IL_000b: ldftn ""object C.Ptr_Obj()""
IL_0011: call ""void C.M(delegate*<object>)""
IL_0016: ldftn ""string C.Ptr_Str()""
IL_001c: call ""void C.M(delegate*<string>)""
IL_0021: ret
}
");
}
[Fact]
public void Overloading_ValidReturnRefness()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object field = ""R"";
static void M(delegate*<object> ptr) => Console.WriteLine(ptr());
static void M(delegate*<ref object> ptr)
{
Console.Write(field);
ref var local = ref ptr();
local = ""ef"";
Console.WriteLine(field);
}
static object Ptr_NonRef() => ""NonRef"";
static ref object Ptr_Ref() => ref field;
static void Main()
{
M(&Ptr_NonRef);
M(&Ptr_Ref);
}
}
", expectedOutput: @"
NonRef
Ref");
verifier.VerifyIL("C.Main", @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldftn ""object C.Ptr_NonRef()""
IL_0006: call ""void C.M(delegate*<object>)""
IL_000b: ldftn ""ref object C.Ptr_Ref()""
IL_0011: call ""void C.M(delegate*<ref object>)""
IL_0016: ret
}
");
}
[Fact]
public void Overloading_InvalidReturnRefness()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C<T>
{
static void M1(delegate*<ref readonly object> ptr) => throw null;
static void M1(delegate*<ref object> ptr) => throw null;
static void M2(C<delegate*<ref readonly object>[]> c) => throw null;
static void M2(C<delegate*<ref object>[]> c) => throw null;
}
");
comp.VerifyDiagnostics(
// (5,17): error CS0111: Type 'C<T>' already defines a member called 'M1' with the same parameter types
// static void M1(delegate*<ref object> ptr) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C<T>").WithLocation(5, 17),
// (8,17): error CS0111: Type 'C<T>' already defines a member called 'M2' with the same parameter types
// static void M2(C<delegate*<ref object>[]> c) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C<T>").WithLocation(8, 17)
);
}
[Fact]
public void Overloading_ReturnNoBetterFunction()
{
var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
unsafe class C : I1, I2
{
static void M1(delegate*<I1> ptr) => throw null;
static void M1(delegate*<I2> ptr) => throw null;
static void M2(delegate*<C> ptr)
{
M1(ptr);
}
}
");
comp.VerifyDiagnostics(
// (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1(delegate*<I1>)' and 'C.M1(delegate*<I2>)'
// M1(ptr);
Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1(delegate*<I1>)", "C.M1(delegate*<I2>)").WithLocation(11, 9)
);
}
[Fact]
public void Overloading_ParameterTypes()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(delegate*<object, void> ptr) => ptr(""Object"");
static void M(delegate*<string, void> ptr) => ptr(""String"");
static void Main()
{
delegate*<object, void> ptr1 = &Console.WriteLine;
delegate*<string, void> ptr2 = &Console.WriteLine;
M(ptr1);
M(ptr2);
}
}
", expectedOutput: @"
Object
String");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 25 (0x19)
.maxstack 2
.locals init (delegate*<string, void> V_0) //ptr2
IL_0000: ldftn ""void System.Console.WriteLine(object)""
IL_0006: ldftn ""void System.Console.WriteLine(string)""
IL_000c: stloc.0
IL_000d: call ""void C.M(delegate*<object, void>)""
IL_0012: ldloc.0
IL_0013: call ""void C.M(delegate*<string, void>)""
IL_0018: ret
}
");
}
[Fact]
public void Overloading_ValidParameterRefness()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object field = ""R"";
static void M(delegate*<ref object, void> ptr)
{
Console.Write(field);
ref var local = ref field;
ptr(ref local);
Console.WriteLine(field);
}
static void M(delegate*<object, void> ptr) => ptr(""NonRef"");
static void Ptr(ref object param) => param = ""ef"";
static void Main()
{
M(&Console.WriteLine);
M(&Ptr);
}
}
", expectedOutput: @"
NonRef
Ref");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldftn ""void System.Console.WriteLine(object)""
IL_0006: call ""void C.M(delegate*<object, void>)""
IL_000b: ldftn ""void C.Ptr(ref object)""
IL_0011: call ""void C.M(delegate*<ref object, void>)""
IL_0016: ret
}
");
}
[Theory]
[InlineData("ref", "out")]
[InlineData("ref", "in")]
[InlineData("out", "in")]
public void Overloading_InvalidParameterRefness(string refKind1, string refKind2)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C<T>
{{
static void M1(delegate*<{refKind1} object, void> ptr) => throw null;
static void M1(delegate*<{refKind2} object, void> ptr) => throw null;
static void M2(C<delegate*<{refKind1} object, void>[]> c) => throw null;
static void M2(C<delegate*<{refKind2} object, void>[]> c) => throw null;
}}
");
comp.VerifyDiagnostics(
// (5,17): error CS0111: Type 'C<T>' already defines a member called 'M1' with the same parameter types
// static void M1(delegate*<{refKind2} object, void> ptr) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C<T>").WithLocation(5, 17),
// (8,17): error CS0111: Type 'C<T>' already defines a member called 'M2' with the same parameter types
// static void M2(C<delegate*<{refKind2} object, void>[]> c) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C<T>").WithLocation(8, 17)
);
}
[Fact]
public void Overloading_ParameterTypesNoBetterFunctionMember()
{
var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
unsafe class C : I1, I2
{
static void M1(delegate*<delegate*<I1, void>, void> ptr) => throw null;
static void M1(delegate*<delegate*<I2, void>, void> ptr) => throw null;
static void M2(delegate*<delegate*<C, void>, void> ptr)
{
M1(ptr);
}
}
");
comp.VerifyDiagnostics(
// (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1(delegate*<delegate*<I1, void>, void>)' and 'C.M1(delegate*<delegate*<I2, void>, void>)'
// M1(ptr);
Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1(delegate*<delegate*<I1, void>, void>)", "C.M1(delegate*<delegate*<I2, void>, void>)").WithLocation(11, 9)
);
}
[Fact]
public void Override_CallingConventionMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<void> ptr) {}
protected virtual delegate*<void> M2() => throw null;
protected virtual void M3(delegate* unmanaged[Stdcall, Thiscall]<void> ptr) {}
protected virtual delegate* unmanaged[Stdcall, Thiscall]<void> M4() => throw null;
}
unsafe class Derived1 : Base
{
protected override void M1(delegate* unmanaged[Cdecl]<void> ptr) {}
protected override delegate* unmanaged[Cdecl]<void> M2() => throw null;
protected override void M3(delegate* unmanaged[Fastcall, Thiscall]<void> ptr) {}
protected override delegate* unmanaged[Fastcall, Thiscall]<void> M4() => throw null;
}
unsafe class Derived2 : Base
{
protected override void M1(delegate*<void> ptr) {} // Implemented correctly
protected override delegate*<void> M2() => throw null; // Implemented correctly
protected override void M3(delegate* unmanaged[Stdcall, Fastcall]<void> ptr) {}
protected override delegate* unmanaged[Stdcall, Fastcall]<void> M4() => throw null;
}
");
comp.VerifyDiagnostics(
// (11,29): error CS0115: 'Derived1.M1(delegate* unmanaged[Cdecl]<void>)': no suitable method found to override
// protected override void M1(delegate* unmanaged[Cdecl]<void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived1.M1(delegate* unmanaged[Cdecl]<void>)").WithLocation(11, 29),
// (12,57): error CS0508: 'Derived1.M2()': return type must be 'delegate*<void>' to match overridden member 'Base.M2()'
// protected override delegate* unmanaged[Cdecl]<void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived1.M2()", "Base.M2()", "delegate*<void>").WithLocation(12, 57),
// (13,29): error CS0115: 'Derived1.M3(delegate* unmanaged[Fastcall, Thiscall]<void>)': no suitable method found to override
// protected override void M3(delegate* unmanaged[Fastcall, Thiscall]<void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived1.M3(delegate* unmanaged[Fastcall, Thiscall]<void>)").WithLocation(13, 29),
// (14,70): error CS0508: 'Derived1.M4()': return type must be 'delegate* unmanaged[Stdcall, Thiscall]<void>' to match overridden member 'Base.M4()'
// protected override delegate* unmanaged[Fastcall, Thiscall]<void> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived1.M4()", "Base.M4()", "delegate* unmanaged[Stdcall, Thiscall]<void>").WithLocation(14, 70),
// (20,29): error CS0115: 'Derived2.M3(delegate* unmanaged[Stdcall, Fastcall]<void>)': no suitable method found to override
// protected override void M3(delegate* unmanaged[Stdcall, Fastcall]<void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived2.M3(delegate* unmanaged[Stdcall, Fastcall]<void>)").WithLocation(20, 29),
// (21,69): error CS0508: 'Derived2.M4()': return type must be 'delegate* unmanaged[Stdcall, Thiscall]<void>' to match overridden member 'Base.M4()'
// protected override delegate* unmanaged[Stdcall, Fastcall]<void> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived2.M4()", "Base.M4()", "delegate* unmanaged[Stdcall, Thiscall]<void>").WithLocation(21, 69)
);
}
[Fact]
public void Override_ConventionOrderingDoesNotMatter()
{
var source1 = @"
using System;
public unsafe class Base
{
public virtual void M1(delegate* unmanaged[Thiscall, Stdcall]<void> param) => Console.WriteLine(""Base Thiscall, Stdcall param"");
public virtual delegate* unmanaged[Thiscall, Stdcall]<void> M2() { Console.WriteLine(""Base Thiscall, Stdcall return""); return null; }
public virtual void M3(delegate* unmanaged[Thiscall, Stdcall]<ref string> param) => Console.WriteLine(""Base Thiscall, Stdcall ref param"");
public virtual delegate* unmanaged[Thiscall, Stdcall]<ref string> M4() { Console.WriteLine(""Base Thiscall, Stdcall ref return""); return null; }
}
";
var source2 = @"
using System;
unsafe class Derived1 : Base
{
public override void M1(delegate* unmanaged[Stdcall, Thiscall]<void> param) => Console.WriteLine(""Derived1 Stdcall, Thiscall param"");
public override delegate* unmanaged[Stdcall, Thiscall]<void> M2() { Console.WriteLine(""Derived1 Stdcall, Thiscall return""); return null; }
public override void M3(delegate* unmanaged[Stdcall, Thiscall]<ref string> param) => Console.WriteLine(""Derived1 Stdcall, Thiscall ref param"");
public override delegate* unmanaged[Stdcall, Thiscall]<ref string> M4() { Console.WriteLine(""Derived1 Stdcall, Thiscall ref return""); return null; }
}
unsafe class Derived2 : Base
{
public override void M1(delegate* unmanaged[Stdcall, Stdcall, Thiscall]<void> param) => Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall param"");
public override delegate* unmanaged[Stdcall, Stdcall, Thiscall]<void> M2() { Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall return""); return null; }
public override void M3(delegate* unmanaged[Stdcall, Stdcall, Thiscall]<ref string> param) => Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall ref param"");
public override delegate* unmanaged[Stdcall, Stdcall, Thiscall]<ref string> M4() { Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall ref return""); return null; }
}
";
var executableCode = @"
using System;
unsafe
{
delegate* unmanaged[Stdcall, Thiscall]<void> ptr1 = null;
delegate* unmanaged[Stdcall, Thiscall]<ref string> ptr3 = null;
Base b1 = new Base();
b1.M1(ptr1);
b1.M2();
b1.M3(ptr3);
b1.M4();
Base d1 = new Derived1();
d1.M1(ptr1);
d1.M2();
d1.M3(ptr3);
d1.M4();
Base d2 = new Derived2();
d2.M1(ptr1);
d2.M2();
d2.M3(ptr3);
d2.M4();
}
";
var expectedOutput = @"
Base Thiscall, Stdcall param
Base Thiscall, Stdcall return
Base Thiscall, Stdcall ref param
Base Thiscall, Stdcall ref return
Derived1 Stdcall, Thiscall param
Derived1 Stdcall, Thiscall return
Derived1 Stdcall, Thiscall ref param
Derived1 Stdcall, Thiscall ref return
Derived2 Stdcall, Stdcall, Thiscall param
Derived2 Stdcall, Stdcall, Thiscall return
Derived2 Stdcall, Stdcall, Thiscall ref param
Derived2 Stdcall, Stdcall, Thiscall ref return
";
var allSourceComp = CreateCompilationWithFunctionPointers(new[] { executableCode, source1, source2 }, options: TestOptions.UnsafeReleaseExe);
CompileAndVerify(
allSourceComp,
expectedOutput: RuntimeUtilities.IsCoreClrRuntime ? expectedOutput : null,
symbolValidator: getSymbolValidator(separateAssembly: false),
verify: Verification.Skipped);
var baseComp = CreateCompilationWithFunctionPointers(source1);
var metadataRef = baseComp.EmitToImageReference();
var derivedComp = CreateCompilationWithFunctionPointers(new[] { executableCode, source2 }, references: new[] { metadataRef }, options: TestOptions.UnsafeReleaseExe);
CompileAndVerify(
derivedComp,
expectedOutput: RuntimeUtilities.IsCoreClrRuntime ? expectedOutput : null,
symbolValidator: getSymbolValidator(separateAssembly: true),
verify: Verification.Skipped);
static Action<ModuleSymbol> getSymbolValidator(bool separateAssembly)
{
return module =>
{
var @base = (separateAssembly ? module.ReferencedAssemblySymbols[1].GlobalNamespace : module.GlobalNamespace).GetTypeMember("Base");
var baseM1 = @base.GetMethod("M1");
var baseM2 = @base.GetMethod("M2");
var baseM3 = @base.GetMethod("M3");
var baseM4 = @base.GetMethod("M4");
for (int derivedI = 1; derivedI <= 2; derivedI++)
{
var derived = module.GlobalNamespace.GetTypeMember($"Derived{derivedI}");
var derivedM1 = derived.GetMethod("M1");
var derivedM2 = derived.GetMethod("M2");
var derivedM3 = derived.GetMethod("M3");
var derivedM4 = derived.GetMethod("M4");
Assert.True(baseM1.Parameters.Single().Type.Equals(derivedM1.Parameters.Single().Type, TypeCompareKind.ConsiderEverything));
Assert.True(baseM2.ReturnType.Equals(derivedM2.ReturnType, TypeCompareKind.ConsiderEverything));
Assert.True(baseM3.Parameters.Single().Type.Equals(derivedM3.Parameters.Single().Type, TypeCompareKind.ConsiderEverything));
Assert.True(baseM4.ReturnType.Equals(derivedM4.ReturnType, TypeCompareKind.ConsiderEverything));
}
};
}
}
[Theory]
[InlineData("", "ref ")]
[InlineData("", "out ")]
[InlineData("", "in ")]
[InlineData("ref ", "")]
[InlineData("ref ", "out ")]
[InlineData("ref ", "in ")]
[InlineData("out ", "")]
[InlineData("out ", "ref ")]
[InlineData("out ", "in ")]
[InlineData("in ", "")]
[InlineData("in ", "ref ")]
[InlineData("in ", "out ")]
public void Override_RefnessMustMatch_Parameters(string refKind1, string refKind2)
{
var comp = CreateCompilationWithFunctionPointers(@$"
unsafe class Base
{{
protected virtual void M1(delegate*<{refKind1}string, void> ptr) {{}}
protected virtual delegate*<{refKind1}string, void> M2() => throw null;
}}
unsafe class Derived : Base
{{
protected override void M1(delegate*<{refKind2}string, void> ptr) {{}}
protected override delegate*<{refKind2}string, void> M2() => throw null;
}}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<{refKind2} string, void>)': no suitable method found to override
// protected override void M1(delegate*<{refKind2} string, void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments($"Derived.M1(delegate*<{refKind2}string, void>)").WithLocation(9, 29),
// (10,49): error CS0508: 'Derived.M2()': return type must be 'delegate*<{refKind1} string, void>' to match overridden member 'Base.M2()'
// protected override delegate*<{refKind2} string, void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", $"delegate*<{refKind1}string, void>").WithLocation(10, 48 + refKind2.Length)
);
}
[Theory]
[InlineData(" ", "ref ")]
[InlineData(" ", "ref readonly ")]
[InlineData("ref ", " ")]
[InlineData("ref ", "ref readonly ")]
[InlineData("ref readonly ", " ")]
[InlineData("ref readonly ", "ref ")]
public void Override_RefnessMustMatch_Returns(string refKind1, string refKind2)
{
var comp = CreateCompilationWithFunctionPointers(@$"
unsafe class Base
{{
protected virtual void M1(delegate*<{refKind1}string> ptr) {{}}
protected virtual delegate*<{refKind1}string> M2() => throw null;
}}
unsafe class Derived : Base
{{
protected override void M1(delegate*<{refKind2}string> ptr) {{}}
protected override delegate*<{refKind2}string> M2() => throw null;
}}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<{refKind2} string>)': no suitable method found to override
// protected override void M1(delegate*<{refKind2} string> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments($"Derived.M1(delegate*<{(string.IsNullOrWhiteSpace(refKind2) ? "" : refKind2)}string>)").WithLocation(9, 29),
// (10,49): error CS0508: 'Derived.M2()': return type must be 'delegate*<{refKind1} string>' to match overridden member 'Base.M2()'
// protected override delegate*<{refKind2} string> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", $"delegate*<{(string.IsNullOrWhiteSpace(refKind1) ? "" : refKind1)}string>").WithLocation(10, 42 + refKind2.Length)
);
}
[Fact]
public void Override_ParameterTypesMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<object, void> ptr) {{}}
protected virtual delegate*<object, void> M2() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<string, void> ptr) {{}}
protected override delegate*<string, void> M2() => throw null;
}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<string, void>)': no suitable method found to override
// protected override void M1(delegate*<string, void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<string, void>)").WithLocation(9, 29),
// (10,48): error CS0508: 'Derived.M2()': return type must be 'delegate*<object, void>' to match overridden member 'Base.M2()'
// protected override delegate*<string, void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<object, void>").WithLocation(10, 48)
);
}
[Fact]
public void Override_ReturnTypesMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<object> ptr) {{}}
protected virtual delegate*<object> M2() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<string> ptr) {{}}
protected override delegate*<string> M2() => throw null;
}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<string>)': no suitable method found to override
// protected override void M1(delegate*<string> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<string>)").WithLocation(9, 29),
// (10,42): error CS0508: 'Derived.M2()': return type must be 'delegate*<object>' to match overridden member 'Base.M2()'
// protected override delegate*<string> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<object>").WithLocation(10, 42)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44358")]
public void Override_NintIntPtrDifferences()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<nint> ptr) {}
protected virtual delegate*<nint> M2() => throw null;
protected virtual void M3(delegate*<nint, void> ptr) {}
protected virtual delegate*<nint, void> M4() => throw null;
protected virtual void M5(delegate*<System.IntPtr> ptr) {}
protected virtual delegate*<System.IntPtr> M6() => throw null;
protected virtual void M7(delegate*<System.IntPtr, void> ptr) {}
protected virtual delegate*<System.IntPtr, void> M8() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<System.IntPtr> ptr) {}
protected override delegate*<System.IntPtr> M2() => throw null;
protected override void M3(delegate*<System.IntPtr, void> ptr) {}
protected override delegate*<System.IntPtr, void> M4() => throw null;
protected override void M5(delegate*<nint> ptr) {}
protected override delegate*<nint> M6() => throw null;
protected override void M7(delegate*<nint, void> ptr) {}
protected override delegate*<nint, void> M8() => throw null;
}");
comp.VerifyDiagnostics(
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<System.IntPtr> ptr)");
assertMethod(derived, "M2", "delegate*<System.IntPtr> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<System.IntPtr, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<System.IntPtr, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<nint> ptr)");
assertMethod(derived, "M6", "delegate*<nint> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<nint, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<nint, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_ObjectDynamicDifferences()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<dynamic> ptr) {}
protected virtual delegate*<dynamic> M2() => throw null;
protected virtual void M3(delegate*<dynamic, void> ptr) {}
protected virtual delegate*<dynamic, void> M4() => throw null;
protected virtual void M5(delegate*<object> ptr) {}
protected virtual delegate*<object> M6() => throw null;
protected virtual void M7(delegate*<object, void> ptr) {}
protected virtual delegate*<object, void> M8() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<object> ptr) {}
protected override delegate*<object> M2() => throw null;
protected override void M3(delegate*<object, void> ptr) {}
protected override delegate*<object, void> M4() => throw null;
protected override void M5(delegate*<dynamic> ptr) {}
protected override delegate*<dynamic> M6() => throw null;
protected override void M7(delegate*<dynamic, void> ptr) {}
protected override delegate*<dynamic, void> M8() => throw null;
}");
comp.VerifyDiagnostics(
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<System.Object> ptr)");
assertMethod(derived, "M2", "delegate*<System.Object> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<System.Object, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<System.Object, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<dynamic> ptr)");
assertMethod(derived, "M6", "delegate*<dynamic> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<dynamic, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<dynamic, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_TupleNameChanges()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<(int, string)> ptr) {}
protected virtual delegate*<(int, string)> M2() => throw null;
protected virtual void M3(delegate*<(int, string), void> ptr) {}
protected virtual delegate*<(int, string), void> M4() => throw null;
protected virtual void M5(delegate*<(int i, string s)> ptr) {}
protected virtual delegate*<(int i, string s)> M6() => throw null;
protected virtual void M7(delegate*<(int i, string s), void> ptr) {}
protected virtual delegate*<(int i, string s), void> M8() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<(int i, string s)> ptr) {}
protected override delegate*<(int i, string s)> M2() => throw null;
protected override void M3(delegate*<(int i, string s), void> ptr) {}
protected override delegate*<(int i, string s), void> M4() => throw null;
protected override void M5(delegate*<(int, string)> ptr) {}
protected override delegate*<(int, string)> M6() => throw null;
protected override void M7(delegate*<(int, string), void> ptr) {}
protected override delegate*<(int, string), void> M8() => throw null;
}");
comp.VerifyDiagnostics(
// (15,29): error CS8139: 'Derived.M1(delegate*<(int i, string s)>)': cannot change tuple element names when overriding inherited member 'Base.M1(delegate*<(int, string)>)'
// protected override void M1(delegate*<(int i, string s)> ptr) {}
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M1").WithArguments("Derived.M1(delegate*<(int i, string s)>)", "Base.M1(delegate*<(int, string)>)").WithLocation(15, 29),
// (16,53): error CS8139: 'Derived.M2()': cannot change tuple element names when overriding inherited member 'Base.M2()'
// protected override delegate*<(int i, string s)> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()").WithLocation(16, 53),
// (17,29): error CS8139: 'Derived.M3(delegate*<(int i, string s), void>)': cannot change tuple element names when overriding inherited member 'Base.M3(delegate*<(int, string), void>)'
// protected override void M3(delegate*<(int i, string s), void> ptr) {}
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3(delegate*<(int i, string s), void>)", "Base.M3(delegate*<(int, string), void>)").WithLocation(17, 29),
// (18,59): error CS8139: 'Derived.M4()': cannot change tuple element names when overriding inherited member 'Base.M4()'
// protected override delegate*<(int i, string s), void> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()").WithLocation(18, 59)
);
assertMethod("M1", "void Derived.M1(delegate*<(System.Int32 i, System.String s)> ptr)");
assertMethod("M2", "delegate*<(System.Int32 i, System.String s)> Derived.M2()");
assertMethod("M3", "void Derived.M3(delegate*<(System.Int32 i, System.String s), System.Void> ptr)");
assertMethod("M4", "delegate*<(System.Int32 i, System.String s), System.Void> Derived.M4()");
assertMethod("M5", "void Derived.M5(delegate*<(System.Int32, System.String)> ptr)");
assertMethod("M6", "delegate*<(System.Int32, System.String)> Derived.M6()");
assertMethod("M7", "void Derived.M7(delegate*<(System.Int32, System.String), System.Void> ptr)");
assertMethod("M8", "delegate*<(System.Int32, System.String), System.Void> Derived.M8()");
void assertMethod(string methodName, string expectedSignature)
{
var m = comp.GetMember<MethodSymbol>($"Derived.{methodName}");
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString());
}
}
[Fact]
public void Override_NullabilityChanges_NoRefs()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe class Base
{
protected virtual void M1(delegate*<string?> ptr) {}
protected virtual delegate*<string?> M2() => throw null!;
protected virtual void M3(delegate*<string?, void> ptr) {}
protected virtual delegate*<string?, void> M4() => throw null!;
protected virtual void M5(delegate*<string> ptr) {}
protected virtual delegate*<string> M6() => throw null!;
protected virtual void M7(delegate*<string, void> ptr) {}
protected virtual delegate*<string, void> M8() => throw null!;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<string> ptr) {}
protected override delegate*<string> M2() => throw null!;
protected override void M3(delegate*<string, void> ptr) {}
protected override delegate*<string, void> M4() => throw null!;
protected override void M5(delegate*<string?> ptr) {}
protected override delegate*<string?> M6() => throw null!;
protected override void M7(delegate*<string?, void> ptr) {}
protected override delegate*<string?, void> M8() => throw null!;
}");
comp.VerifyDiagnostics(
// (16,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M1(delegate*<string> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 29),
// (19,48): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<string, void> M4() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 48),
// (21,43): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<string?> M6() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 43),
// (22,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M7(delegate*<string?, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 29)
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<System.String!> ptr)");
assertMethod(derived, "M2", "delegate*<System.String!> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<System.String!, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<System.String!, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<System.String?> ptr)");
assertMethod(derived, "M6", "delegate*<System.String?> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<System.String?, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<System.String?, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_NullabilityChanges_RefsInParameterReturnTypes()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe class Base
{
protected virtual void M1(delegate*<ref string?> ptr) {}
protected virtual delegate*<ref string?> M2() => throw null!;
protected virtual void M3(delegate*<ref string?, void> ptr) {}
protected virtual delegate*<ref string?, void> M4() => throw null!;
protected virtual void M5(delegate*<ref string> ptr) {}
protected virtual delegate*<ref string> M6() => throw null!;
protected virtual void M7(delegate*<ref string, void> ptr) {}
protected virtual delegate*<ref string, void> M8() => throw null!;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<ref string> ptr) {}
protected override delegate*<ref string> M2() => throw null!;
protected override void M3(delegate*<ref string, void> ptr) {}
protected override delegate*<ref string, void> M4() => throw null!;
protected override void M5(delegate*<ref string?> ptr) {}
protected override delegate*<ref string?> M6() => throw null!;
protected override void M7(delegate*<ref string?, void> ptr) {}
protected override delegate*<ref string?, void> M8() => throw null!;
}");
comp.VerifyDiagnostics(
// (16,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M1(delegate*<ref string> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 29),
// (17,46): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string> M2() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(17, 46),
// (18,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M3(delegate*<ref string, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("ptr").WithLocation(18, 29),
// (19,52): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string, void> M4() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 52),
// (20,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M5(delegate*<ref string?> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("ptr").WithLocation(20, 29),
// (21,47): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string?> M6() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 47),
// (22,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M7(delegate*<ref string?, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 29),
// (23,53): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string?, void> M8() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M8").WithLocation(23, 53)
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<ref System.String!> ptr)");
assertMethod(derived, "M2", "delegate*<ref System.String!> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<ref System.String!, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<ref System.String!, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<ref System.String?> ptr)");
assertMethod(derived, "M6", "delegate*<ref System.String?> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<ref System.String?, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<ref System.String?, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_NullabilityChanges_PointerByRef()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
public unsafe class Base
{
public virtual void M1(ref delegate*<string?> ptr) {}
public virtual ref delegate*<string?> M2() => throw null!;
public virtual void M3(ref delegate*<string?, void> ptr) {}
public virtual ref delegate*<string?, void> M4() => throw null!;
public virtual void M5(ref delegate*<string> ptr) {}
public virtual ref delegate*<string> M6() => throw null!;
public virtual void M7(ref delegate*<string, void> ptr) {}
public virtual ref delegate*<string, void> M8() => throw null!;
}
public unsafe class Derived : Base
{
public override void M1(ref delegate*<string> ptr) {}
public override ref delegate*<string> M2() => throw null!;
public override void M3(ref delegate*<string, void> ptr) {}
public override ref delegate*<string, void> M4() => throw null!;
public override void M5(ref delegate*<string?> ptr) {}
public override ref delegate*<string?> M6() => throw null!;
public override void M7(ref delegate*<string?, void> ptr) {}
public override ref delegate*<string?, void> M8() => throw null!;
}");
comp.VerifyDiagnostics(
// (16,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M1(ref delegate*<string> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 26),
// (17,43): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string> M2() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(17, 43),
// (18,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M3(ref delegate*<string, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("ptr").WithLocation(18, 26),
// (19,49): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string, void> M4() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 49),
// (20,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M5(ref delegate*<string?> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("ptr").WithLocation(20, 26),
// (21,44): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string?> M6() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 44),
// (22,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M7(ref delegate*<string?, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 26),
// (23,50): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string?, void> M8() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M8").WithLocation(23, 50)
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(ref delegate*<System.String!> ptr)");
assertMethod(derived, "M2", "ref delegate*<System.String!> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(ref delegate*<System.String!, System.Void> ptr)");
assertMethod(derived, "M4", "ref delegate*<System.String!, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(ref delegate*<System.String?> ptr)");
assertMethod(derived, "M6", "ref delegate*<System.String?> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(ref delegate*<System.String?, System.Void> ptr)");
assertMethod(derived, "M8", "ref delegate*<System.String?, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_SingleDimensionArraySizesInMetadata()
{
var il = @"
.class public auto ansi abstract beforefieldinit Base
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig newslot abstract virtual
void M1 (method void *(int32[0...]) param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method void *(int32[0...]) M2 () cil managed
{
}
.method public hidebysig newslot abstract virtual
void M3 (method int32[0...] *() param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method int32[0...] *() M4 () cil managed
{
}
.method family hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}";
var source = @"
unsafe class Derived : Base
{
public override void M1(delegate*<int[], void> param) => throw null;
public override delegate*<int[], void> M2() => throw null;
public override void M3(delegate*<int[]> param) => throw null;
public override delegate*<int[]> M4() => throw null;
}";
var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
comp.VerifyDiagnostics(
// (2,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.M1(delegate*<int[*], void>)'
// unsafe class Derived : Base
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.M1(delegate*<int[*], void>)").WithLocation(2, 14),
// (2,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.M3(delegate*<int[*]>)'
// unsafe class Derived : Base
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.M3(delegate*<int[*]>)").WithLocation(2, 14),
// (4,26): error CS0115: 'Derived.M1(delegate*<int[], void>)': no suitable method found to override
// public override void M1(delegate*<int[], void> param) => throw null;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<int[], void>)").WithLocation(4, 26),
// (5,44): error CS0508: 'Derived.M2()': return type must be 'delegate*<int[*], void>' to match overridden member 'Base.M2()'
// public override delegate*<int[], void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<int[*], void>").WithLocation(5, 44),
// (6,26): error CS0115: 'Derived.M3(delegate*<int[]>)': no suitable method found to override
// public override void M3(delegate*<int[]> param) => throw null;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived.M3(delegate*<int[]>)").WithLocation(6, 26),
// (7,38): error CS0508: 'Derived.M4()': return type must be 'delegate*<int[*]>' to match overridden member 'Base.M4()'
// public override delegate*<int[]> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()", "delegate*<int[*]>").WithLocation(7, 38)
);
}
[Fact]
public void Override_ArraySizesInMetadata()
{
var il = @"
.class public auto ansi abstract beforefieldinit Base
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig newslot abstract virtual
void M1 (method void *(int32[5...5,2...4]) param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method void *(int32[5...5,2...4]) M2 () cil managed
{
}
.method public hidebysig newslot abstract virtual
void M3 (method int32[5...5,2...4] *() param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method int32[5...5,2...4] *() M4 () cil managed
{
}
.method family hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}";
var source = @"
using System;
unsafe class Derived : Base
{
private static void MultiDimensionParamFunc(int[,] param) { }
private static int[,] MultiDimensionReturnFunc() => null;
public override void M1(delegate*<int[,], void> param)
{
Console.WriteLine(""Multi-dimension array param as param"");
param(null);
}
public override delegate*<int[,], void> M2()
{
Console.WriteLine(""Multi-dimension array param as return"");
return &MultiDimensionParamFunc;
}
public override void M3(delegate*<int[,]> param)
{
Console.WriteLine(""Multi-dimension array return as param"");
_ = param();
}
public override delegate*<int[,]> M4()
{
Console.WriteLine(""Multi-dimension array return as return"");
return &MultiDimensionReturnFunc;
}
public static void Main()
{
var d = new Derived();
d.M1(&MultiDimensionParamFunc);
var ptr1 = d.M2();
ptr1(null);
d.M3(&MultiDimensionReturnFunc);
var ptr2 = d.M4();
_ = ptr2();
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: @"
Multi-dimension array param as param
Multi-dimension array param as return
Multi-dimension array return as param
Multi-dimension array return as return
");
verifier.VerifyIL("Derived.M1", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
.locals init (delegate*<int[,], void> V_0)
IL_0000: ldstr ""Multi-dimension array param as param""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldarg.1
IL_000b: stloc.0
IL_000c: ldnull
IL_000d: ldloc.0
IL_000e: calli ""delegate*<int[,], void>""
IL_0013: ret
}
");
verifier.VerifyIL("Derived.M2", expectedIL: @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldstr ""Multi-dimension array param as return""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldftn ""void Derived.MultiDimensionParamFunc(int[,])""
IL_0010: ret
}
");
verifier.VerifyIL("Derived.M3", expectedIL: @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldstr ""Multi-dimension array return as param""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldarg.1
IL_000b: calli ""delegate*<int[,]>""
IL_0010: pop
IL_0011: ret
}
");
verifier.VerifyIL("Derived.M4", expectedIL: @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldstr ""Multi-dimension array return as return""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldftn ""int[,] Derived.MultiDimensionReturnFunc()""
IL_0010: ret
}
");
verifier.VerifyIL("Derived.Main", expectedIL: @"
{
// Code size 55 (0x37)
.maxstack 3
.locals init (delegate*<int[,], void> V_0)
IL_0000: newobj ""Derived..ctor()""
IL_0005: dup
IL_0006: ldftn ""void Derived.MultiDimensionParamFunc(int[,])""
IL_000c: callvirt ""void Base.M1(delegate*<int[,], void>)""
IL_0011: dup
IL_0012: callvirt ""delegate*<int[,], void> Base.M2()""
IL_0017: stloc.0
IL_0018: ldnull
IL_0019: ldloc.0
IL_001a: calli ""delegate*<int[,], void>""
IL_001f: dup
IL_0020: ldftn ""int[,] Derived.MultiDimensionReturnFunc()""
IL_0026: callvirt ""void Base.M3(delegate*<int[,]>)""
IL_002b: callvirt ""delegate*<int[,]> Base.M4()""
IL_0030: calli ""delegate*<int[,]>""
IL_0035: pop
IL_0036: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var m1 = comp.GetMember<MethodSymbol>("Derived.M1");
var m2 = comp.GetMember<MethodSymbol>("Derived.M2");
var m3 = comp.GetMember<MethodSymbol>("Derived.M3");
var m4 = comp.GetMember<MethodSymbol>("Derived.M4");
var funcPtr = (FunctionPointerTypeSymbol)m1.Parameters.Single().Type;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.Parameters.Single().Type);
funcPtr = (FunctionPointerTypeSymbol)m2.ReturnType;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.Parameters.Single().Type);
funcPtr = (FunctionPointerTypeSymbol)m3.Parameters.Single().Type;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.ReturnType);
funcPtr = (FunctionPointerTypeSymbol)m4.ReturnType;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.ReturnType);
static void verifyArray(TypeSymbol type)
{
var array = (ArrayTypeSymbol)type;
Assert.False(array.IsSZArray);
Assert.Equal(2, array.Rank);
Assert.Equal(5, array.LowerBounds[0]);
Assert.Equal(1, array.Sizes[0]);
Assert.Equal(2, array.LowerBounds[1]);
Assert.Equal(3, array.Sizes[1]);
}
}
[Fact]
public void NullableUsageWarnings()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe public class C
{
static void M1(delegate*<string, string?, string?> ptr1)
{
_ = ptr1(null, null);
_ = ptr1("""", null).ToString();
delegate*<string?, string?, string?> ptr2 = ptr1;
delegate*<string, string?, string> ptr3 = ptr1;
}
static void M2(delegate*<ref string, ref string> ptr1)
{
string? str1 = null;
ptr1(ref str1);
string str2 = """";
ref string? str3 = ref ptr1(ref str2);
delegate*<ref string?, ref string> ptr2 = ptr1;
delegate*<ref string, ref string?> ptr3 = ptr1;
}
}
");
comp.VerifyDiagnostics(
// (7,18): warning CS8625: Cannot convert null literal to non-nullable reference type.
// _ = ptr1(null, null);
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 18),
// (8,13): warning CS8602: Dereference of a possibly null reference.
// _ = ptr1("", null).ToString();
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"ptr1("""", null)").WithLocation(8, 13),
// (9,53): warning CS8619: Nullability of reference types in value of type 'delegate*<string, string?, string?>' doesn't match target type 'delegate*<string?, string?, string?>'.
// delegate*<string?, string?, string?> ptr2 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<string, string?, string?>", "delegate*<string?, string?, string?>").WithLocation(9, 53),
// (10,51): warning CS8619: Nullability of reference types in value of type 'delegate*<string, string?, string?>' doesn't match target type 'delegate*<string, string?, string>'.
// delegate*<string, string?, string> ptr3 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<string, string?, string?>", "delegate*<string, string?, string>").WithLocation(10, 51),
// (16,18): warning CS8601: Possible null reference assignment.
// ptr1(ref str1);
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "str1").WithLocation(16, 18),
// (18,32): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'.
// ref string? str3 = ref ptr1(ref str2);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1(ref str2)").WithArguments("string", "string?").WithLocation(18, 32),
// (19,51): warning CS8619: Nullability of reference types in value of type 'delegate*<ref string, ref string>' doesn't match target type 'delegate*<ref string?, ref string>'.
// delegate*<ref string?, ref string> ptr2 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<ref string, ref string>", "delegate*<ref string?, ref string>").WithLocation(19, 51),
// (20,51): warning CS8619: Nullability of reference types in value of type 'delegate*<ref string, ref string>' doesn't match target type 'delegate*<ref string, ref string?>'.
// delegate*<ref string, ref string?> ptr3 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<ref string, ref string>", "delegate*<ref string, ref string?>").WithLocation(20, 51)
);
}
[ConditionalFact(typeof(CoreClrOnly))]
public void SpanInArgumentAndReturn()
{
var comp = CompileAndVerifyFunctionPointers(@"
using System;
public class C
{
static char[] chars = new[] { '1', '2', '3', '4' };
static Span<char> ChopSpan(Span<char> span) => span[..^1];
public static unsafe void Main()
{
delegate*<Span<char>, Span<char>> ptr = &ChopSpan;
Console.Write(new string(ptr(chars)));
}
}
", targetFramework: TargetFramework.NetCoreApp, expectedOutput: "123");
comp.VerifyIL("C.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (delegate*<System.Span<char>, System.Span<char>> V_0)
IL_0000: ldftn ""System.Span<char> C.ChopSpan(System.Span<char>)""
IL_0006: stloc.0
IL_0007: ldsfld ""char[] C.chars""
IL_000c: call ""System.Span<char> System.Span<char>.op_Implicit(char[])""
IL_0011: ldloc.0
IL_0012: calli ""delegate*<System.Span<char>, System.Span<char>>""
IL_0017: call ""System.ReadOnlySpan<char> System.Span<char>.op_Implicit(System.Span<char>)""
IL_001c: newobj ""string..ctor(System.ReadOnlySpan<char>)""
IL_0021: call ""void System.Console.Write(string)""
IL_0026: ret
}
");
}
[Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
public void LocalFunction_ValidStatic()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class FunctionPointer
{
public static void Main()
{
delegate*<void> a = &local;
a();
static void local() => System.Console.Write(""local"");
}
}
", expectedOutput: "local");
verifier.VerifyIL("FunctionPointer.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void FunctionPointer.<Main>g__local|0_0()""
IL_0006: calli ""delegate*<void>""
IL_000b: ret
}
");
}
[Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
public void LocalFunction_ValidStatic_NestedInLocalFunction()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class FunctionPointer
{
public static void Main()
{
local(true);
static void local(bool invoke)
{
if (invoke)
{
delegate*<bool, void> ptr = &local;
ptr(false);
}
else
{
System.Console.Write(""local"");
}
}
}
}
", expectedOutput: "local");
verifier.VerifyIL("FunctionPointer.<Main>g__local|0_0(bool)", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<bool, void> V_0)
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0012
IL_0003: ldftn ""void FunctionPointer.<Main>g__local|0_0(bool)""
IL_0009: stloc.0
IL_000a: ldc.i4.0
IL_000b: ldloc.0
IL_000c: calli ""delegate*<bool, void>""
IL_0011: ret
IL_0012: ldstr ""local""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: ret
}
");
}
[Fact]
public void LocalFunction_ValidStatic_NestedInLambda()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
public static void Main()
{
int capture = 1;
System.Action _ = () =>
{
System.Console.Write(capture); // Just to ensure that this is emitted as a capture
delegate*<void> ptr = &local;
ptr();
static void local() => System.Console.Write(""local"");
};
_();
}
}
", expectedOutput: "1local");
verifier.VerifyIL("C.<>c__DisplayClass0_0.<Main>b__0()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.capture""
IL_0006: call ""void System.Console.Write(int)""
IL_000b: ldftn ""void C.<Main>g__local|0_1()""
IL_0011: calli ""delegate*<void>""
IL_0016: ret
}
");
}
[Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
public void LocalFunction_InvalidNonStatic()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class FunctionPointer
{
public static void M()
{
int local = 1;
delegate*<void> first = &noCaptures;
delegate*<void> second = &capturesLocal;
void noCaptures() { }
void capturesLocal() { local++; }
}
}");
comp.VerifyDiagnostics(
// (8,34): error CS8759: Cannot create a function pointer for 'noCaptures()' because it is not a static method
// delegate*<void> first = &noCaptures;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "noCaptures").WithArguments("noCaptures()").WithLocation(8, 34),
// (9,35): error CS8759: Cannot create a function pointer for 'capturesLocal()' because it is not a static method
// delegate*<void> second = &capturesLocal;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "capturesLocal").WithArguments("capturesLocal()").WithLocation(9, 35)
);
}
[Fact, WorkItem(45418, "https://github.com/dotnet/roslyn/issues/45418")]
public void RefMismatchInCall()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Test
{
void M1(delegate*<ref string, void> param1)
{
param1(out var l);
string s = null;
param1(s);
param1(in s);
}
void M2(delegate*<in string, void> param2)
{
param2(out var l);
string s = null;
param2(s);
param2(ref s);
}
void M3(delegate*<out string, void> param3)
{
string s = null;
param3(s);
param3(ref s);
param3(in s);
}
void M4(delegate*<string, void> param4)
{
param4(out var l);
string s = null;
param4(ref s);
param4(in s);
}
}");
comp.VerifyDiagnostics(
// (6,20): error CS1620: Argument 1 must be passed with the 'ref' keyword
// param1(out var l);
Diagnostic(ErrorCode.ERR_BadArgRef, "var l").WithArguments("1", "ref").WithLocation(6, 20),
// (8,16): error CS1620: Argument 1 must be passed with the 'ref' keyword
// param1(s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "ref").WithLocation(8, 16),
// (9,19): error CS1620: Argument 1 must be passed with the 'ref' keyword
// param1(in s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "ref").WithLocation(9, 19),
// (14,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// param2(out var l);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var l").WithArguments("1", "out").WithLocation(14, 20),
// (17,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword
// param2(ref s);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "ref").WithLocation(17, 20),
// (23,16): error CS1620: Argument 1 must be passed with the 'out' keyword
// param3(s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(23, 16),
// (24,20): error CS1620: Argument 1 must be passed with the 'out' keyword
// param3(ref s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(24, 20),
// (25,19): error CS1620: Argument 1 must be passed with the 'out' keyword
// param3(in s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(25, 19),
// (30,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// param4(out var l);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var l").WithArguments("1", "out").WithLocation(30, 20),
// (32,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword
// param4(ref s);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "ref").WithLocation(32, 20),
// (33,19): error CS1615: Argument 1 may not be passed with the 'in' keyword
// param4(in s);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "in").WithLocation(33, 19)
);
}
[Fact]
public void MismatchedInferredLambdaReturn()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
public void M(delegate*<System.Func<string>, void> param)
{
param(a => a);
}
}");
comp.VerifyDiagnostics(
// (6,15): error CS1593: Delegate 'Func<string>' does not take 1 arguments
// param(a => a);
Diagnostic(ErrorCode.ERR_BadDelArgCount, "a => a").WithArguments("System.Func<string>", "1").WithLocation(6, 15)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
Assert.Equal("a => a", lambda.ToString());
var info = model.GetSymbolInfo(lambda);
var lambdaSymbol = (IMethodSymbol)info.Symbol!;
Assert.NotNull(lambdaSymbol);
Assert.Equal("System.String", lambdaSymbol.ReturnType.ToTestDisplayString(includeNonNullable: false));
Assert.True(lambdaSymbol.Parameters.Single().Type.IsErrorType());
}
[Fact, WorkItem(45418, "https://github.com/dotnet/roslyn/issues/45418")]
public void OutDeconstructionMismatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Test
{
void M1(delegate*<string, void> param1, object o)
{
param1(o is var (a, b));
param1(o is (var c, var d));
}
}", targetFramework: TargetFramework.Standard);
comp.VerifyDiagnostics(
// (6,25): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// param1(o is var (a, b));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a, b)").WithArguments("object", "Deconstruct").WithLocation(6, 25),
// (6,25): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// param1(o is var (a, b));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a, b)").WithArguments("object", "2").WithLocation(6, 25),
// (7,21): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// param1(o is (var c, var d));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(var c, var d)").WithArguments("object", "Deconstruct").WithLocation(7, 21),
// (7,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// param1(o is (var c, var d));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(var c, var d)").WithArguments("object", "2").WithLocation(7, 21)
);
}
[Fact]
public void UnusedLoadNotLeftOnStack()
{
string source = @"
unsafe class FunctionPointer
{
public static void Main()
{
delegate*<void> ptr = &Main;
}
}
";
var verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "", options: TestOptions.UnsafeReleaseExe);
verifier.VerifyIL(@"FunctionPointer.Main", expectedIL: @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
");
verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "", options: TestOptions.UnsafeDebugExe);
verifier.VerifyIL("FunctionPointer.Main", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (delegate*<void> V_0) //ptr
IL_0000: nop
IL_0001: ldftn ""void FunctionPointer.Main()""
IL_0007: stloc.0
IL_0008: ret
}
");
}
[Fact]
public void UnmanagedOnUnsupportedRuntime()
{
var comp = CreateCompilationWithFunctionPointers(@"
#pragma warning disable CS0168 // Unused variable
class C
{
unsafe void M()
{
delegate* unmanaged<void> ptr1;
delegate* unmanaged[Stdcall, Thiscall]<void> ptr2;
}
}", targetFramework: TargetFramework.NetStandard20);
comp.VerifyDiagnostics(
// (7,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
// delegate* unmanaged<void> ptr1;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(7, 19),
// (8,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
// delegate* unmanaged[Stdcall, Thiscall]<void> ptr2;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(8, 19)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var functionPointerSyntaxes = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().ToArray();
Assert.Equal(2, functionPointerSyntaxes.Length);
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntaxes[0],
expectedSyntax: "delegate* unmanaged<void>",
expectedType: "delegate* unmanaged<System.Void>",
expectedSymbol: "delegate* unmanaged<System.Void>");
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntaxes[1],
expectedSyntax: "delegate* unmanaged[Stdcall, Thiscall]<void>",
expectedType: "delegate* unmanaged[Stdcall, Thiscall]<System.Void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvThiscall)>",
expectedSymbol: "delegate* unmanaged[Stdcall, Thiscall]<System.Void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvThiscall)>");
}
[Fact]
public void NonPublicCallingConventionType()
{
string source1 = @"
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public class String { }
namespace Runtime.CompilerServices
{
internal class CallConvTest {}
public static class RuntimeFeature
{
public const string UnmanagedSignatureCallingConvention = nameof(UnmanagedSignatureCallingConvention);
}
}
}
";
string source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
void M()
{
delegate* unmanaged[Test]<void> ptr = null;
}
}
";
var allInCoreLib = CreateEmptyCompilation(source1 + source2, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
allInCoreLib.VerifyDiagnostics(
// (23,29): error CS8891: Type 'CallConvTest' must be public to be used as a calling convention.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeMustBePublic, "Test").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(23, 29)
);
var tree = allInCoreLib.SyntaxTrees[0];
var model = allInCoreLib.GetSemanticModel(tree);
var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>");
var coreLib = CreateEmptyCompilation(source1);
coreLib.VerifyDiagnostics();
var comp1 = CreateEmptyCompilation(source2, references: new[] { coreLib.EmitToImageReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
comp1.VerifyDiagnostics(
// (7,29): error CS8891: Type 'CallConvTest' must be public to be used as a calling convention.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeMustBePublic, "Test").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(7, 29)
);
tree = comp1.SyntaxTrees[0];
model = comp1.GetSemanticModel(tree);
functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>");
}
[Fact]
public void GenericCallingConventionType()
{
string source1 = @"
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public class String { }
namespace Runtime.CompilerServices
{
public class CallConvTest<T> {}
public static class RuntimeFeature
{
public const string UnmanagedSignatureCallingConvention = nameof(UnmanagedSignatureCallingConvention);
}
}
}
";
string source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
void M()
{
delegate* unmanaged[Test]<void> ptr = null;
}
}
";
var allInCoreLib = CreateEmptyCompilation(source1 + source2, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
allInCoreLib.VerifyDiagnostics(
// (23,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(23, 29)
);
var tree = allInCoreLib.SyntaxTrees[0];
var model = allInCoreLib.GetSemanticModel(tree);
var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var coreLib = CreateEmptyCompilation(source1);
coreLib.VerifyDiagnostics();
var comp1 = CreateEmptyCompilation(source2, references: new[] { coreLib.EmitToImageReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
comp1.VerifyDiagnostics(
// (7,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(7, 29)
);
tree = comp1.SyntaxTrees[0];
model = comp1.GetSemanticModel(tree);
functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var @string = comp1.GetSpecialType(SpecialType.System_String);
var testMod = CSharpCustomModifier.CreateOptional(comp1.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvTest`1"));
var funcPtr = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp1);
var funcPtrRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
parameterRefCustomModifiers: default, returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
compilation: comp1);
var funcPtrWithTestOnReturn = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string, customModifiers: ImmutableArray.Create(testMod)), refCustomModifiers: default,
parameterRefCustomModifiers: default, returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
compilation: comp1);
var funcPtrWithTestOnRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: ImmutableArray.Create(testMod),
parameterRefCustomModifiers: default, returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
compilation: comp1);
Assert.Empty(funcPtrWithTestOnReturn.Signature.GetCallingConventionModifiers());
Assert.Empty(funcPtrWithTestOnRef.Signature.GetCallingConventionModifiers());
Assert.True(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.ConsiderEverything));
Assert.True(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.ConsiderEverything));
}
[Fact]
public void ConventionDefinedInWrongAssembly()
{
var source1 = @"
namespace System.Runtime.CompilerServices
{
public class CallConvTest { }
}
";
var source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
static void M()
{
delegate* unmanaged[Test]<void> ptr;
}
}
";
var comp1 = CreateCompilationWithFunctionPointers(source1 + source2);
comp1.VerifyDiagnostics(
// (12,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(12, 29)
);
var tree = comp1.SyntaxTrees[0];
var model = comp1.GetSemanticModel(tree);
var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var reference = CreateCompilation(source1);
var comp2 = CreateCompilationWithFunctionPointers(source2, new[] { reference.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (7,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(7, 29)
);
tree = comp2.SyntaxTrees[0];
model = comp2.GetSemanticModel(tree);
functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var @string = comp2.GetSpecialType(SpecialType.System_String);
var testMod = CSharpCustomModifier.CreateOptional(comp2.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvTest"));
var funcPtr = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
var funcPtrRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
var funcPtrWithTestOnReturn = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string, customModifiers: ImmutableArray.Create(testMod)), refCustomModifiers: default,
returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
var funcPtrWithTestOnRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: ImmutableArray.Create(testMod),
returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
Assert.Empty(funcPtrWithTestOnReturn.Signature.GetCallingConventionModifiers());
Assert.Empty(funcPtrWithTestOnRef.Signature.GetCallingConventionModifiers());
Assert.True(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.ConsiderEverything));
Assert.True(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.ConsiderEverything));
}
private const string UnmanagedCallersOnlyAttribute = @"
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public Type[] CallConvs;
public string EntryPoint;
}
}
";
private const string UnmanagedCallersOnlyAttributeIl = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute
extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
}
}
";
[Fact]
public void UnmanagedCallersOnlyRequiresStatic()
{
var comp = CreateCompilation(new[] { @"
#pragma warning disable 8321 // Unreferenced local function
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
void M1() {}
public void M2()
{
[UnmanagedCallersOnly]
void local() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6),
// (11,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(11, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyAllowedOnStatics()
{
var comp = CreateCompilation(new[] { @"
#pragma warning disable 8321 // Unreferenced local function
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
static void M1() {}
public void M2()
{
[UnmanagedCallersOnly]
static void local() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustComeFromCorrectNamespace()
{
var comp = CreateEmptyCompilation(new[] { @"
using System.Runtime.InteropServices;
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public abstract partial class Enum : ValueType {}
public class String { }
public struct Boolean { }
public struct Int32 { }
public class Type { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) {}
public bool Inherited { get; set; }
}
public enum AttributeTargets { Method = 0x0040, }
}
class CallConvTest
{
}
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (26,6): error CS8893: 'CallConvTest' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })").WithArguments("CallConvTest").WithLocation(26, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustNotBeNestedType()
{
var comp = CreateEmptyCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public abstract partial class Enum : ValueType {}
public class String { }
public struct Boolean { }
public struct Int32 { }
public class Type { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) {}
public bool Inherited { get; set; }
}
public enum AttributeTargets { Method = 0x0040, }
namespace Runtime.CompilerServices
{
public class CallConvTestA
{
public class CallConvTestB { }
}
}
}
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (31,6): error CS8893: 'CallConvTestA.CallConvTestB' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })").WithArguments("System.Runtime.CompilerServices.CallConvTestA.CallConvTestB").WithLocation(31, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustComeFromCorelib()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices
{
class CallConvTest
{
}
}
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,6): error CS8893: 'CallConvTest' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(12, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustStartWithCallConv()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(ExtensionAttribute) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,6): error CS8893: 'ExtensionAttribute' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.ExtensionAttribute) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(ExtensionAttribute) })").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(6, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvNull_InSource()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new System.Type[] { null })]
static void M() {}
unsafe static void M1()
{
delegate* unmanaged<void> ptr = &M;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'null' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new System.Type[] { null })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new System.Type[] { null })").WithArguments("null").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvNull_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static void M () cil managed
{
// [UnmanagedCallersOnly(CallConvs = new Type[] { null })]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 01 00 53 1d 50 09 43 61 6c 6c 43 6f 6e 76
73 01 00 00 00 ff
)
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
class D
{
unsafe static void M1()
{
C.M();
delegate* unmanaged<void> ptr = &C.M;
}
}
", il);
comp.VerifyDiagnostics(
// (6,9): error CS8901: 'C.M()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// C.M();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M()").WithArguments("C.M()").WithLocation(6, 9)
);
var c = comp.GetTypeByMetadataName("C");
var m1 = c.GetMethod("M");
var unmanagedData = m1.GetUnmanagedCallersOnlyAttributeData(forceComplete: true);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.Uninitialized);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound);
Assert.Empty(unmanagedData!.CallingConventionTypes);
}
[Fact]
public void UnmanagedCallersOnlyCallConvDefault()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new System.Type[] { default })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'null' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new System.Type[] { default })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new System.Type[] { default })").WithArguments("null").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_Errors()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
static string M1() => throw null;
[UnmanagedCallersOnly]
static void M2(object o) {}
[UnmanagedCallersOnly]
static T M3<T>() => throw null;
[UnmanagedCallersOnly]
static void M4<T>(T t) {}
[UnmanagedCallersOnly]
static T M5<T>() where T : struct => throw null;
[UnmanagedCallersOnly]
static void M6<T>(T t) where T : struct {}
[UnmanagedCallersOnly]
static T M7<T>() where T : unmanaged => throw null;
[UnmanagedCallersOnly]
static void M8<T>(T t) where T : unmanaged {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,12): error CS8894: Cannot use 'string' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static string M1() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "string").WithArguments("string", "return").WithLocation(6, 12),
// (9,20): error CS8894: Cannot use 'object' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M2(object o) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "object o").WithArguments("object", "parameter").WithLocation(9, 20),
// (11,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(11, 6),
// (12,12): error CS8894: Cannot use 'T' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static T M3<T>() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T").WithArguments("T", "return").WithLocation(12, 12),
// (14,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(14, 6),
// (15,23): error CS8894: Cannot use 'T' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M4<T>(T t) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T t").WithArguments("T", "parameter").WithLocation(15, 23),
// (17,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(17, 6),
// (18,12): error CS8894: Cannot use 'T' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static T M5<T>() where T : struct => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T").WithArguments("T", "return").WithLocation(18, 12),
// (20,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(20, 6),
// (21,23): error CS8894: Cannot use 'T' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M6<T>(T t) where T : struct {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T t").WithArguments("T", "parameter").WithLocation(21, 23),
// (23,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 6),
// (26,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(26, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_Valid()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
#pragma warning disable CS0169 // unused private field
struct S
{
private int _field;
}
class C
{
[UnmanagedCallersOnly]
static int M1() => throw null;
[UnmanagedCallersOnly]
static void M2(int o) {}
[UnmanagedCallersOnly]
static S M3() => throw null;
[UnmanagedCallersOnly]
public static void M4(S s) {}
[UnmanagedCallersOnly]
static int? M5() => throw null;
[UnmanagedCallersOnly]
static void M6(int? o) {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_MethodWithGenericParameter()
{
var comp = CreateCompilation(new[] { @"
#pragma warning disable CS8321 // Unused local function
using System.Runtime.InteropServices;
public struct S<T> where T : unmanaged
{
public T t;
}
class C
{
[UnmanagedCallersOnly] // 1
static S<T> M1<T>() where T : unmanaged => throw null;
[UnmanagedCallersOnly] // 2
static void M2<T>(S<T> o) where T : unmanaged {}
static void M3<T>()
{
[UnmanagedCallersOnly] // 3
static void local1() {}
static void local2()
{
[UnmanagedCallersOnly] // 4
static void local3() { }
}
System.Action a = () =>
{
[UnmanagedCallersOnly] // 5
static void local4() { }
};
}
static void M4()
{
[UnmanagedCallersOnly] // 6
static void local2<T>() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 1
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(10, 6),
// (13,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 2
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(13, 6),
// (18,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 3
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(18, 10),
// (23,14): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 4
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 14),
// (29,14): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 5
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(29, 14),
// (36,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 6
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(36, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiredUnmanagedTypes_MethodWithGenericParameter_InIl()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C extends [mscorlib]System.Object
{
.method public hidebysig static void M<T> () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
unsafe
{
delegate* unmanaged<void> ptr = C.M<int>;
}", il, options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (4,37): error CS0570: 'C.M<T>()' is not supported by the language
// delegate* unmanaged<void> ptr = C.M<int>;
Diagnostic(ErrorCode.ERR_BindToBogus, "C.M<int>").WithArguments("C.M<T>()").WithLocation(4, 37)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeWithGenericParameter()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T> where T : unmanaged
{
public T t;
}
class C<T> where T : unmanaged
{
[UnmanagedCallersOnly] // 1
static S<T> M1() => throw null;
[UnmanagedCallersOnly] // 2
static void M2(S<T> o) {}
[UnmanagedCallersOnly] // 3
static S<int> M3() => throw null;
[UnmanagedCallersOnly] // 4
static void M4(S<int> o) {}
class C2
{
[UnmanagedCallersOnly] // 5
static void M5() {}
}
struct S2
{
[UnmanagedCallersOnly] // 6
static void M6() {}
}
#pragma warning disable CS8321 // Unused local function
static void M7()
{
[UnmanagedCallersOnly] // 7
static void local1() { }
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (9,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 1
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(9, 6),
// (12,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 2
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(12, 6),
// (15,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 3
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(15, 6),
// (18,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 4
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(18, 6),
// (23,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 5
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 10),
// (29,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 6
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(29, 10),
// (36,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 7
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(36, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeWithGenericParameter_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Object
{
// Nested Types
.class nested public auto ansi beforefieldinit NestedClass<T> extends [mscorlib]System.Object
{
.method public hidebysig static void M2 () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
.class nested public sequential ansi sealed beforefieldinit NestedStruct<T> extends [mscorlib]System.ValueType
{
.pack 0
.size 1
// Methods
.method public hidebysig static void M3 () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
.method public hidebysig static void M1 () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
unsafe
{
delegate* unmanaged<void> ptr1 = &C<int>.M1;
delegate* unmanaged<void> ptr2 = &C<int>.NestedClass.M2;
delegate* unmanaged<void> ptr3 = &C<int>.NestedStruct.M3;
}
", il, options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (4,39): error CS0570: 'C<T>.M1()' is not supported by the language
// delegate* unmanaged<void> ptr1 = &C<int>.M1;
Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.M1").WithArguments("C<T>.M1()").WithLocation(4, 39),
// (5,39): error CS0570: 'C<T>.NestedClass.M2()' is not supported by the language
// delegate* unmanaged<void> ptr2 = &C<int>.NestedClass.M2;
Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.NestedClass.M2").WithArguments("C<T>.NestedClass.M2()").WithLocation(5, 39),
// (6,39): error CS0570: 'C<T>.NestedStruct.M3()' is not supported by the language
// delegate* unmanaged<void> ptr3 = &C<int>.NestedStruct.M3;
Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.NestedStruct.M3").WithArguments("C<T>.NestedStruct.M3()").WithLocation(6, 39)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeAndMethodWithGenericParameter()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C<T1>
{
[UnmanagedCallersOnly]
static void M<T2>() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_StructWithGenericParameters_1()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T>
{
public T t;
}
class C
{
[UnmanagedCallersOnly]
static S<int> M1() => throw null;
[UnmanagedCallersOnly]
static void M2(S<int> o) {}
[UnmanagedCallersOnly]
static S<S<int>> M2() => throw null;
[UnmanagedCallersOnly]
static void M3(S<S<int>> o) {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_StructWithGenericParameters_2()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T>
{
public T t;
}
class C
{
[UnmanagedCallersOnly]
static S<object> M1() => throw null;
[UnmanagedCallersOnly]
static void M2(S<object> o) {}
[UnmanagedCallersOnly]
static S<S<object>> M2() => throw null;
[UnmanagedCallersOnly]
static void M3(S<S<object>> o) {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,12): error CS8894: Cannot use 'S<object>' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static S<object> M1() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<object>").WithArguments("S<object>", "return").WithLocation(10, 12),
// (13,20): error CS8894: Cannot use 'S<object>' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M2(S<object> o) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<object> o").WithArguments("S<object>", "parameter").WithLocation(13, 20),
// (16,12): error CS8894: Cannot use 'S<S<object>>' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static S<S<object>> M2() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<S<object>>").WithArguments("S<S<object>>", "return").WithLocation(16, 12),
// (19,20): error CS8894: Cannot use 'S<S<object>>' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M3(S<S<object>> o) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<S<object>> o").WithArguments("S<S<object>>", "parameter").WithLocation(19, 20)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCallMethodDirectly()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M1() { }
public static unsafe void M2()
{
M1();
delegate*<void> p1 = &M1;
delegate* unmanaged<void> p2 = &M1;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "M1()", isSuppressed: false).WithArguments("C.M1()").WithLocation(10, 9),
// (11,31): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("C.M1()", "Default").WithLocation(11, 31)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCallMethodDirectlyWithAlias()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
using E = D;
public class C
{
public static unsafe void M2()
{
E.M1();
delegate*<void> p1 = &E.M1;
delegate* unmanaged<void> p2 = &E.M1;
}
}
public class D
{
[UnmanagedCallersOnly]
public static void M1() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'D.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// E.M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "E.M1()", isSuppressed: false).WithArguments("D.M1()").WithLocation(8, 9),
// (9,31): error CS8786: Calling convention of 'D.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &E.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "E.M1", isSuppressed: false).WithArguments("D.M1()", "Default").WithLocation(9, 31)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCallMethodDirectlyWithUsingStatic()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
using static D;
public class C
{
public static unsafe void M2()
{
M1();
delegate*<void> p1 = &M1;
delegate* unmanaged<void> p2 = &M1;
}
}
public class D
{
[UnmanagedCallersOnly]
public static void M1() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'D.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "M1()", isSuppressed: false).WithArguments("D.M1()").WithLocation(8, 9),
// (9,31): error CS8786: Calling convention of 'D.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("D.M1()", "Default").WithLocation(9, 31)
);
}
[Fact]
public void UnmanagedCallersOnlyReferencedFromMetadata()
{
var comp0 = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M1() { }
}
", UnmanagedCallersOnlyAttribute });
validate(comp0.ToMetadataReference());
validate(comp0.EmitToImageReference());
static void validate(MetadataReference reference)
{
var comp1 = CreateCompilationWithFunctionPointers(@"
class D
{
public static unsafe void M2()
{
C.M1();
delegate*<void> p1 = &C.M1;
delegate* unmanaged<void> p2 = &C.M1;
}
}
", references: new[] { reference }, targetFramework: TargetFramework.Standard);
comp1.VerifyDiagnostics(
// (6,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// C.M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M1()").WithArguments("C.M1()").WithLocation(6, 9),
// (7,31): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1", isSuppressed: false).WithArguments("C.M1()", "Default").WithLocation(7, 31),
// (8,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
// delegate* unmanaged<void> p2 = &C.M1;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(8, 19)
);
}
}
[Fact]
public void UnmanagedCallersOnlyReferencedFromMetadata_BadTypeInList()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
void M1 () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 01 00 53 1d 50 09 43 61 6c 6c 43 6f 6e 76
73 01 00 00 00 68 53 79 73 74 65 6d 2e 4f 62 6a
65 63 74 2c 20 53 79 73 74 65 6d 2e 50 72 69 76
61 74 65 2e 43 6f 72 65 4c 69 62 2c 20 56 65 72
73 69 6f 6e 3d 34 2e 30 2e 30 2e 30 2c 20 43 75
6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50
75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 37 63
65 63 38 35 64 37 62 65 61 37 37 39 38 65
)
ret
}
}";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
class D
{
public unsafe static void M2()
{
C.M1();
delegate* unmanaged<void> ptr = &C.M1;
}
}
", il);
comp.VerifyDiagnostics(
// (6,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// C.M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M1()").WithArguments("C.M1()").WithLocation(6, 9)
);
var c = comp.GetTypeByMetadataName("C");
var m1 = c.GetMethod("M1");
var unmanagedData = m1.GetUnmanagedCallersOnlyAttributeData(forceComplete: true);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.Uninitialized);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound);
Assert.Empty(unmanagedData!.CallingConventionTypes);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnInstanceMethod()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig
instance void M1 () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
c.M1();
}
}
", il);
comp.VerifyDiagnostics(
// (6,11): error CS0570: 'C.M1()' is not supported by the language
// c.M1();
Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("C.M1()").WithLocation(6, 11)
);
}
[Fact]
[WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")]
public void UnmanagedCallersOnlyDefinedOnConversion()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname static
int32 op_Implicit (
class C i
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
IL_0000: ldc.i4.0
IL_0001: ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
}
}
";
var comp = CreateCompilationWithIL(@"
class Test
{
void M(C x)
{
_ = (int)x;
}
}
", il);
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnProperty_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
static int Prop
{
[UnmanagedCallersOnly] get => throw null;
[UnmanagedCallersOnly] set => throw null;
}
static void M()
{
Prop = 1;
_ = Prop;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] get => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10),
// (8,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] set => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnProperty_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig specialname static
int32 get_Prop () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.method public hidebysig specialname static
void set_Prop (
int32 'value'
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.property int32 Prop()
{
.get int32 C::get_Prop()
.set void C::set_Prop(int32)
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2()
{
C.Prop = 1;
_ = C.Prop;
}
}
", il);
comp.VerifyDiagnostics(
// (6,11): error CS0570: 'C.Prop.set' is not supported by the language
// C.Prop = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.set").WithLocation(6, 11),
// (7,15): error CS0570: 'C.Prop.get' is not supported by the language
// _ = C.Prop;
Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.get").WithLocation(7, 15)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnPropertyRefReadonlyGetterAsLvalue_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
static ref int Prop { [UnmanagedCallersOnly] get => throw null; }
static void M()
{
Prop = 1;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,28): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// static int Prop { [UnmanagedCallersOnly] get {} }
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 28)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnPropertyRefReadonlyGetterAsLvalue_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig specialname static
int32& get_Prop () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
} // end of method C::get_Prop
// Properties
.property int32& Prop()
{
.get int32& C::get_Prop()
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2()
{
C.Prop = 1;
}
}
", il);
comp.VerifyDiagnostics(
// (6,11): error CS0570: 'C.Prop.get' is not supported by the language
// C.Prop = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.get").WithLocation(6, 11)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnIndexer_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
01 00 04 49 74 65 6d 00 00
)
// Methods
.method public hidebysig specialname
instance void set_Item (
int32 i,
int32 'value'
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
nop
ret
} // end of method C::set_Item
.method public hidebysig specialname
instance int32 get_Item (
int32 i
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
} // end of method C::get_Item
// Properties
.property instance int32 Item(
int32 i
)
{
.get instance int32 C::get_Item(int32)
.set instance void C::set_Item(int32, int32)
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
c[1] = 1;
_ = c[0];
}
}
", il);
comp.VerifyDiagnostics(
// (6,10): error CS0570: 'C.this[int].set' is not supported by the language
// c[1] = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "[1]").WithArguments("C.this[int].set").WithLocation(6, 10),
// (7,14): error CS0570: 'C.this[int].get' is not supported by the language
// _ = c[0];
Diagnostic(ErrorCode.ERR_BindToBogus, "[0]").WithArguments("C.this[int].get").WithLocation(7, 14)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnIndexer_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
public int this[int i]
{
[UnmanagedCallersOnly] set => throw null;
[UnmanagedCallersOnly] get => throw null;
}
static void M(C c)
{
c[1] = 1;
_ = c[0];
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] set => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10),
// (8,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] get => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnIndexerRefReturnAsLvalue_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
01 00 04 49 74 65 6d 00 00
)
// Methods
.method public hidebysig specialname
instance int32& get_Item (
int32 i
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
} // end of method C::get_Item
// Properties
.property instance int32& Item(
int32 i
)
{
.get instance int32& C::get_Item(int32)
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
c[1] = 1;
_ = c[0];
}
}
", il);
comp.VerifyDiagnostics(
// (6,10): error CS0570: 'C.this[int].get' is not supported by the language
// c[1] = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "[1]").WithArguments("C.this[int].get").WithLocation(6, 10),
// (7,14): error CS0570: 'C.this[int].get' is not supported by the language
// _ = c[0];
Diagnostic(ErrorCode.ERR_BindToBogus, "[0]").WithArguments("C.this[int].get").WithLocation(7, 14)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnBinaryOperator_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static C operator +(C c1, C c2) => null;
static void M(C c1, C c2)
{
_ = c1 + c2;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnBinaryOperator_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname static
class C op_Addition (
class C c1,
class C c2
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
ret
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c1, C c2)
{
_ = c1 + c2;
}
}
", il);
comp.VerifyDiagnostics(
// (6,13): error CS0570: 'C.operator +(C, C)' is not supported by the language
// _ = c1 + c2;
Diagnostic(ErrorCode.ERR_BindToBogus, "c1 + c2").WithArguments("C.operator +(C, C)").WithLocation(6, 13)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnUnaryOperator_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static C operator +(C c) => null;
static void M(C c)
{
_ = +c;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnUnaryOperator_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname static
class C op_UnaryPlus (
class C c1
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
ret
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c1, C c2)
{
_ = +c1;
}
}
", il);
comp.VerifyDiagnostics(
// (6,13): error CS0570: 'C.operator +(C)' is not supported by the language
// _ = +c1;
Diagnostic(ErrorCode.ERR_BindToBogus, "+c1").WithArguments("C.operator +(C)").WithLocation(6, 13)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnGetEnumerator_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> GetEnumerator () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
foreach (var i in c) {}
}
}
", il);
comp.VerifyDiagnostics(
// (6,27): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'
// foreach (var i in c) {}
Diagnostic(ErrorCode.ERR_ForEachMissingMember, "c").WithArguments("C", "GetEnumerator").WithLocation(6, 27)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnGetEnumeratorExtension()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
public static void M2(S s)
{
foreach (var i in s) {}
}
}
public struct SEnumerator
{
public bool MoveNext() => throw null;
public int Current => throw null;
}
public static class CExt
{
[UnmanagedCallersOnly]
public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,9): error CS8901: 'CExt.GetEnumerator(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// foreach (var i in s) {}
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "foreach").WithArguments("CExt.GetEnumerator(S)").WithLocation(7, 9)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnMoveNext()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
public static void M2(S s)
{
foreach (var i in s) {}
}
}
public struct SEnumerator
{
[UnmanagedCallersOnly]
public bool MoveNext() => throw null;
public int Current => throw null;
}
public static class CExt
{
public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(12, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnPatternDispose()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
public static void M2(S s)
{
foreach (var i in s) {}
}
}
public ref struct SEnumerator
{
public bool MoveNext() => throw null;
public int Current => throw null;
[UnmanagedCallersOnly]
public void Dispose() => throw null;
}
public static class CExt
{
public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCaptureToDelegate()
{
var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M1() { }
public static void M2()
{
Action a = M1;
a = local;
a = new Action(M1);
a = new Action(local);
[UnmanagedCallersOnly]
static void local() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (11,20): error CS8902: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// Action a = M1;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M1").WithArguments("C.M1()").WithLocation(11, 20),
// (12,13): error CS8902: 'local()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// a = local;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "local").WithArguments("local()").WithLocation(12, 13),
// (13,24): error CS8902: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// a = new Action(M1);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M1").WithArguments("C.M1()").WithLocation(13, 24),
// (14,24): error CS8902: 'local()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// a = new Action(local);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "local").WithArguments("local()").WithLocation(14, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCaptureToDelegate_OverloadStillPicked()
{
var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M(int s) { }
public static void M(object o) { }
void N()
{
Action<int> a = M;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (13,25): error CS8902: 'C.M(int)' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// Action<int> a = M;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M").WithArguments("C.M(int)").WithLocation(13, 25)
);
}
[Fact]
public void UnmanagedCallersOnlyOnExtensionsCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
struct S
{
static void M(S s)
{
s.Extension();
CExt.Extension(s);
}
}
static class CExt
{
[UnmanagedCallersOnly]
public static void Extension(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'CExt.Extension(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// s.Extension();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s.Extension()").WithArguments("CExt.Extension(S)").WithLocation(8, 9),
// (9,9): error CS8901: 'CExt.Extension(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// CExt.Extension(s);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "CExt.Extension(s)").WithArguments("CExt.Extension(S)").WithLocation(9, 9)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionDeconstructCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Collections.Generic;
using System.Runtime.InteropServices;
struct S
{
static void M(S s, List<S> ls)
{
var (i1, i2) = s;
(i1, i2) = s;
foreach (var (_, _) in ls) { }
_ = s is (int _, int _);
}
}
static class CExt
{
[UnmanagedCallersOnly]
public static void Deconstruct(this S s, out int i1, out int i2) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (9,24): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// var (i1, i2) = s;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(9, 24),
// (10,20): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// (i1, i2) = s;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(10, 20),
// (11,32): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// foreach (var (_, _) in ls) { }
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "ls").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(11, 32),
// (12,18): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = s is (int _, int _);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "(int _, int _)").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(12, 18)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionAddCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
struct S : IEnumerable
{
static void M(S s, List<S> ls)
{
_ = new S() { 1, 2, 3 };
}
public IEnumerator GetEnumerator() => throw null;
}
static class CExt
{
[UnmanagedCallersOnly]
public static void Add(this S s, int i) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,23): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = new S() { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "1").WithArguments("CExt.Add(S, int)").WithLocation(10, 23),
// (10,26): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = new S() { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "2").WithArguments("CExt.Add(S, int)").WithLocation(10, 26),
// (10,29): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = new S() { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "3").WithArguments("CExt.Add(S, int)").WithLocation(10, 29)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionGetAwaiterCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
struct S
{
static async void M(S s)
{
await s;
}
}
public struct Result : System.Runtime.CompilerServices.INotifyCompletion
{
public int GetResult() => throw null;
public void OnCompleted(System.Action continuation) => throw null;
public bool IsCompleted => throw null;
}
static class CExt
{
[UnmanagedCallersOnly]
public static Result GetAwaiter(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'CExt.GetAwaiter(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// await s;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "await s").WithArguments("CExt.GetAwaiter(S)").WithLocation(8, 9)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionGetPinnableReferenceCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
struct S
{
static void M(S s)
{
unsafe
{
fixed (int* i = s)
{
}
}
}
}
static class CExt
{
[UnmanagedCallersOnly]
public static ref int GetPinnableReference(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (10,29): error CS8901: 'CExt.GetPinnableReference(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// fixed (int* i = s)
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.GetPinnableReference(S)").WithLocation(10, 29)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_1()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (6,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static void Main() {}
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(6, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_2()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
public static void Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (5,24): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
// public static void Main() {}
Diagnostic(ErrorCode.ERR_MultipleEntryPoints, "Main").WithLocation(5, 24),
// (10,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static void Main() {}
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(10, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_3()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
public static void Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyOnMain_4()
{
var comp = CreateCompilation(new[] { @"
using System.Threading.Tasks;
using System.Runtime.InteropServices;
class C
{
public static async Task Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static async Task Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (6,30): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_MultipleEntryPoints, "Main").WithLocation(6, 30),
// (6,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(6, 30),
// (11,25): error CS8894: Cannot use 'Task' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "Task").WithArguments("System.Threading.Tasks.Task", "return").WithLocation(11, 25),
// (11,30): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(11, 30),
// (11,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(11, 30)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_5()
{
var comp = CreateCompilation(new[] { @"
using System.Threading.Tasks;
using System.Runtime.InteropServices;
class C
{
public static void Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static async Task Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (11,25): error CS8894: Cannot use 'Task' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "Task").WithArguments("System.Threading.Tasks.Task", "return").WithLocation(11, 25),
// (11,30): warning CS8892: Method 'D.Main()' will not be used as an entry point because a synchronous entry point 'C.Main()' was found.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("D.Main()", "C.Main()").WithLocation(11, 30),
// (11,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(11, 30)
);
}
[Fact, WorkItem(47858, "https://github.com/dotnet/roslyn/issues/47858")]
public void UnmanagedCallersOnlyOnMain_GetEntryPoint()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static void Main()
{
}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
var method = comp.GetEntryPoint(System.Threading.CancellationToken.None);
Assert.Equal("void C.Main()", method.ToTestDisplayString());
comp.VerifyDiagnostics(
// (6,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static void Main()
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main", isSuppressed: false).WithLocation(6, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyOnModuleInitializer()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
public class C
{
[UnmanagedCallersOnly, ModuleInitializer]
public static void M1() {}
[ModuleInitializer, UnmanagedCallersOnly]
public static void M2() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (9,28): error CS8900: Module initializer cannot be attributed with 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly, ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly, "ModuleInitializer").WithLocation(9, 28),
// (12,6): error CS8900: Module initializer cannot be attributed with 'UnmanagedCallersOnly'.
// [ModuleInitializer, UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly, "ModuleInitializer").WithLocation(12, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyMultipleApplications()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })]
[UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
public static void M1() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'string' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })").WithArguments("string").WithLocation(5, 6),
// (6,6): error CS0579: Duplicate 'UnmanagedCallersOnly' attribute
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
Diagnostic(ErrorCode.ERR_DuplicateAttribute, "UnmanagedCallersOnly").WithArguments("UnmanagedCallersOnly").WithLocation(6, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInDefinition_1()
{
var comp = CreateCompilation(@"
#nullable enable
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public Type[]? CallConvs;
public string? EntryPoint;
[UnmanagedCallersOnly]
static void M() {}
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInDefinition_2()
{
var comp = CreateCompilation(@"
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
public UnmanagedCallersOnlyAttribute() { }
public Type[] CallConvs;
}
}
");
comp.VerifyDiagnostics(
// (7,10): error CS8893: 'UnmanagedCallersOnlyAttribute' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })").WithArguments("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute").WithLocation(7, 10),
// (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_1()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })]
public static void Func() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'C' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })").WithArguments("C").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_2()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class A
{
struct B { }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })]
static void F() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,6): error CS8893: 'A.B' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })").WithArguments("A.B").WithLocation(6, 6)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/47125")]
public void UnmanagedCallersOnlyWithLoopInUsage_3()
{
// Remove UnmanagedCallersOnlyWithLoopInUsage_3_Release when
// this is unskipped.
var comp = CreateCompilation(new[] { @"
#nullable enable
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = F())]
static Type[] F() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(IsRelease))]
public void UnmanagedCallersOnlyWithLoopInUsage_3_Release()
{
// The bug in UnmanagedCallersOnlyWithLoopInUsage_3 is only
// triggered by the nullablewalker, which is unconditionally
// run in debug mode. We also want to verify the use-site
// diagnostic for unmanagedcallersonly does not cause a loop,
// so we have a separate version that does not have nullable
// enabled and only runs in release to verify. When
// https://github.com/dotnet/roslyn/issues/47125 is fixed, this
// test can be removed
var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = F())]
static Type[] F() => null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,39): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// [UnmanagedCallersOnly(CallConvs = F())]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()").WithArguments("C.F()").WithLocation(6, 39),
// (6,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [UnmanagedCallersOnly(CallConvs = F())]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()").WithLocation(6, 39)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_4()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
unsafe class Attr : Attribute
{
public Attr(delegate*<void> d) {}
}
unsafe class C
{
[UnmanagedCallersOnly]
[Attr(&M1)]
static void M1()
{
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,6): error CS0181: Attribute constructor parameter 'd' has type 'delegate*<void>', which is not a valid attribute parameter type
// [Attr(&M1)]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr", isSuppressed: false).WithArguments("d", "delegate*<void>").WithLocation(12, 6)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/47125")]
public void UnmanagedCallersOnlyWithLoopInUsage_5()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class Attr : Attribute
{
public Attr(int i) {}
}
unsafe class C
{
[UnmanagedCallersOnly]
[Attr(F())]
static int F()
{
return 0;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,11): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// [Attr(F())]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F()").WithLocation(12, 11),
// (12,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Attr(F())]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()", isSuppressed: false).WithLocation(12, 11)
);
}
[ConditionalFact(typeof(IsRelease))]
public void UnmanagedCallersOnlyWithLoopInUsage_5_Release()
{
// The bug in UnmanagedCallersOnlyWithLoopInUsage_5 is only
// triggered by the nullablewalker, which is unconditionally
// run in debug mode. We also want to verify the use-site
// diagnostic for unmanagedcallersonly does not cause a loop,
// so we have a separate version that does not have nullable
// enabled and only runs in release to verify. When
// https://github.com/dotnet/roslyn/issues/47125 is fixed, this
// test can be removed
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class Attr : Attribute
{
public Attr(int i) {}
}
unsafe class C
{
[UnmanagedCallersOnly]
[Attr(F())]
static int F()
{
return 0;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,11): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// [Attr(F())]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F()").WithLocation(12, 11),
// (12,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Attr(F())]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()", isSuppressed: false).WithLocation(12, 11)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_6()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvFastcall) })]
static void F(int i = G(&F)) { }
static int G(delegate*unmanaged[Fastcall]<int, void> d) => 0;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,27): error CS1736: Default parameter value for 'i' must be a compile-time constant
// static void F(int i = G(&F)) { }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "G(&F)", isSuppressed: false).WithArguments("i").WithLocation(7, 27)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_7()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvFastcall) })]
static int F(int i = F()) => 0;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,26): error CS8901: 'C.F(int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// static int F(int i = F()) => 0;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F(int)").WithLocation(7, 26),
// (7,26): error CS1736: Default parameter value for 'i' must be a compile-time constant
// static int F(int i = F()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()", isSuppressed: false).WithArguments("i").WithLocation(7, 26)
);
}
[Fact]
public void UnmanagedCallersOnlyUnrecognizedConstructor()
{
var comp = CreateCompilation(@"
using System.Runtime.InteropServices;
public class C
{
// Invalid typeof for the regular constructor, non-static method
[UnmanagedCallersOnly(CallConvs: new[] { typeof(string) })]
public void M() {}
}
#nullable enable
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute(Type[]? CallConvs)
{
}
public string? EntryPoint;
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyCallConvsWithADifferentType()
{
var definition = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
public static void M1() {}
}
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public string EntryPoint;
public object CallConvs;
}
}
";
var usage = @"
class D
{
unsafe void M2()
{
delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
}
}
";
var allInOne = CreateCompilationWithFunctionPointers(definition + usage);
allInOne.VerifyDiagnostics(
// (27,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(27, 51)
);
var definitionComp = CreateCompilation(definition);
var usageComp = CreateCompilationWithFunctionPointers(usage, new[] { definitionComp.EmitToImageReference() });
usageComp.VerifyDiagnostics(
// (6,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(6, 51)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsWithADifferentType_2()
{
var definition = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
public static void M1() {}
}
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public string EntryPoint;
public object[] CallConvs;
}
}
";
var usage = @"
class D
{
unsafe void M2()
{
delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
}
}
";
var allInOne = CreateCompilationWithFunctionPointers(definition + usage);
allInOne.VerifyDiagnostics(
// (27,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(27, 51)
);
var definitionComp = CreateCompilation(definition);
var usageComp = CreateCompilationWithFunctionPointers(usage, new[] { definitionComp.EmitToImageReference() });
usageComp.VerifyDiagnostics(
// (6,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(6, 51)
);
}
[Fact]
public void UnmanagedCallersOnly_CallConvsAsProperty()
{
string source1 = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public Type[] CallConvs { get; set; }
public string EntryPoint;
}
}
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
public static void M() {}
}";
string source2 = @"
class D
{
unsafe void M2()
{
delegate* unmanaged<void> ptr1 = &C.M;
delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
}
}";
var sameComp = CreateCompilationWithFunctionPointers(source1 + source2);
sameComp.VerifyDiagnostics(
// (28,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(28, 50)
);
verifyUnmanagedData(sameComp);
var refComp = CreateCompilation(source1);
var differentComp = CreateCompilationWithFunctionPointers(source2, new[] { refComp.EmitToImageReference() });
differentComp.VerifyDiagnostics(
// (7,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(7, 50)
);
verifyUnmanagedData(differentComp);
static void verifyUnmanagedData(CSharpCompilation compilation)
{
var c = compilation.GetTypeByMetadataName("C");
var m = c.GetMethod("M");
Assert.Empty(m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true)!.CallingConventionTypes);
}
}
[Fact]
public void UnmanagedCallersOnly_UnrecognizedSignature()
{
string source1 = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute(Type[] CallConvs)
{
}
public string EntryPoint;
}
}
public class C
{
[UnmanagedCallersOnly(CallConvs: new[] { typeof(CallConvCdecl) })]
public static void M() {}
}";
string source2 = @"
class D
{
unsafe void M2()
{
delegate* unmanaged<void> ptr1 = &C.M;
delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
delegate*<void> ptr3 = &C.M;
}
}";
var sameComp = CreateCompilationWithFunctionPointers(source1 + source2);
sameComp.VerifyDiagnostics(
// (26,43): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// delegate* unmanaged<void> ptr1 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Unmanaged").WithLocation(26, 43),
// (27,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(27, 50)
);
verifyUnmanagedData(sameComp);
var refComp = CreateCompilation(source1);
var differentComp = CreateCompilationWithFunctionPointers(source2, new[] { refComp.EmitToImageReference() });
differentComp.VerifyDiagnostics(
// (6,43): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// delegate* unmanaged<void> ptr1 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Unmanaged").WithLocation(6, 43),
// (7,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(7, 50)
);
verifyUnmanagedData(differentComp);
static void verifyUnmanagedData(CSharpCompilation compilation)
{
var c = compilation.GetTypeByMetadataName("C");
var m = c.GetMethod("M");
Assert.Null(m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true));
}
}
[Fact]
public void UnmanagedCallersOnly_PropertyAndFieldNamedCallConvs()
{
var il = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute
extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
// Fields
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
// Methods
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
} // end of method UnmanagedCallersOnlyAttribute::.ctor
.method public hidebysig specialname instance class [mscorlib]System.Type[] get_CallConvs () cil managed
{
ldnull
ret
} // end of method UnmanagedCallersOnlyAttribute::get_CallConvs
.method public hidebysig specialname instance void set_CallConvs (
class [mscorlib]System.Type[] 'value'
) cil managed
{
ret
} // end of method UnmanagedCallersOnlyAttribute::set_CallConvs
// Properties
.property instance class [mscorlib]System.Type[] CallConvs()
{
.get instance class [mscorlib]System.Type[] System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::get_CallConvs()
.set instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::set_CallConvs(class [mscorlib]System.Type[])
}
}
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static void M () cil managed
{
// As separate field/property assignments. Property is first.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) }, CallConvs = new[] { typeof(CallConvCdecl) })]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 02 00 54 1d 50 09 43 61 6c 6c 43 6f 6e 76
73 01 00 00 00 7c 53 79 73 74 65 6d 2e 52 75 6e
74 69 6d 65 2e 43 6f 6d 70 69 6c 65 72 53 65 72
76 69 63 65 73 2e 43 61 6c 6c 43 6f 6e 76 53 74
64 63 61 6c 6c 2c 20 6d 73 63 6f 72 6c 69 62 2c
20 56 65 72 73 69 6f 6e 3d 34 2e 30 2e 30 2e 30
2c 20 43 75 6c 74 75 72 65 3d 6e 65 75 74 72 61
6c 2c 20 50 75 62 6c 69 63 4b 65 79 54 6f 6b 65
6e 3d 62 37 37 61 35 63 35 36 31 39 33 34 65 30
38 39 53 1d 50 09 43 61 6c 6c 43 6f 6e 76 73 01
00 00 00 7a 53 79 73 74 65 6d 2e 52 75 6e 74 69
6d 65 2e 43 6f 6d 70 69 6c 65 72 53 65 72 76 69
63 65 73 2e 43 61 6c 6c 43 6f 6e 76 43 64 65 63
6c 2c 20 6d 73 63 6f 72 6c 69 62 2c 20 56 65 72
73 69 6f 6e 3d 34 2e 30 2e 30 2e 30 2c 20 43 75
6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50
75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 62 37
37 61 35 63 35 36 31 39 33 34 65 30 38 39
)
ret
} // end of method C::M
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
unsafe class D
{
static void M1()
{
delegate* unmanaged[Cdecl]<void> ptr1 = &C.M;
delegate* unmanaged[Stdcall]<void> ptr2 = &C.M; // Error
M2();
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
static void M2() {}
}
", il);
comp.VerifyDiagnostics(
// (9,52): error CS8786: Calling convention of 'C.M()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr2 = &C.M; // Error
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Standard").WithLocation(9, 52),
// (13,27): error CS0229: Ambiguity between 'UnmanagedCallersOnlyAttribute.CallConvs' and 'UnmanagedCallersOnlyAttribute.CallConvs'
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
Diagnostic(ErrorCode.ERR_AmbigMember, "CallConvs").WithArguments("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute.CallConvs", "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute.CallConvs").WithLocation(13, 27)
);
var c = comp.GetTypeByMetadataName("C");
var m = c.GetMethod("M");
var callConvCdecl = comp.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvCdecl");
Assert.True(callConvCdecl!.Equals((NamedTypeSymbol)m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true)!.CallingConventionTypes.Single(), TypeCompareKind.ConsiderEverything));
}
[Fact]
public void UnmanagedCallersOnly_BadExpressionInArguments()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
class A
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
static unsafe void F()
{
delegate*<void> ptr1 = &F;
delegate* unmanaged<void> ptr2 = &F;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,54): error CS0246: The type or namespace name 'Bad' could not be found (are you missing a using directive or an assembly reference?)
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Bad", isSuppressed: false).WithArguments("Bad").WithLocation(5, 54),
// (5,57): error CS1026: ) expected
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_CloseParenExpected, ",", isSuppressed: false).WithLocation(5, 57),
// (5,59): error CS0103: The name 'Expression' does not exist in the current context
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_NameNotInContext, "Expression", isSuppressed: false).WithArguments("Expression").WithLocation(5, 59),
// (5,69): error CS1003: Syntax error, ',' expected
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_SyntaxError, ")", isSuppressed: false).WithArguments(",", ")").WithLocation(5, 69),
// (9,43): error CS8786: Calling convention of 'A.F()' is not compatible with 'Unmanaged'.
// delegate* unmanaged<void> ptr2 = &F;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "F", isSuppressed: false).WithArguments("A.F()", "Unmanaged").WithLocation(9, 43)
);
}
[Theory]
[InlineData("", 1)]
[InlineData("CallConvs = null", 1)]
[InlineData("CallConvs = new System.Type[0]", 1)]
[InlineData("CallConvs = new[] { typeof(CallConvCdecl) }", 2)]
[InlineData("CallConvs = new[] { typeof(CallConvCdecl), typeof(CallConvCdecl) }", 2)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall) }", 3)]
[InlineData("CallConvs = new[] { typeof(CallConvStdcall) }", 4)]
[InlineData("CallConvs = new[] { typeof(CallConvFastcall) }", 5)]
[InlineData("CallConvs = new[] { typeof(CallConvCdecl), typeof(CallConvThiscall) }", 6)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl) }", 6)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl), typeof(CallConvCdecl) }", 6)]
[InlineData("CallConvs = new[] { typeof(CallConvFastcall), typeof(CallConvCdecl) }", -1)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl), typeof(CallConvStdcall) }", -1)]
public void UnmanagedCallersOnlyAttribute_ConversionsToPointerType(string unmanagedCallersOnlyConventions, int diagnosticToSkip)
{
var comp = CreateCompilationWithFunctionPointers(new[] { $@"
#pragma warning disable CS8019 // Unused using
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{{
[UnmanagedCallersOnly({unmanagedCallersOnlyConventions})]
public static void M()
{{
delegate*<void> ptrManaged = &M;
delegate* unmanaged<void> ptrUnmanaged = &M;
delegate* unmanaged[Cdecl]<void> ptrCdecl = &M;
delegate* unmanaged[Thiscall]<void> ptrThiscall = &M;
delegate* unmanaged[Stdcall]<void> ptrStdcall = &M;
delegate* unmanaged[Fastcall]<void> ptrFastcall = &M;
delegate* unmanaged[Cdecl, Thiscall]<void> ptrCdeclThiscall = &M;
}}
}}
", UnmanagedCallersOnlyAttribute });
List<DiagnosticDescription> diagnostics = new()
{
// (10,39): error CS8786: Calling convention of 'C.M()' is not compatible with 'Default'.
// delegate*<void> ptrManaged = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Default").WithLocation(10, 39)
};
if (diagnosticToSkip != 1)
{
diagnostics.Add(
// (11,25): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// ptrUnmanaged = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Unmanaged").WithLocation(11, 51)
);
}
if (diagnosticToSkip != 2)
{
diagnostics.Add(
// (12,54): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptrCdecl = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "CDecl").WithLocation(12, 54)
);
}
if (diagnosticToSkip != 3)
{
diagnostics.Add(
// (13,60): error CS8786: Calling convention of 'C.M()' is not compatible with 'ThisCall'.
// delegate* unmanaged[Thiscall]<void> ptrThiscall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "ThisCall").WithLocation(13, 60)
);
}
if (diagnosticToSkip != 4)
{
diagnostics.Add(
// (14,58): error CS8786: Calling convention of 'C.M()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptrStdcall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Standard").WithLocation(14, 58)
);
}
if (diagnosticToSkip != 5)
{
diagnostics.Add(
// (15,60): error CS8786: Calling convention of 'C.M()' is not compatible with 'FastCall'.
// delegate* unmanaged[Fastcall]<void> ptrFastcall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "FastCall").WithLocation(15, 60)
);
}
if (diagnosticToSkip != 6)
{
diagnostics.Add(
// (16,72): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// delegate* unmanaged[Cdecl, Thiscall]<void> ptrCdeclThiscall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Unmanaged").WithLocation(16, 72)
);
}
comp.VerifyDiagnostics(diagnostics.ToArray());
}
[Fact]
public void UnmanagedCallersOnlyAttribute_AddressOfUsedInAttributeArgument()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
unsafe class Attr : Attribute
{
public Attr() {}
public delegate* unmanaged<void> PropUnmanaged { get; set; }
public delegate*<void> PropManaged { get; set; }
public delegate* unmanaged[Cdecl]<void> PropCdecl { get; set; }
}
unsafe class C
{
[UnmanagedCallersOnly]
static void M1()
{
}
[Attr(PropUnmanaged = &M1)]
[Attr(PropManaged = &M1)]
[Attr(PropCdecl = &M1)]
static unsafe void M2()
{
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (20,11): error CS0655: 'PropUnmanaged' is not a valid named attribute argument because it is not a valid attribute parameter type
// [Attr(PropUnmanaged = &M1)]
Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropUnmanaged", isSuppressed: false).WithArguments("PropUnmanaged").WithLocation(20, 11),
// (21,11): error CS0655: 'PropManaged' is not a valid named attribute argument because it is not a valid attribute parameter type
// [Attr(PropManaged = &M1)]
Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropManaged", isSuppressed: false).WithArguments("PropManaged").WithLocation(21, 11),
// (22,11): error CS0655: 'PropCdecl' is not a valid named attribute argument because it is not a valid attribute parameter type
// [Attr(PropCdecl = &M1)]
Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropCdecl", isSuppressed: false).WithArguments("PropCdecl").WithLocation(22, 11)
);
}
[ConditionalFact(typeof(CoreClrOnly))]
public void UnmanagedCallersOnly_Il()
{
var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
unsafe
{
delegate* unmanaged<void> ptr = &M;
ptr();
}
[UnmanagedCallersOnly]
static void M()
{
Console.WriteLine(1);
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp);
// TODO: Remove the manual unmanagedcallersonlyattribute definition and override and verify the
// output of running this code when we move to p8
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void Program.<<Main>$>g__M|0_0()""
IL_0006: calli ""delegate* unmanaged<void>""
IL_000b: ret
}
");
}
[Fact]
public void UnmanagedCallersOnly_AddressOfAsInvocationArgument()
{
var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
public static void M1(int i) { }
public static void M2(delegate* unmanaged[Cdecl]<int, void> param)
{
M2(&M1);
}
}
", UnmanagedCallersOnlyAttribute });
verifier.VerifyIL(@"C.M2", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void C.M1(int)""
IL_0006: call ""void C.M2(delegate* unmanaged[Cdecl]<int, void>)""
IL_000b: ret
}
");
}
[Fact]
public void UnmanagedCallersOnly_LambdaInference()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly]
public static void M1(int i) { }
public static void M2()
{
Func<delegate*<int, void>> a1 = () => &M1;
Func<delegate* unmanaged<int, void>> a2 = () => &M1;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (11,14): error CS0306: The type 'delegate*<int, void>' may not be used as a type argument
// Func<delegate*<int, void>> a1 = () => &M1;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, void>", isSuppressed: false).WithArguments("delegate*<int, void>").WithLocation(11, 14),
// (11,47): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<delegate*<int, void>> a1 = () => &M1;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "&M1", isSuppressed: false).WithArguments("lambda expression").WithLocation(11, 47),
// (11,48): error CS8786: Calling convention of 'C.M1(int)' is not compatible with 'Default'.
// Func<delegate*<int, void>> a1 = () => &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("C.M1(int)", "Default").WithLocation(11, 48),
// (12,14): error CS0306: The type 'delegate* unmanaged<int, void>' may not be used as a type argument
// Func<delegate* unmanaged<int, void>> a2 = () => &M1;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate* unmanaged<int, void>", isSuppressed: false).WithArguments("delegate* unmanaged<int, void>").WithLocation(12, 14)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambdas = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToArray();
Assert.Equal(2, lambdas.Length);
var typeInfo = model.GetTypeInfo(lambdas[0]);
var conversion = model.GetConversion(lambdas[0]);
AssertEx.Equal("System.Func<delegate*<System.Int32, System.Void>>",
typeInfo.Type.ToTestDisplayString(includeNonNullable: false));
AssertEx.Equal("System.Func<delegate*<System.Int32, System.Void>>",
typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false));
Assert.Equal(Conversion.NoConversion, conversion);
typeInfo = model.GetTypeInfo(lambdas[1]);
conversion = model.GetConversion(lambdas[1]);
Assert.Null(typeInfo.Type);
AssertEx.Equal("System.Func<delegate* unmanaged<System.Int32, System.Void>>",
typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false));
Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind);
}
[Fact, WorkItem(47487, "https://github.com/dotnet/roslyn/issues/47487")]
public void InAndRefParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
delegate*<in int, ref char, void> F = &Test;
char c = 'a';
F(int.MaxValue, ref c);
}
static void Test(in int b, ref char c)
{
Console.WriteLine($""b = {b}, c = {c}"");
}
", expectedOutput: "b = 2147483647, c = a");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 27 (0x1b)
.maxstack 3
.locals init (char V_0, //c
delegate*<in int, ref char, void> V_1,
int V_2)
IL_0000: ldftn ""void Program.<<Main>$>g__Test|0_0(in int, ref char)""
IL_0006: ldc.i4.s 97
IL_0008: stloc.0
IL_0009: stloc.1
IL_000a: ldc.i4 0x7fffffff
IL_000f: stloc.2
IL_0010: ldloca.s V_2
IL_0012: ldloca.s V_0
IL_0014: ldloc.1
IL_0015: calli ""delegate*<in int, ref char, void>""
IL_001a: ret
}
");
}
[Fact, WorkItem(47487, "https://github.com/dotnet/roslyn/issues/47487")]
public void OutDiscard()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
delegate*<out int, out int, void> F = &Test;
F(out var i1, out _);
F(out _, out var i2);
Console.Write(i1);
Console.Write(i2);
}
static void Test(out int i1, out int i2)
{
i1 = 1;
i2 = 2;
}
", expectedOutput: "12");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
int V_2,
delegate*<out int, out int, void> V_3)
IL_0000: ldftn ""void Program.<<Main>$>g__Test|0_0(out int, out int)""
IL_0006: dup
IL_0007: stloc.3
IL_0008: ldloca.s V_0
IL_000a: ldloca.s V_2
IL_000c: ldloc.3
IL_000d: calli ""delegate*<out int, out int, void>""
IL_0012: stloc.3
IL_0013: ldloca.s V_2
IL_0015: ldloca.s V_1
IL_0017: ldloc.3
IL_0018: calli ""delegate*<out int, out int, void>""
IL_001d: ldloc.0
IL_001e: call ""void System.Console.Write(int)""
IL_0023: ldloc.1
IL_0024: call ""void System.Console.Write(int)""
IL_0029: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
iRef = 2;
System.Console.WriteLine(i);
static ref int ReturnPtrByRef(delegate*<ref int, ref int> ptr, ref int i)
=> ref ptr(ref i);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref int, ref int>, ref int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref int, ref int>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_FunctionPointerDoesNotReturnByRefError()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe
{
int i = 1;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
static ref int ReturnPtrByRef(delegate*<ref int, int> ptr, ref int i)
=> ref ptr(ref i);
static int ReturnByRef(ref int i) => i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (8,16): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// => ref ptr(ref i);
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "ptr(ref i)").WithLocation(8, 16)
);
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_NotSafeToEscape()
{
var comp = CreateCompilationWithSpan(@"
using System;
unsafe
{
ref Span<int> spanRef = ref ReturnPtrByRef(&ReturnByRef);
static ref Span<int> ReturnPtrByRef(delegate*<ref Span<int>, ref Span<int>> ptr)
{
Span<int> span = stackalloc int[1];
return ref ptr(ref span);
}
static ref Span<int> ReturnByRef(ref Span<int> i) => ref i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (10,20): error CS8347: Cannot use a result of 'delegate*<ref Span<int>, ref Span<int>>' in this context because it may expose variables referenced by parameter '0' outside of their declaration scope
// return ref ptr(ref span);
Diagnostic(ErrorCode.ERR_EscapeCall, "ptr(ref span)").WithArguments("delegate*<ref System.Span<int>, ref System.Span<int>>", "0").WithLocation(10, 20),
// (10,28): error CS8168: Cannot return local 'span' by reference because it is not a ref local
// return ref ptr(ref span);
Diagnostic(ErrorCode.ERR_RefReturnLocal, "span").WithArguments("span").WithLocation(10, 28)
);
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_SafeToEscape()
{
var comp = CreateCompilationWithSpan(@"
using System;
unsafe
{
Span<int> s = stackalloc int[1];
s[0] = 1;
ref Span<int> sRef = ref ReturnPtrByRef(&ReturnByRef, ref s);
sRef[0] = 2;
Console.WriteLine(s[0]);
static ref Span<int> ReturnPtrByRef(delegate*<ref Span<int>, ref Span<int>> ptr, ref Span<int> s)
=> ref ptr(ref s);
static ref Span<int> ReturnByRef(ref Span<int> i) => ref i;
}", options: TestOptions.UnsafeReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref System.Span<int>, ref System.Span<int>>, ref System.Span<int>)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref System.Span<int>, ref System.Span<int>> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref System.Span<int>, ref System.Span<int>>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_RefReadonlyToRefError()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe
{
int i = 1;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
static ref int ReturnPtrByRef(delegate*<ref int, ref readonly int> ptr, ref int i)
=> ref ptr(ref i);
static ref readonly int ReturnByRef(ref int i) => ref i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (8,16): error CS8333: Cannot return method 'delegate*<ref int, ref readonly int>' by writable reference because it is a readonly variable
// => ref ptr(ref i);
Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "ptr(ref i)").WithArguments("method", "delegate*<ref int, ref readonly int>").WithLocation(8, 16)
);
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_RefToRefReadonly()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
ref readonly int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
i = 2;
System.Console.WriteLine(iRef);
static ref readonly int ReturnPtrByRef(delegate*<ref int, ref int> ptr, ref int i)
=> ref ptr(ref i);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref int, ref int>, ref int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref int, ref int>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void RefAssignment()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
delegate*<ref int, ref int> ptr = &ReturnByRef;
ref readonly int iRef = ref ptr(ref i);
i = 2;
System.Console.WriteLine(iRef);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldftn ""ref int Program.<<Main>$>g__ReturnByRef|0_0(ref int)""
IL_0008: stloc.1
IL_0009: ldloca.s V_0
IL_000b: ldloc.1
IL_000c: calli ""delegate*<ref int, ref int>""
IL_0011: ldc.i4.2
IL_0012: stloc.0
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void RefAssignmentThroughTernary()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
int i2 = 3;
delegate*<ref int, ref int> ptr = &ReturnByRef;
ref readonly int iRef = ref false ? ref i2 : ref ptr(ref i);
i = 2;
System.Console.WriteLine(iRef);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldftn ""ref int Program.<<Main>$>g__ReturnByRef|0_0(ref int)""
IL_0008: stloc.1
IL_0009: ldloca.s V_0
IL_000b: ldloc.1
IL_000c: calli ""delegate*<ref int, ref int>""
IL_0011: ldc.i4.2
IL_0012: stloc.0
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void RefReturnThroughTernary()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
int i2 = 3;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i, ref i2);
iRef = 2;
System.Console.WriteLine(i);
static ref int ReturnPtrByRef(delegate*<ref int, ref int> ptr, ref int i, ref int i2)
=> ref false ? ref i2 : ref ptr(ref i);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref int, ref int>, ref int, ref int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref int, ref int>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void PassedAsByRefParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
delegate*<ref int, ref int> ptr = &ReturnByRef;
ref readonly int iRef = ref ptr(ref ptr(ref i));
i = 2;
System.Console.WriteLine(iRef);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1,
delegate*<ref int, ref int> V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldftn ""ref int Program.<<Main>$>g__ReturnByRef|0_0(ref int)""
IL_0008: dup
IL_0009: stloc.1
IL_000a: stloc.2
IL_000b: ldloca.s V_0
IL_000d: ldloc.2
IL_000e: calli ""delegate*<ref int, ref int>""
IL_0013: ldloc.1
IL_0014: calli ""delegate*<ref int, ref int>""
IL_0019: ldc.i4.2
IL_001a: stloc.0
IL_001b: ldind.i4
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: ret
}
");
}
[Fact, WorkItem(49760, "https://github.com/dotnet/roslyn/issues/49760")]
public void ReturnRefStructByValue_CanEscape()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
Console.WriteLine(ptrTest().field);
static BorrowedReference ptrTest()
{
delegate*<BorrowedReference> ptr = &test;
return ptr();
}
static BorrowedReference test() => new BorrowedReference() { field = 1 };
}
ref struct BorrowedReference {
public int field;
}
", expectedOutput: "1");
verifier.VerifyIL("Program.<<Main>$>g__ptrTest|0_0()", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""BorrowedReference Program.<<Main>$>g__test|0_1()""
IL_0006: calli ""delegate*<BorrowedReference>""
IL_000b: ret
}
");
}
[Fact, WorkItem(49760, "https://github.com/dotnet/roslyn/issues/49760")]
public void ReturnRefStructByValue_CannotEscape()
{
var comp = CreateCompilationWithSpan(@"
#pragma warning disable CS8321 // Unused local function ptrTest
using System;
unsafe
{
static Span<int> ptrTest()
{
Span<int> s = stackalloc int[1];
delegate*<Span<int>, Span<int>> ptr = &test;
return ptr(s);
}
static Span<int> ptrTest2(Span<int> s)
{
delegate*<Span<int>, Span<int>> ptr = &test;
return ptr(s);
}
static Span<int> test(Span<int> s) => s;
}
", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (10,16): error CS8347: Cannot use a result of 'delegate*<Span<int>, Span<int>>' in this context because it may expose variables referenced by parameter '0' outside of their declaration scope
// return ptr(s);
Diagnostic(ErrorCode.ERR_EscapeCall, "ptr(s)").WithArguments("delegate*<System.Span<int>, System.Span<int>>", "0").WithLocation(10, 16),
// (10,20): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// return ptr(s);
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(10, 20)
);
}
[Fact]
public void RefEscapeNestedArrayAccess()
{
var verifier = CompileAndVerifyFunctionPointers(@"
System.Console.WriteLine(M());
static ref int M()
{
var arr = new int[1]{40};
unsafe ref int N()
{
static ref int NN(ref int arg) => ref arg;
delegate*<ref int, ref int> ptr = &NN;
ref var r = ref ptr(ref arr[0]);
r += 2;
return ref r;
}
return ref N();
}
", expectedOutput: "42");
verifier.VerifyIL("Program.<<Main>$>g__N|0_1(ref Program.<>c__DisplayClass0_0)", @"
{
// Code size 32 (0x20)
.maxstack 4
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldftn ""ref int Program.<<Main>$>g__NN|0_2(ref int)""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldfld ""int[] Program.<>c__DisplayClass0_0.arr""
IL_000d: ldc.i4.0
IL_000e: ldelema ""int""
IL_0013: ldloc.0
IL_0014: calli ""delegate*<ref int, ref int>""
IL_0019: dup
IL_001a: dup
IL_001b: ldind.i4
IL_001c: ldc.i4.2
IL_001d: add
IL_001e: stind.i4
IL_001f: ret
}
");
}
[Fact]
public void RefReturnInCompoundAssignment()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
delegate*<ref int, ref int> ptr = &RefReturn;
int i = 0;
ptr(ref i) += 1;
System.Console.WriteLine(i);
static ref int RefReturn(ref int i) => ref i;
}", expectedOutput: "1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1)
IL_0000: ldftn ""ref int Program.<<Main>$>g__RefReturn|0_0(ref int)""
IL_0006: ldc.i4.0
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloca.s V_0
IL_000b: ldloc.1
IL_000c: calli ""delegate*<ref int, ref int>""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: stind.i4
IL_0016: ldloc.0
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: ret
}
");
}
[Fact]
public void InvalidReturnInCompoundAssignment()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe
{
delegate*<int, int> ptr = &RefReturn;
int i = 0;
ptr(i) += 1;
static int RefReturn(int i) => i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (6,5): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// ptr(i) += 1;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "ptr(i)").WithLocation(6, 5)
);
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithNestedUnconstrainedTypeParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
test<int>(null);
test<int>(&intTest);
static void test<T>(delegate*<T, void> f)
{
Console.WriteLine(f == null);
Console.WriteLine(f is null);
}
static void intTest(int i) {}
}
", expectedOutput: @"
True
True
False
False");
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(delegate*<T, void>)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Fact, WorkItem(48765, "https://github.com/dotnet/roslyn/issues/48765")]
public void TypeOfFunctionPointerInAttribute()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
[Attr(typeof(delegate*<void>))]
[Attr(typeof(delegate*<void>[]))]
[Attr(typeof(C<delegate*<void>[]>))]
unsafe class Attr : System.Attribute
{
public Attr(System.Type type) {}
}
class C<T> {}
");
// https://github.com/dotnet/roslyn/issues/48765 tracks enabling support for this scenario. Currently, we don't know how to
// encode these in metadata, and may need to work with the runtime team to define a new format.
comp.VerifyDiagnostics(
// (4,7): error CS8911: Using a function pointer type in a 'typeof' in an attribute is not supported.
// [Attr(typeof(delegate*<void>))]
Diagnostic(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, "typeof(delegate*<void>)").WithLocation(4, 7),
// (5,7): error CS8911: Using a function pointer type in a 'typeof' in an attribute is not supported.
// [Attr(typeof(delegate*<void>[]))]
Diagnostic(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, "typeof(delegate*<void>[])").WithLocation(5, 7),
// (6,7): error CS8911: Using a function pointer type in a 'typeof' in an attribute is not supported.
// [Attr(typeof(C<delegate*<void>[]>))]
Diagnostic(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, "typeof(C<delegate*<void>[]>)").WithLocation(6, 7)
);
}
private static readonly Guid s_guid = new Guid("97F4DBD4-F6D1-4FAD-91B3-1001F92068E5");
private static readonly BlobContentId s_contentId = new BlobContentId(s_guid, 0x04030201);
private static void DefineInvalidSignatureAttributeIL(MetadataBuilder metadata, BlobBuilder ilBuilder, SignatureHeader headerToUseForM)
{
metadata.AddModule(
0,
metadata.GetOrAddString("ConsoleApplication.exe"),
metadata.GetOrAddGuid(s_guid),
default(GuidHandle),
default(GuidHandle));
metadata.AddAssembly(
metadata.GetOrAddString("ConsoleApplication"),
version: new Version(1, 0, 0, 0),
culture: default(StringHandle),
publicKey: metadata.GetOrAddBlob(new byte[0]),
flags: default(AssemblyFlags),
hashAlgorithm: AssemblyHashAlgorithm.Sha1);
var mscorlibAssemblyRef = metadata.AddAssemblyReference(
name: metadata.GetOrAddString("mscorlib"),
version: new Version(4, 0, 0, 0),
culture: default(StringHandle),
publicKeyOrToken: metadata.GetOrAddBlob(ImmutableArray.Create<byte>(0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89)),
flags: default(AssemblyFlags),
hashValue: default(BlobHandle));
var systemObjectTypeRef = metadata.AddTypeReference(
mscorlibAssemblyRef,
metadata.GetOrAddString("System"),
metadata.GetOrAddString("Object"));
var systemConsoleTypeRefHandle = metadata.AddTypeReference(
mscorlibAssemblyRef,
metadata.GetOrAddString("System"),
metadata.GetOrAddString("Console"));
var consoleWriteLineSignature = new BlobBuilder();
new BlobEncoder(consoleWriteLineSignature).
MethodSignature().
Parameters(1,
returnType => returnType.Void(),
parameters => parameters.AddParameter().Type().String());
var consoleWriteLineMemberRef = metadata.AddMemberReference(
systemConsoleTypeRefHandle,
metadata.GetOrAddString("WriteLine"),
metadata.GetOrAddBlob(consoleWriteLineSignature));
var parameterlessCtorSignature = new BlobBuilder();
new BlobEncoder(parameterlessCtorSignature).
MethodSignature(isInstanceMethod: true).
Parameters(0, returnType => returnType.Void(), parameters => { });
var parameterlessCtorBlobIndex = metadata.GetOrAddBlob(parameterlessCtorSignature);
var objectCtorMemberRef = metadata.AddMemberReference(
systemObjectTypeRef,
metadata.GetOrAddString(".ctor"),
parameterlessCtorBlobIndex);
// Signature for M() with an _invalid_ SignatureAttribute
var mSignature = new BlobBuilder();
var mBlobBuilder = new BlobEncoder(mSignature);
mBlobBuilder.Builder.WriteByte(headerToUseForM.RawValue);
var mParameterEncoder = new MethodSignatureEncoder(mBlobBuilder.Builder, hasVarArgs: false);
mParameterEncoder.Parameters(parameterCount: 0, returnType => returnType.Void(), parameters => { });
var methodBodyStream = new MethodBodyStreamEncoder(ilBuilder);
var codeBuilder = new BlobBuilder();
InstructionEncoder il;
//
// Program::.ctor
//
il = new InstructionEncoder(codeBuilder);
// ldarg.0
il.LoadArgument(0);
// call instance void [mscorlib]System.Object::.ctor()
il.Call(objectCtorMemberRef);
// ret
il.OpCode(ILOpCode.Ret);
int ctorBodyOffset = methodBodyStream.AddMethodBody(il);
codeBuilder.Clear();
//
// Program::M
//
il = new InstructionEncoder(codeBuilder);
// ldstr "M"
il.LoadString(metadata.GetOrAddUserString("M"));
// call void [mscorlib]System.Console::WriteLine(string)
il.Call(consoleWriteLineMemberRef);
// ret
il.OpCode(ILOpCode.Ret);
int mBodyOffset = methodBodyStream.AddMethodBody(il);
codeBuilder.Clear();
var mMethodDef = metadata.AddMethodDefinition(
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig,
MethodImplAttributes.IL | MethodImplAttributes.Managed,
metadata.GetOrAddString("M"),
metadata.GetOrAddBlob(mSignature),
mBodyOffset,
parameterList: default(ParameterHandle));
var ctorDef = metadata.AddMethodDefinition(
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
MethodImplAttributes.IL | MethodImplAttributes.Managed,
metadata.GetOrAddString(".ctor"),
parameterlessCtorBlobIndex,
ctorBodyOffset,
parameterList: default(ParameterHandle));
metadata.AddTypeDefinition(
default(TypeAttributes),
default(StringHandle),
metadata.GetOrAddString("<Module>"),
baseType: default(EntityHandle),
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: mMethodDef);
metadata.AddTypeDefinition(
TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit,
metadata.GetOrAddString("ConsoleApplication"),
metadata.GetOrAddString("Program"),
systemObjectTypeRef,
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: mMethodDef);
}
private static void WritePEImage(
Stream peStream,
MetadataBuilder metadataBuilder,
BlobBuilder ilBuilder)
{
var peHeaderBuilder = new PEHeaderBuilder(imageCharacteristics: Characteristics.Dll);
var peBuilder = new ManagedPEBuilder(
peHeaderBuilder,
new MetadataRootBuilder(metadataBuilder),
ilBuilder,
flags: CorFlags.ILOnly,
deterministicIdProvider: content => s_contentId);
var peBlob = new BlobBuilder();
var contentId = peBuilder.Serialize(peBlob);
peBlob.WriteContentTo(peStream);
}
private static ModuleSymbol GetSourceModule(CompilationVerifier verifier)
{
return ((CSharpCompilation)verifier.Compilation).SourceModule;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.CSharp.UnitTests.FunctionPointerUtilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenFunctionPointersTests : CSharpTestBase
{
private CompilationVerifier CompileAndVerifyFunctionPointers(
CSharpTestSource sources,
MetadataReference[]? references = null,
Action<ModuleSymbol>? symbolValidator = null,
string? expectedOutput = null,
TargetFramework targetFramework = TargetFramework.Standard,
CSharpCompilationOptions? options = null)
{
var comp = CreateCompilation(
sources,
references,
parseOptions: TestOptions.Regular9,
options: options ?? (expectedOutput is null ? TestOptions.UnsafeReleaseDll : TestOptions.UnsafeReleaseExe),
targetFramework: targetFramework);
return CompileAndVerify(comp, symbolValidator: symbolValidator, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
private static CSharpCompilation CreateCompilationWithFunctionPointers(CSharpTestSource source, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null, TargetFramework? targetFramework = null)
{
return CreateCompilation(source, references: references, options: options ?? TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, targetFramework: targetFramework ?? TargetFramework.NetCoreApp);
}
private CompilationVerifier CompileAndVerifyFunctionPointersWithIl(string source, string ilStub, Action<ModuleSymbol>? symbolValidator = null, string? expectedOutput = null)
{
var comp = CreateCompilationWithIL(source, ilStub, parseOptions: TestOptions.Regular9, options: expectedOutput is null ? TestOptions.UnsafeReleaseDll : TestOptions.UnsafeReleaseExe);
return CompileAndVerify(comp, expectedOutput: expectedOutput, symbolValidator: symbolValidator, verify: Verification.Skipped);
}
private static CSharpCompilation CreateCompilationWithFunctionPointersAndIl(string source, string ilStub, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null)
{
return CreateCompilationWithIL(source, ilStub, references: references, options: options ?? TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
}
[Theory]
[InlineData("", CallingConvention.Default)]
[InlineData("managed", CallingConvention.Default)]
[InlineData("unmanaged[Cdecl]", CallingConvention.CDecl)]
[InlineData("unmanaged[Thiscall]", CallingConvention.ThisCall)]
[InlineData("unmanaged[Stdcall]", CallingConvention.Standard)]
[InlineData("unmanaged[Fastcall]", CallingConvention.FastCall)]
[InlineData("unmanaged[@Cdecl]", CallingConvention.CDecl)]
[InlineData("unmanaged[@Thiscall]", CallingConvention.ThisCall)]
[InlineData("unmanaged[@Stdcall]", CallingConvention.Standard)]
[InlineData("unmanaged[@Fastcall]", CallingConvention.FastCall)]
[InlineData("unmanaged", CallingConvention.Unmanaged)]
internal void CallingConventions(string conventionString, CallingConvention expectedConvention)
{
var verifier = CompileAndVerifyFunctionPointers($@"
class C
{{
public unsafe delegate* {conventionString}<string, int> M() => throw null;
}}", symbolValidator: symbolValidator, targetFramework: TargetFramework.NetCoreApp);
symbolValidator(GetSourceModule(verifier));
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ReturnType;
VerifyFunctionPointerSymbol(funcPtr, expectedConvention,
(RefKind.None, IsSpecialType(SpecialType.System_Int32)),
(RefKind.None, IsSpecialType(SpecialType.System_String)));
}
}
[Fact]
public void MultipleCallingConventions()
{
var comp = CompileAndVerifyFunctionPointers(@"
#pragma warning disable CS0168
unsafe class C
{
public delegate* unmanaged[Thiscall, Stdcall]<void> M() => throw null;
}", symbolValidator: symbolValidator, targetFramework: TargetFramework.NetCoreApp);
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ReturnType;
AssertEx.Equal("delegate* unmanaged[Thiscall, Stdcall]<System.Void modopt(System.Runtime.CompilerServices.CallConvThiscall) modopt(System.Runtime.CompilerServices.CallConvStdcall)>", funcPtr.ToTestDisplayString());
Assert.Equal(CallingConvention.Unmanaged, ((FunctionPointerTypeSymbol)funcPtr).Signature.CallingConvention);
}
}
[Fact]
public void RefParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
class C
{
public unsafe void M(delegate*<ref C, ref string, ref int[]> param1) => throw null;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ParameterTypesWithAnnotations[0].Type;
VerifyFunctionPointerSymbol(funcPtr, CallingConvention.Default,
(RefKind.Ref, IsArrayType(IsSpecialType(SpecialType.System_Int32))),
(RefKind.Ref, IsTypeName("C")),
(RefKind.Ref, IsSpecialType(SpecialType.System_String)));
}
}
[Fact]
public void OutParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
class C
{
public unsafe void M(delegate*<out C, out string, ref int[]> param1) => throw null;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var funcPtr = m.ParameterTypesWithAnnotations[0].Type;
VerifyFunctionPointerSymbol(funcPtr, CallingConvention.Default,
(RefKind.Ref, IsArrayType(IsSpecialType(SpecialType.System_Int32))),
(RefKind.Out, IsTypeName("C")),
(RefKind.Out, IsSpecialType(SpecialType.System_String)));
}
}
[Fact]
public void NestedFunctionPointers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public class C
{
public unsafe delegate* unmanaged[Cdecl]<delegate* unmanaged[Stdcall]<int, void>, void> M(delegate*<C, delegate*<S>> param1) => throw null;
}
public struct S
{
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var returnType = m.ReturnType;
VerifyFunctionPointerSymbol(returnType, CallingConvention.CDecl,
(RefKind.None, IsVoidType()),
(RefKind.None, IsFunctionPointerTypeSymbol(CallingConvention.Standard,
(RefKind.None, IsVoidType()),
(RefKind.None, IsSpecialType(SpecialType.System_Int32)))
));
var paramType = m.Parameters[0].Type;
VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
(RefKind.None, IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsTypeName("S")))),
(RefKind.None, IsTypeName("C")));
}
}
[Fact]
public void InModifier()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public class C
{
public unsafe void M(delegate*<in string, in int, ref readonly bool> param) {}
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var paramType = m.Parameters[0].Type;
VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Boolean)),
(RefKind.In, IsSpecialType(SpecialType.System_String)),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
}
}
[Fact]
public void BadReturnModReqs()
{
var il = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field public method int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& *() 'Field1'
.field public method int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field2'
.field public method int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field3'
.field public method int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field4'
.field public method int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field5'
.field public method int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)& *() 'Field6'
.field public method int32 modreq([mscorlib]System.Object)& *() 'Field7'
.field public method int32& modreq([mscorlib]System.Object) *() 'Field8'
.field static public method method int32 modreq([mscorlib]System.Object) *() *() 'Field9'
}
";
var source = @"
class D
{
void M(C c)
{
ref int i1 = ref c.Field1();
ref int i2 = ref c.Field2();
c.Field1 = c.Field1;
c.Field2 = c.Field2;
}
}";
var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
comp.VerifyDiagnostics(
// (6,26): error CS0570: 'delegate*<ref int>' is not supported by the language
// ref int i1 = ref c.Field1();
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1()").WithArguments("delegate*<ref int>").WithLocation(6, 26),
// (6,28): error CS0570: 'C.Field1' is not supported by the language
// ref int i1 = ref c.Field1();
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(6, 28),
// (7,26): error CS0570: 'delegate*<ref int>' is not supported by the language
// ref int i2 = ref c.Field2();
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field2()").WithArguments("delegate*<ref int>").WithLocation(7, 26),
// (7,28): error CS0570: 'C.Field2' is not supported by the language
// ref int i2 = ref c.Field2();
Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(7, 28),
// (8,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 11),
// (8,22): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 22),
// (9,11): error CS0570: 'C.Field2' is not supported by the language
// c.Field2 = c.Field2;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(9, 11),
// (9,22): error CS0570: 'C.Field2' is not supported by the language
// c.Field2 = c.Field2;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field2").WithArguments("C.Field2").WithLocation(9, 22)
);
var c = comp.GetTypeByMetadataName("C");
for (int i = 1; i <= 9; i++)
{
var field = c.GetField($"Field{i}");
Assert.True(field.HasUseSiteError);
Assert.True(field.HasUnsupportedMetadata);
Assert.Equal(TypeKind.FunctionPointer, field.Type.TypeKind);
var signature = ((FunctionPointerTypeSymbol)field.Type).Signature;
Assert.True(signature.HasUseSiteError);
Assert.True(signature.HasUnsupportedMetadata);
Assert.True(field.Type.HasUseSiteError);
Assert.True(field.Type.HasUnsupportedMetadata);
}
}
[Fact]
public void BadParamModReqs()
{
var il = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field1'
.field public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field2'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field3'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field4'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.InAttribute)&) 'Field5'
.field public method void *(int32 modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)&) 'Field6'
.field public method void *(int32& modreq([mscorlib]System.Object)) 'Field7'
.field public method void *(int32 modreq([mscorlib]System.Object)&) 'Field8'
.field public method void *(method void *(int32 modreq([mscorlib]System.Object))) 'Field9'
}
";
var source = @"
class D
{
void M(C c)
{
int i = 1;
c.Field1(ref i);
c.Field1(in i);
c.Field1(out i);
c.Field1 = c.Field1;
}
}";
var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
comp.VerifyDiagnostics(
// (7,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
// c.Field1(ref i);
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(ref i)").WithArguments("delegate*<in int, void>").WithLocation(7, 9),
// (7,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1(ref i);
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(7, 11),
// (8,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
// c.Field1(in i);
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(in i)").WithArguments("delegate*<in int, void>").WithLocation(8, 9),
// (8,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1(in i);
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(8, 11),
// (9,9): error CS0570: 'delegate*<in int, void>' is not supported by the language
// c.Field1(out i);
Diagnostic(ErrorCode.ERR_BindToBogus, "c.Field1(out i)").WithArguments("delegate*<in int, void>").WithLocation(9, 9),
// (9,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1(out i);
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(9, 11),
// (10,11): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(10, 11),
// (10,22): error CS0570: 'C.Field1' is not supported by the language
// c.Field1 = c.Field1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Field1").WithArguments("C.Field1").WithLocation(10, 22)
);
var c = comp.GetTypeByMetadataName("C");
for (int i = 1; i <= 9; i++)
{
var field = c.GetField($"Field{i}");
Assert.True(field.HasUseSiteError);
Assert.True(field.HasUnsupportedMetadata);
Assert.Equal(TypeKind.FunctionPointer, field.Type.TypeKind);
var signature = ((FunctionPointerTypeSymbol)field.Type).Signature;
Assert.True(signature.HasUseSiteError);
Assert.True(signature.HasUnsupportedMetadata);
Assert.True(field.Type.HasUseSiteError);
Assert.True(field.Type.HasUnsupportedMetadata);
}
}
[Fact]
public void ValidModReqsAndOpts()
{
var il = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field static public method int32& modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *() 'Field1'
.field static public method int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) *() 'Field2'
.field static public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.OutAttribute) modopt([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field3'
.field static public method void *(int32& modopt([mscorlib]System.Runtime.InteropServices.OutAttribute) modreq([mscorlib]System.Runtime.InteropServices.InAttribute)) 'Field4'
.field static public method void *(int32& modopt([mscorlib]System.Runtime.InteropServices.InAttribute) modreq([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field5'
.field static public method void *(int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.OutAttribute)) 'Field6'
}
";
var source = @"
using System;
unsafe class D
{
static int i = 1;
static ref readonly int M()
{
return ref i;
}
static void MIn(in int param)
{
Console.Write(param);
}
static void MOut(out int param)
{
param = i;
}
static void Main()
{
TestRefReadonly();
TestOut();
TestIn();
}
static void TestRefReadonly()
{
C.Field1 = &M;
ref readonly int local1 = ref C.Field1();
Console.Write(local1);
i = 2;
Console.Write(local1);
C.Field2 = &M;
i = 3;
ref readonly int local2 = ref C.Field2();
Console.Write(local2);
i = 4;
Console.Write(local2);
}
static void TestOut()
{
C.Field3 = &MOut;
i = 5;
C.Field3(out int local);
Console.Write(local);
C.Field5 = &MOut;
i = 6;
C.Field5(out local);
Console.Write(local);
}
static void TestIn()
{
i = 7;
C.Field4 = &MIn;
C.Field4(in i);
i = 8;
C.Field6 = &MIn;
C.Field6(in i);
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "12345678");
verifier.VerifyIL("D.TestRefReadonly", @"
{
// Code size 87 (0x57)
.maxstack 2
IL_0000: ldftn ""ref readonly int D.M()""
IL_0006: stsfld ""delegate*<ref readonly int> C.Field1""
IL_000b: ldsfld ""delegate*<ref readonly int> C.Field1""
IL_0010: calli ""delegate*<ref readonly int>""
IL_0015: dup
IL_0016: ldind.i4
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ldc.i4.2
IL_001d: stsfld ""int D.i""
IL_0022: ldind.i4
IL_0023: call ""void System.Console.Write(int)""
IL_0028: ldftn ""ref readonly int D.M()""
IL_002e: stsfld ""delegate*<ref readonly int> C.Field2""
IL_0033: ldc.i4.3
IL_0034: stsfld ""int D.i""
IL_0039: ldsfld ""delegate*<ref readonly int> C.Field2""
IL_003e: calli ""delegate*<ref readonly int>""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: call ""void System.Console.Write(int)""
IL_004a: ldc.i4.4
IL_004b: stsfld ""int D.i""
IL_0050: ldind.i4
IL_0051: call ""void System.Console.Write(int)""
IL_0056: ret
}
");
verifier.VerifyIL("D.TestOut", @"
{
// Code size 75 (0x4b)
.maxstack 2
.locals init (int V_0, //local
delegate*<out int, void> V_1,
delegate*<out int, void> V_2)
IL_0000: ldftn ""void D.MOut(out int)""
IL_0006: stsfld ""delegate*<out int, void> C.Field3""
IL_000b: ldc.i4.5
IL_000c: stsfld ""int D.i""
IL_0011: ldsfld ""delegate*<out int, void> C.Field3""
IL_0016: stloc.1
IL_0017: ldloca.s V_0
IL_0019: ldloc.1
IL_001a: calli ""delegate*<out int, void>""
IL_001f: ldloc.0
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ldftn ""void D.MOut(out int)""
IL_002b: stsfld ""delegate*<out int, void> C.Field5""
IL_0030: ldc.i4.6
IL_0031: stsfld ""int D.i""
IL_0036: ldsfld ""delegate*<out int, void> C.Field5""
IL_003b: stloc.2
IL_003c: ldloca.s V_0
IL_003e: ldloc.2
IL_003f: calli ""delegate*<out int, void>""
IL_0044: ldloc.0
IL_0045: call ""void System.Console.Write(int)""
IL_004a: ret
}
");
verifier.VerifyIL("D.TestIn", @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (delegate*<in int, void> V_0,
delegate*<in int, void> V_1)
IL_0000: ldc.i4.7
IL_0001: stsfld ""int D.i""
IL_0006: ldftn ""void D.MIn(in int)""
IL_000c: stsfld ""delegate*<in int, void> C.Field4""
IL_0011: ldsfld ""delegate*<in int, void> C.Field4""
IL_0016: stloc.0
IL_0017: ldsflda ""int D.i""
IL_001c: ldloc.0
IL_001d: calli ""delegate*<in int, void>""
IL_0022: ldc.i4.8
IL_0023: stsfld ""int D.i""
IL_0028: ldftn ""void D.MIn(in int)""
IL_002e: stsfld ""delegate*<in int, void> C.Field6""
IL_0033: ldsfld ""delegate*<in int, void> C.Field6""
IL_0038: stloc.1
IL_0039: ldsflda ""int D.i""
IL_003e: ldloc.1
IL_003f: calli ""delegate*<in int, void>""
IL_0044: ret
}
");
var c = ((CSharpCompilation)verifier.Compilation).GetTypeByMetadataName("C");
var field = c.GetField("Field1");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field2");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field3");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.Out, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field4");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field5");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.Out, IsSpecialType(SpecialType.System_Int32)));
field = c.GetField("Field6");
VerifyFunctionPointerSymbol(field.Type, CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
}
[Fact]
public void RefReadonlyIsDoneByRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
private static int i = 0;
static ref readonly int GetI() => ref i;
static void Main()
{
delegate*<ref readonly int> d = &GetI;
ref readonly int local = ref d();
Console.Write(local);
i = 1;
Console.Write(local);
}
}
", expectedOutput: "01");
verifier.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
IL_0000: ldftn ""ref readonly int C.GetI()""
IL_0006: calli ""delegate*<ref readonly int>""
IL_000b: dup
IL_000c: ldind.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: ldc.i4.1
IL_0013: stsfld ""int C.i""
IL_0018: ldind.i4
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ret
}
");
}
[Fact]
public void NestedPointerTypes()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public class C
{
public unsafe delegate* unmanaged[Cdecl]<ref delegate*<ref readonly string>, void> M(delegate*<in delegate* unmanaged[Stdcall]<delegate*<void>>, delegate*<int>> param) => throw null;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
var returnType = m.ReturnType;
var paramType = m.Parameters[0].Type;
VerifyFunctionPointerSymbol(returnType, CallingConvention.CDecl,
(RefKind.None, IsVoidType()),
(RefKind.Ref,
IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_String)))));
VerifyFunctionPointerSymbol(paramType, CallingConvention.Default,
(RefKind.None,
IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsSpecialType(SpecialType.System_Int32)))),
(RefKind.In,
IsFunctionPointerTypeSymbol(CallingConvention.Standard,
(RefKind.None,
IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsVoidType()))))));
}
}
[Fact]
public void RandomModOptsFromIl()
{
var ilSource = @"
.class public auto ansi beforefieldinit Test1
extends[mscorlib] System.Object
{
.method public hidebysig instance void M(method bool modopt([mscorlib]System.Runtime.InteropServices.OutAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.ComImport) *(int32 modopt([mscorlib]System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute)& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) modopt([mscorlib]System.Runtime.InteropServices.PreserveSigAttribute)) param) cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method Test::M
}
";
var compilation = CreateCompilationWithIL(source: "", ilSource, parseOptions: TestOptions.Regular9);
var testClass = compilation.GetTypeByMetadataName("Test1")!;
var m = testClass.GetMethod("M");
Assert.NotNull(m);
var param = (FunctionPointerTypeSymbol)m.Parameters[0].Type;
VerifyFunctionPointerSymbol(param, CallingConvention.Default,
(RefKind.RefReadOnly, IsSpecialType(SpecialType.System_Boolean)),
(RefKind.In, IsSpecialType(SpecialType.System_Int32)));
var returnModifiers = param.Signature.ReturnTypeWithAnnotations.CustomModifiers;
verifyMod(1, "OutAttribute", returnModifiers);
var returnRefModifiers = param.Signature.RefCustomModifiers;
verifyMod(2, "ComImport", returnRefModifiers);
var paramModifiers = param.Signature.ParameterTypesWithAnnotations[0].CustomModifiers;
verifyMod(1, "AllowReversePInvokeCallsAttribute", paramModifiers);
var paramRefModifiers = param.Signature.Parameters[0].RefCustomModifiers;
verifyMod(2, "PreserveSigAttribute", paramRefModifiers);
static void verifyMod(int length, string expectedTypeName, ImmutableArray<CustomModifier> customMods)
{
Assert.Equal(length, customMods.Length);
var firstMod = customMods[0];
Assert.True(firstMod.IsOptional);
Assert.Equal(expectedTypeName, ((CSharpCustomModifier)firstMod).ModifierSymbol.Name);
if (length > 1)
{
Assert.Equal(2, customMods.Length);
var inMod = customMods[1];
Assert.False(inMod.IsOptional);
Assert.True(((CSharpCustomModifier)inMod).ModifierSymbol.IsWellKnownTypeInAttribute());
}
}
}
[Fact]
public void MultipleFunctionPointerArguments()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public unsafe class C
{
public void M(delegate*<ref int, ref bool> param1,
delegate*<ref int, ref bool> param2,
delegate*<ref int, ref bool> param3,
delegate*<ref int, ref bool> param4,
delegate*<ref int, ref bool> param5) {}
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var m = c.GetMethod("M");
foreach (var param in m.Parameters)
{
VerifyFunctionPointerSymbol(param.Type, CallingConvention.Default,
(RefKind.Ref, IsSpecialType(SpecialType.System_Boolean)),
(RefKind.Ref, IsSpecialType(SpecialType.System_Int32)));
}
}
}
[Fact]
public void FunctionPointersInProperties()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public unsafe class C
{
public delegate*<string, void> Prop1 { get; set; }
public delegate* unmanaged[Stdcall]<int> Prop2 { get => throw null; set => throw null; }
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
verifier.VerifyIL("C.Prop1.get", expectedIL: @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""delegate*<string, void> C.<Prop1>k__BackingField""
IL_0006: ret
}
");
verifier.VerifyIL("C.Prop1.set", expectedIL: @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""delegate*<string, void> C.<Prop1>k__BackingField""
IL_0007: ret
}
");
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
validateProperty((PropertySymbol)c.GetProperty((string)"Prop1"), IsFunctionPointerTypeSymbol(CallingConvention.Default,
(RefKind.None, IsVoidType()),
(RefKind.None, IsSpecialType(SpecialType.System_String))));
validateProperty(c.GetProperty("Prop2"), IsFunctionPointerTypeSymbol(CallingConvention.Standard,
(RefKind.None, IsSpecialType(SpecialType.System_Int32))));
static void validateProperty(PropertySymbol property, Action<TypeSymbol> verifier)
{
verifier(property.Type);
verifier(property.GetMethod.ReturnType);
verifier(property.SetMethod.GetParameterType(0));
}
}
}
[Fact]
public void FunctionPointersInFields()
{
var verifier = CompileAndVerifyFunctionPointers(@"
public unsafe class C
{
public readonly delegate*<C, C> _field;
}", symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
VerifyFunctionPointerSymbol(c.GetField("_field").Type, CallingConvention.Default,
(RefKind.None, IsTypeName("C")),
(RefKind.None, IsTypeName("C")));
}
}
[Fact]
public void CustomModifierOnReturnType()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends[mscorlib] System.Object
{
.method public hidebysig newslot virtual instance method bool modopt([mscorlib]System.Object)& *(int32&) M() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::M
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
}
";
var source = @"
class D : C
{
public unsafe override delegate*<ref int, ref bool> M() => throw null;
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub: ilSource, symbolValidator: symbolValidator);
symbolValidator(GetSourceModule(verifier));
static void symbolValidator(ModuleSymbol module)
{
var d = module.GlobalNamespace.GetMember<NamedTypeSymbol>("D");
var m = d.GetMethod("M");
var returnTypeWithAnnotations = ((FunctionPointerTypeSymbol)m.ReturnType).Signature.ReturnTypeWithAnnotations;
Assert.Equal(1, returnTypeWithAnnotations.CustomModifiers.Length);
Assert.Equal(SpecialType.System_Object, returnTypeWithAnnotations.CustomModifiers[0].Modifier.SpecialType);
}
}
[Fact]
public void UnsupportedCallingConventionInMetadata()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field public method vararg void*() 'Field'
.field private method vararg void *() '<Prop>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 )
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
.method public hidebysig specialname instance method vararg void *()
get_Prop() cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld method vararg void *() C::'<Prop>k__BackingField'
IL_0006: ret
} // end of method C::get_Prop
.method public hidebysig specialname instance void
set_Prop(method vararg void *() 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld method vararg void *() C::'<Prop>k__BackingField'
IL_0007: ret
} // end of method C::set_Prop
.property instance method vararg void *()
Prop()
{
.get instance method vararg void *() C::get_Prop()
.set instance void C::set_Prop(method vararg void *())
} // end of property C::Prop
} // end of class C
";
var source = @"
unsafe class D
{
void M(C c)
{
c.Field(__arglist(1, 2));
c.Field(1, 2, 3);
c.Field();
c.Field = c.Field;
c.Prop();
c.Prop = c.Prop;
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(source, ilSource);
comp.VerifyDiagnostics(
// (6,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(__arglist(1, 2));
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Field(__arglist(1, 2))").WithArguments("delegate* unmanaged[]<void>").WithLocation(6, 9),
// (6,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(__arglist(1, 2));
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(6, 11),
// (7,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(1, 2, 3);
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Field(1, 2, 3)").WithArguments("delegate* unmanaged[]<void>").WithLocation(7, 9),
// (7,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field(1, 2, 3);
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(7, 11),
// (8,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Field()").WithArguments("delegate* unmanaged[]<void>").WithLocation(8, 9),
// (8,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(8, 11),
// (9,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field = c.Field;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(9, 11),
// (9,21): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Field = c.Field;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Field").WithArguments("delegate* unmanaged[]<void>").WithLocation(9, 21),
// (10,9): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "c.Prop()").WithArguments("delegate* unmanaged[]<void>").WithLocation(10, 9),
// (10,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop();
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(10, 11),
// (11,11): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop = c.Prop;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(11, 11),
// (11,20): error CS8806: The calling convention of 'delegate* unmanaged[]<void>' is not supported by the language.
// c.Prop = c.Prop;
Diagnostic(ErrorCode.ERR_UnsupportedCallingConvention, "Prop").WithArguments("delegate* unmanaged[]<void>").WithLocation(11, 20)
);
var c = comp.GetTypeByMetadataName("C");
var prop = c.GetProperty("Prop");
VerifyFunctionPointerSymbol(prop.Type, CallingConvention.ExtraArguments,
(RefKind.None, IsVoidType()));
Assert.True(prop.Type.HasUseSiteError);
var field = c.GetField("Field");
var type = (FunctionPointerTypeSymbol)field.Type;
VerifyFunctionPointerSymbol(type, CallingConvention.ExtraArguments,
(RefKind.None, IsVoidType()));
Assert.True(type.HasUseSiteError);
Assert.True(type.Signature.IsVararg);
}
[Fact]
public void StructWithFunctionPointerThatReferencesStruct()
{
CompileAndVerifyFunctionPointers(@"
unsafe struct S
{
public delegate*<S, S> Field;
public delegate*<S, S> Property { get; set; }
}");
}
[Fact]
public void CalliOnParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *() LoadPtr () cil managed
{
nop
ldftn void Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
void Called () cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
class Caller
{
public unsafe static void Main()
{
Call(Program.LoadPtr());
}
public unsafe static void Call(delegate*<void> ptr)
{
ptr();
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
verifier.VerifyIL("Caller.Call(delegate*<void>)", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: calli ""delegate*<void>""
IL_0006: ret
}");
}
[Fact]
public void CalliOnFieldNoArgs()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *() LoadPtr () cil managed
{
nop
ldftn void Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
void Called () cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
unsafe class Caller
{
static delegate*<void> _field;
public unsafe static void Main()
{
_field = Program.LoadPtr();
Call();
}
public unsafe static void Call()
{
_field();
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
verifier.VerifyIL("Caller.Call()", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldsfld ""delegate*<void> Caller._field""
IL_0005: calli ""delegate*<void>""
IL_000a: ret
}");
}
[Fact]
public void CalliOnFieldArgs()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *(string) LoadPtr () cil managed
{
nop
ldftn void Program::Called(string)
ret
} // end of method Program::Main
.method private hidebysig static
void Called (string arg) cil managed
{
nop
ldarg.0
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
unsafe class Caller
{
static delegate*<string, void> _field;
public unsafe static void Main()
{
_field = Program.LoadPtr();
Call();
}
public unsafe static void Call()
{
_field(""Called"");
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: "Called");
verifier.VerifyIL("Caller.Call()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (delegate*<string, void> V_0)
IL_0000: ldsfld ""delegate*<string, void> Caller._field""
IL_0005: stloc.0
IL_0006: ldstr ""Called""
IL_000b: ldloc.0
IL_000c: calli ""delegate*<string, void>""
IL_0011: ret
}");
}
[Theory]
[InlineData("Cdecl", "Cdecl")]
[InlineData("Stdcall", "StdCall")]
public void UnmanagedCallingConventions(string unmanagedConvention, string enumConvention)
{
// Use IntPtr Marshal.GetFunctionPointerForDelegate<TDelegate>(TDelegate delegate) to
// get a function pointer around a native calling convention
var source = $@"
using System;
using System.Runtime.InteropServices;
public unsafe class UnmanagedFunctionPointer
{{
[UnmanagedFunctionPointer(CallingConvention.{enumConvention})]
public delegate string CombineStrings(string s1, string s2);
private static string CombineStringsImpl(string s1, string s2)
{{
return s1 + s2;
}}
public static delegate* unmanaged[{unmanagedConvention}]<string, string, string> GetFuncPtr(out CombineStrings del)
{{
del = CombineStringsImpl;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[{unmanagedConvention}]<string, string, string>)ptr;
}}
}}
class Caller
{{
public unsafe static void Main()
{{
Call(UnmanagedFunctionPointer.GetFuncPtr(out var del));
GC.KeepAlive(del);
}}
public unsafe static void Call(delegate* unmanaged[{unmanagedConvention}]<string, string, string> ptr)
{{
Console.WriteLine(ptr(""Hello"", "" World""));
}}
}}";
var verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "Hello World");
verifier.VerifyIL($"Caller.Call", $@"
{{
// Code size 24 (0x18)
.maxstack 3
.locals init (delegate* unmanaged[{unmanagedConvention}]<string, string, string> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldstr ""Hello""
IL_0007: ldstr "" World""
IL_000c: ldloc.0
IL_000d: calli ""delegate* unmanaged[{unmanagedConvention}]<string, string, string>""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}}");
}
[ConditionalTheory(typeof(CoreClrOnly))]
[InlineData("", "")]
[InlineData("[Cdecl]", "typeof(System.Runtime.CompilerServices.CallConvCdecl)")]
[InlineData("[Stdcall]", "typeof(System.Runtime.CompilerServices.CallConvStdcall)")]
public void UnmanagedCallingConventions_UnmanagedCallersOnlyAttribute(string delegateConventionString, string attributeArgumentString)
{
var verifier = CompileAndVerifyFunctionPointers(new[] { $@"
using System;
using System.Runtime.InteropServices;
unsafe
{{
delegate* unmanaged{delegateConventionString}<void> ptr = &M;
ptr();
[UnmanagedCallersOnly(CallConvs = new Type[] {{ {attributeArgumentString} }})]
static void M() => Console.Write(1);
}}
", UnmanagedCallersOnlyAttribute }, expectedOutput: "1", targetFramework: TargetFramework.NetCoreApp);
verifier.VerifyIL("<top-level-statements-entry-point>", $@"
{{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void Program.<<Main>$>g__M|0_0()""
IL_0006: calli ""delegate* unmanaged{delegateConventionString}<void>""
IL_000b: ret
}}
");
}
[Fact]
public void FastCall()
{
// Use IntPtr Marshal.GetFunctionPointerForDelegate<TDelegate>(TDelegate delegate) to
// get a function pointer around a native calling convention
var source = @"
using System;
using System.Runtime.InteropServices;
public unsafe class UnmanagedFunctionPointer
{
[UnmanagedFunctionPointer(CallingConvention.FastCall)]
public delegate string CombineStrings(string s1, string s2);
private static string CombineStringsImpl(string s1, string s2)
{
return s1 + s2;
}
public static delegate* unmanaged[Fastcall]<string, string, string> GetFuncPtr(out CombineStrings del)
{
del = CombineStringsImpl;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Fastcall]<string, string, string>)ptr;
}
}
class Caller
{
public unsafe static void Main()
{
Call(UnmanagedFunctionPointer.GetFuncPtr(out var del));
GC.KeepAlive(del);
}
public unsafe static void Call(delegate* unmanaged[Fastcall]<string, string, string> ptr)
{
Console.WriteLine(ptr(""Hello"", "" World""));
}
}";
// Fastcall is only supported by Mono on Windows x86, which we do not have a test leg for.
// Therefore, we just verify that the emitted IL is what we expect.
var verifier = CompileAndVerifyFunctionPointers(source);
verifier.VerifyIL($"Caller.Call(delegate* unmanaged[Fastcall]<string, string, string>)", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (delegate* unmanaged[Fastcall]<string, string, string> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldstr ""Hello""
IL_0007: ldstr "" World""
IL_000c: ldloc.0
IL_000d: calli ""delegate* unmanaged[Fastcall]<string, string, string>""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}");
}
[Fact]
public void ThiscallSimpleReturn()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
using System.Runtime.InteropServices;
unsafe struct S
{
public int i;
public static int GetInt(S* s)
{
return s->i;
}
public static int GetReturn(S* s, int i)
{
return s->i + i;
}
}
unsafe class UnmanagedFunctionPointer
{
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate int SingleParam(S* s);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate int MultipleParams(S* s, int i);
public static delegate* unmanaged[Thiscall]<S*, int> GetFuncPtrSingleParam(out SingleParam del)
{
del = S.GetInt;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, int>)ptr;
}
public static delegate* unmanaged[Thiscall]<S*, int, int> GetFuncPtrMultipleParams(out MultipleParams del)
{
del = S.GetReturn;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, int, int>)ptr;
}
}
unsafe class C
{
public static void Main()
{
TestSingle();
TestMultiple();
}
public static void TestSingle()
{
S s = new S();
s.i = 1;
var i = UnmanagedFunctionPointer.GetFuncPtrSingleParam(out var del)(&s);
Console.Write(i);
GC.KeepAlive(del);
}
public static void TestMultiple()
{
S s = new S();
s.i = 2;
var i = UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out var del)(&s, 3);
Console.Write(i);
GC.KeepAlive(del);
}
}", expectedOutput: @"15");
verifier.VerifyIL("C.TestSingle()", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (S V_0, //s
UnmanagedFunctionPointer.SingleParam V_1, //del
delegate* unmanaged[Thiscall]<S*, int> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, int> UnmanagedFunctionPointer.GetFuncPtrSingleParam(out UnmanagedFunctionPointer.SingleParam)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldloc.2
IL_001c: calli ""delegate* unmanaged[Thiscall]<S*, int>""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ldloc.1
IL_0027: call ""void System.GC.KeepAlive(object)""
IL_002c: ret
}
");
verifier.VerifyIL("C.TestMultiple()", @"
{
// Code size 46 (0x2e)
.maxstack 3
.locals init (S V_0, //s
UnmanagedFunctionPointer.MultipleParams V_1, //del
delegate* unmanaged[Thiscall]<S*, int, int> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.2
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, int, int> UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out UnmanagedFunctionPointer.MultipleParams)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldc.i4.3
IL_001c: ldloc.2
IL_001d: calli ""delegate* unmanaged[Thiscall]<S*, int, int>""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ldloc.1
IL_0028: call ""void System.GC.KeepAlive(object)""
IL_002d: ret
}
");
}
[ConditionalFact(typeof(CoreClrOnly))]
public void Thiscall_UnmanagedCallersOnly()
{
var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
unsafe
{
TestSingle();
TestMultiple();
static void TestSingle()
{
S s = new S();
s.i = 1;
delegate* unmanaged[Thiscall]<S*, int> ptr = &S.GetInt;
Console.Write(ptr(&s));
}
static void TestMultiple()
{
S s = new S();
s.i = 2;
delegate* unmanaged[Thiscall]<S*, int, int> ptr = &S.GetReturn;
Console.Write(ptr(&s, 3));
}
}
unsafe struct S
{
public int i;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
public static int GetInt(S* s)
{
return s->i;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
public static int GetReturn(S* s, int i)
{
return s->i + i;
}
}
", UnmanagedCallersOnlyAttribute }, expectedOutput: "15", targetFramework: TargetFramework.NetCoreApp);
verifier.VerifyIL(@"Program.<<Main>$>g__TestSingle|0_0()", @"
{
// Code size 38 (0x26)
.maxstack 2
.locals init (S V_0, //s
delegate* unmanaged[Thiscall]<S*, int> V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.i""
IL_0010: ldftn ""int S.GetInt(S*)""
IL_0016: stloc.1
IL_0017: ldloca.s V_0
IL_0019: conv.u
IL_001a: ldloc.1
IL_001b: calli ""delegate* unmanaged[Thiscall]<S*, int>""
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ret
}
");
verifier.VerifyIL(@"Program.<<Main>$>g__TestMultiple|0_1()", @"
{
// Code size 39 (0x27)
.maxstack 3
.locals init (S V_0, //s
delegate* unmanaged[Thiscall]<S*, int, int> V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.2
IL_000b: stfld ""int S.i""
IL_0010: ldftn ""int S.GetReturn(S*, int)""
IL_0016: stloc.1
IL_0017: ldloca.s V_0
IL_0019: conv.u
IL_001a: ldc.i4.3
IL_001b: ldloc.1
IL_001c: calli ""delegate* unmanaged[Thiscall]<S*, int, int>""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ret
}
");
}
[Fact]
public void ThiscallBlittable()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
using System.Runtime.InteropServices;
struct IntWrapper
{
public int i;
public IntWrapper(int i)
{
this.i = i;
}
}
struct ReturnWrapper
{
public int i1;
public float f2;
public ReturnWrapper(int i1, float f2)
{
this.i1 = i1;
this.f2 = f2;
}
}
unsafe struct S
{
public int i;
public static IntWrapper GetInt(S* s)
{
return new IntWrapper(s->i);
}
public static ReturnWrapper GetReturn(S* s, float f)
{
return new ReturnWrapper(s->i, f);
}
}
unsafe class UnmanagedFunctionPointer
{
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate IntWrapper SingleParam(S* s);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate ReturnWrapper MultipleParams(S* s, float f);
public static delegate* unmanaged[Thiscall]<S*, IntWrapper> GetFuncPtrSingleParam(out SingleParam del)
{
del = S.GetInt;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, IntWrapper>)ptr;
}
public static delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> GetFuncPtrMultipleParams(out MultipleParams del)
{
del = S.GetReturn;
var ptr = Marshal.GetFunctionPointerForDelegate(del);
return (delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper>)ptr;
}
}
unsafe class C
{
public static void Main()
{
TestSingle();
TestMultiple();
}
public static void TestSingle()
{
S s = new S();
s.i = 1;
var intWrapper = UnmanagedFunctionPointer.GetFuncPtrSingleParam(out var del)(&s);
Console.WriteLine(intWrapper.i);
GC.KeepAlive(del);
}
public static void TestMultiple()
{
S s = new S();
s.i = 2;
var returnWrapper = UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out var del)(&s, 3.5f);
Console.Write(returnWrapper.i1);
Console.Write(returnWrapper.f2);
GC.KeepAlive(del);
}
}", expectedOutput: @"
1
23.5
");
verifier.VerifyIL("C.TestSingle()", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (S V_0, //s
UnmanagedFunctionPointer.SingleParam V_1, //del
delegate* unmanaged[Thiscall]<S*, IntWrapper> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, IntWrapper> UnmanagedFunctionPointer.GetFuncPtrSingleParam(out UnmanagedFunctionPointer.SingleParam)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldloc.2
IL_001c: calli ""delegate* unmanaged[Thiscall]<S*, IntWrapper>""
IL_0021: ldfld ""int IntWrapper.i""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: ldloc.1
IL_002c: call ""void System.GC.KeepAlive(object)""
IL_0031: ret
}
");
verifier.VerifyIL("C.TestMultiple()", @"
{
// Code size 66 (0x42)
.maxstack 3
.locals init (S V_0, //s
UnmanagedFunctionPointer.MultipleParams V_1, //del
delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.2
IL_000b: stfld ""int S.i""
IL_0010: ldloca.s V_1
IL_0012: call ""delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper> UnmanagedFunctionPointer.GetFuncPtrMultipleParams(out UnmanagedFunctionPointer.MultipleParams)""
IL_0017: stloc.2
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: ldc.r4 3.5
IL_0020: ldloc.2
IL_0021: calli ""delegate* unmanaged[Thiscall]<S*, float, ReturnWrapper>""
IL_0026: dup
IL_0027: ldfld ""int ReturnWrapper.i1""
IL_002c: call ""void System.Console.Write(int)""
IL_0031: ldfld ""float ReturnWrapper.f2""
IL_0036: call ""void System.Console.Write(float)""
IL_003b: ldloc.1
IL_003c: call ""void System.GC.KeepAlive(object)""
IL_0041: ret
}");
}
[Fact]
public void InvocationOrder()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *(string, string) LoadPtr () cil managed
{
nop
ldftn void Program::Called(string, string)
ret
} // end of method Program::Main
.method private hidebysig static
void Called (
string arg1,
string arg2) cil managed
{
nop
ldarg.0
ldarg.1
call string [mscorlib]System.String::Concat(string, string)
call void [mscorlib]System.Console::WriteLine(string)
nop
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib]
System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}";
var source = @"
using System;
unsafe class C
{
static delegate*<string, string, void> Prop
{
get
{
Console.WriteLine(""Getter"");
return Program.LoadPtr();
}
}
static delegate*<string, string, void> Method()
{
Console.WriteLine(""Method"");
return Program.LoadPtr();
}
static string GetArg(string val)
{
Console.WriteLine($""Getting {val}"");
return val;
}
static void PropertyOrder()
{
Prop(GetArg(""1""), GetArg(""2""));
}
static void MethodOrder()
{
Method()(GetArg(""3""), GetArg(""4""));
}
static void Main()
{
Console.WriteLine(""Property Access"");
PropertyOrder();
Console.WriteLine(""Method Access"");
MethodOrder();
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Property Access
Getter
Getting 1
Getting 2
12
Method Access
Method
Getting 3
Getting 4
34");
verifier.VerifyIL("C.PropertyOrder", expectedIL: @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (delegate*<string, string, void> V_0)
IL_0000: call ""delegate*<string, string, void> C.Prop.get""
IL_0005: stloc.0
IL_0006: ldstr ""1""
IL_000b: call ""string C.GetArg(string)""
IL_0010: ldstr ""2""
IL_0015: call ""string C.GetArg(string)""
IL_001a: ldloc.0
IL_001b: calli ""delegate*<string, string, void>""
IL_0020: ret
}");
verifier.VerifyIL("C.MethodOrder()", expectedIL: @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (delegate*<string, string, void> V_0)
IL_0000: call ""delegate*<string, string, void> C.Method()""
IL_0005: stloc.0
IL_0006: ldstr ""3""
IL_000b: call ""string C.GetArg(string)""
IL_0010: ldstr ""4""
IL_0015: call ""string C.GetArg(string)""
IL_001a: ldloc.0
IL_001b: calli ""delegate*<string, string, void>""
IL_0020: ret
}");
}
[Fact]
public void ReturnValueUsed()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method string *(string) LoadPtr () cil managed
{
nop
ldftn string Program::Called(string)
ret
} // end of method Program::Main
.method private hidebysig static
string Called (string arg) cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
var retValue = Program.LoadPtr()(""Returned"");
Console.WriteLine(retValue);
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called
Returned");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (delegate*<string, string> V_0)
IL_0000: call ""delegate*<string, string> Program.LoadPtr()""
IL_0005: stloc.0
IL_0006: ldstr ""Returned""
IL_000b: ldloc.0
IL_000c: calli ""delegate*<string, string>""
IL_0011: call ""void System.Console.WriteLine(string)""
IL_0016: ret
}");
}
[Fact]
public void ReturnValueUnused()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method string *(string) LoadPtr () cil managed
{
nop
ldftn string Program::Called(string)
ret
} // end of method Program::Main
.method private hidebysig static
string Called (string arg) cil managed
{
nop
ldstr ""Called""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
Program.LoadPtr()(""Unused"");
Console.WriteLine(""Constant"");
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called
Constant");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<string, string> V_0)
IL_0000: call ""delegate*<string, string> Program.LoadPtr()""
IL_0005: stloc.0
IL_0006: ldstr ""Unused""
IL_000b: ldloc.0
IL_000c: calli ""delegate*<string, string>""
IL_0011: pop
IL_0012: ldstr ""Constant""
IL_0017: call ""void System.Console.WriteLine(string)""
IL_001c: ret
}");
}
[Fact]
public void FunctionPointerReturningFunctionPointer()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method method string *(string) *() LoadPtr () cil managed
{
nop
ldftn method string *(string) Program::Called1()
ret
} // end of method Program::LoadPtr
.method private hidebysig static
method string *(string) Called1 () cil managed
{
nop
ldstr ""Outer pointer""
call void [mscorlib]System.Console::WriteLine(string)
ldftn string Program::Called2(string)
ret
} // end of Program::Called1
.method private hidebysig static
string Called2 (string arg) cil managed
{
nop
ldstr ""Inner pointer""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
ret
} // end of Program::Called2
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
public static void Main()
{
var outer = Program.LoadPtr();
var inner = outer();
Console.WriteLine(inner(""Returned""));
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Outer pointer
Inner pointer
Returned");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (delegate*<string, string> V_0)
IL_0000: call ""delegate*<delegate*<string, string>> Program.LoadPtr()""
IL_0005: calli ""delegate*<delegate*<string, string>>""
IL_000a: stloc.0
IL_000b: ldstr ""Returned""
IL_0010: ldloc.0
IL_0011: calli ""delegate*<string, string>""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: ret
}");
}
[Fact]
public void UserDefinedConversionParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.field public string '_field'
// Methods
.method public hidebysig static
method void *(class Program) LoadPtr () cil managed
{
nop
ldstr ""LoadPtr""
call void [mscorlib]System.Console::WriteLine(string)
ldftn void Program::Called(class Program)
ret
} // end of method Program::LoadPtr
.method private hidebysig static
void Called (class Program arg1) cil managed
{
nop
ldarg.0
ldfld string Program::'_field'
call void [mscorlib]System.Console::WriteLine(string)
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
public static void Main()
{
Program.LoadPtr()(new C());
}
public static implicit operator Program(C c)
{
var p = new Program();
p._field = ""Implicit conversion"";
return p;
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
LoadPtr
Implicit conversion
");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (delegate*<Program, void> V_0)
IL_0000: call ""delegate*<Program, void> Program.LoadPtr()""
IL_0005: stloc.0
IL_0006: newobj ""C..ctor()""
IL_000b: call ""Program C.op_Implicit(C)""
IL_0010: ldloc.0
IL_0011: calli ""delegate*<Program, void>""
IL_0016: ret
}");
}
[Fact]
public void RefParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method void *(string&) LoadPtr () cil managed
{
nop
ldftn void Program::Called(string&)
ret
} // end of method Program::Main
.method private hidebysig static
void Called (string& arg) cil managed
{
nop
ldarg.0
ldstr ""Ref set""
stind.ref
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
delegate*<ref string, void> pointer = Program.LoadPtr();
string str = ""Unset"";
pointer(ref str);
Console.WriteLine(str);
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Ref set");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (string V_0, //str
delegate*<ref string, void> V_1)
IL_0000: call ""delegate*<ref string, void> Program.LoadPtr()""
IL_0005: ldstr ""Unset""
IL_000a: stloc.0
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: ldloc.1
IL_000f: calli ""delegate*<ref string, void>""
IL_0014: ldloc.0
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}");
}
[Fact]
public void RefReturnUsedByValue()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.field public static string 'field'
// Methods
.method public hidebysig static
method string& *() LoadPtr () cil managed
{
nop
ldftn string& Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
string& Called () cil managed
{
nop
ldsflda string Program::'field'
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
Program.field = ""Field"";
delegate*<ref string> pointer = Program.LoadPtr();
Console.WriteLine(pointer());
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Field");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 1
IL_0000: ldstr ""Field""
IL_0005: stsfld ""string Program.field""
IL_000a: call ""delegate*<ref string> Program.LoadPtr()""
IL_000f: calli ""delegate*<ref string>""
IL_0014: ldind.ref
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}");
}
[Fact]
public void RefReturnUsed()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.field public static string 'field'
// Methods
.method public hidebysig static
method string& *() LoadPtr () cil managed
{
nop
ldftn string& Program::Called()
ret
} // end of method Program::Main
.method private hidebysig static
string& Called () cil managed
{
nop
ldsflda string Program::'field'
ret
} // end of Program::Called
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
static void Main()
{
Program.LoadPtr()() = ""Field"";
Console.WriteLine(Program.field);
}
}
";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"Field");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: call ""delegate*<ref string> Program.LoadPtr()""
IL_0005: calli ""delegate*<ref string>""
IL_000a: ldstr ""Field""
IL_000f: stind.ref
IL_0010: ldsfld ""string Program.field""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}
");
}
[Fact]
public void ModifiedReceiverInParameter()
{
var ilStub = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
method string *(string) LoadPtr1 () cil managed
{
nop
ldftn string Program::Called1(string)
ret
} // end of method Program::LoadPtr1
.method public hidebysig static
method string *(string) LoadPtr2 () cil managed
{
nop
ldftn string Program::Called2(string)
ret
} // end of method Program::LoadPtr2
.method private hidebysig static
string Called1 (string) cil managed
{
nop
ldstr ""Called Function 1""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
call void [mscorlib]System.Console::WriteLine(string)
ldstr ""Returned From Function 1""
ret
} // end of Program::Called1
.method private hidebysig static
string Called2 (string) cil managed
{
nop
ldstr ""Called Function 2""
call void [mscorlib]System.Console::WriteLine(string)
ldarg.0
call void [mscorlib]System.Console::WriteLine(string)
ldstr ""Returned From Function 2""
ret
} // end of Program::Called2
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void[mscorlib] System.Object::.ctor()
nop
ret
} // end of Program::.ctor
}
";
var source = @"
using System;
unsafe class C
{
public static void Main()
{
var ptr = Program.LoadPtr1();
Console.WriteLine(ptr((ptr = Program.LoadPtr2())(""Argument To Function 2"")));
Console.WriteLine(ptr(""Argument To Function 2""));
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, ilStub, expectedOutput: @"
Called Function 2
Argument To Function 2
Called Function 1
Returned From Function 2
Returned From Function 1
Called Function 2
Argument To Function 2
Returned From Function 2");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (delegate*<string, string> V_0, //ptr
delegate*<string, string> V_1,
delegate*<string, string> V_2)
IL_0000: call ""delegate*<string, string> Program.LoadPtr1()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: stloc.1
IL_0008: call ""delegate*<string, string> Program.LoadPtr2()""
IL_000d: dup
IL_000e: stloc.0
IL_000f: stloc.2
IL_0010: ldstr ""Argument To Function 2""
IL_0015: ldloc.2
IL_0016: calli ""delegate*<string, string>""
IL_001b: ldloc.1
IL_001c: calli ""delegate*<string, string>""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ldloc.0
IL_0027: stloc.1
IL_0028: ldstr ""Argument To Function 2""
IL_002d: ldloc.1
IL_002e: calli ""delegate*<string, string>""
IL_0033: call ""void System.Console.WriteLine(string)""
IL_0038: ret
}");
}
[Fact]
public void Typeof()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
class C
{
static void Main()
{
var t = typeof(delegate*<void>);
Console.WriteLine(t.ToString());
}
}
", expectedOutput: "System.IntPtr");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 21 (0x15)
.maxstack 1
IL_0000: ldtoken ""delegate*<void>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: callvirt ""string object.ToString()""
IL_000f: call ""void System.Console.WriteLine(string)""
IL_0014: ret
}");
}
private const string NoPiaInterfaces = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
[assembly: PrimaryInteropAssemblyAttribute(1,1)]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
[ComImport]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
public interface I1
{
string GetStr();
}
[ComImport]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58270"")]
public interface I2{}";
[Fact]
public void NoPiaInSignature()
{
var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);
CompileAndVerifyFunctionPointers(@"
unsafe class C
{
public delegate*<I2, I1> M() => throw null;
}", references: new[] { nopiaReference }, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
Assert.Equal(1, module.ReferencedAssemblies.Length);
Assert.NotEqual(nopiaReference.Display, module.ReferencedAssemblies[0].Name);
var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
Assert.NotNull(i1);
Assert.Equal(module, i1.ContainingModule);
var i2 = module.GlobalNamespace.GetTypeMembers("I2").Single();
Assert.NotNull(i2);
Assert.Equal(module, i2.ContainingModule);
var c = module.GlobalNamespace.GetTypeMembers("C").Single();
var m = c.GetMethod("M");
var returnType = (FunctionPointerTypeSymbol)m.ReturnType;
Assert.Equal(i1, returnType.Signature.ReturnType);
Assert.Equal(i2, returnType.Signature.ParameterTypesWithAnnotations[0].Type);
}
}
[Fact]
public void NoPiaInTypeOf()
{
var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);
CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public Type M() => typeof(delegate*<I1, I2>);
}", references: new[] { nopiaReference }, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
Assert.Equal(1, module.ReferencedAssemblies.Length);
Assert.NotEqual(nopiaReference.Display, module.ReferencedAssemblies[0].Name);
var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
Assert.NotNull(i1);
Assert.Equal(module, i1.ContainingModule);
var i2 = module.GlobalNamespace.GetTypeMembers("I2").Single();
Assert.NotNull(i2);
Assert.Equal(module, i2.ContainingModule);
}
}
[Fact]
public void NoPiaInCall()
{
var nopiaReference = CreateCompilation(NoPiaInterfaces).EmitToImageReference(embedInteropTypes: true);
var intermediate = CreateCompilation(@"
using System;
public unsafe class C
{
public delegate*<I1> M() => throw null;
}", references: new[] { nopiaReference }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
CompileAndVerifyFunctionPointers(@"
unsafe class C2
{
public void M(C c)
{
_ = c.M()();
}
}", references: new[] { nopiaReference, intermediate }, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
Assert.Equal(2, module.ReferencedAssemblies.Length);
Assert.DoesNotContain(nopiaReference.Display, module.ReferencedAssemblies.Select(a => a.Name));
Assert.Equal(intermediate.Display, module.ReferencedAssemblies[1].Name);
var i1 = module.GlobalNamespace.GetTypeMembers("I1").Single();
Assert.NotNull(i1);
Assert.Equal(module, i1.ContainingModule);
}
}
[Fact]
public void InternalsVisibleToAccessChecks_01()
{
var aRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""B"")]
internal class A {}", assemblyName: "A").EmitToImageReference();
var bRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""C"")]
internal class B
{
internal unsafe delegate*<A> M() => throw null;
}", references: new[] { aRef }, assemblyName: "B", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
var cComp = CreateCompilation(@"
internal class C
{
internal unsafe void CM(B b)
{
b.M()();
}
}", references: new[] { aRef, bRef }, assemblyName: "C", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
cComp.VerifyDiagnostics(
// (6,9): error CS0122: 'B.M()' is inaccessible due to its protection level
// b.M()();
Diagnostic(ErrorCode.ERR_BadAccess, "b.M").WithArguments("B.M()").WithLocation(6, 9));
}
[Fact]
public void InternalsVisibleToAccessChecks_02()
{
var aRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
public class A {}", assemblyName: "A").EmitToImageReference();
var bRef = CreateCompilation(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""C"")]
internal class B
{
internal unsafe delegate*<A> M() => throw null;
}", references: new[] { aRef }, assemblyName: "B", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll).EmitToImageReference();
var cComp = CreateCompilation(@"
internal class C
{
internal unsafe void CM(B b)
{
b.M()();
}
}", references: new[] { aRef, bRef }, assemblyName: "C", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
cComp.VerifyDiagnostics();
}
[Fact]
public void AddressOf_Initializer_VoidReturnNoParams()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M() => Console.Write(""1"");
static void Main()
{
delegate*<void> ptr = &M;
ptr();
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void C.M()""
IL_0006: calli ""delegate*<void>""
IL_000b: ret
}");
}
[Fact]
public void AddressOf_Initializer_VoidReturnValueParams()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(string s, int i) => Console.Write(s + i.ToString());
static void Main()
{
delegate*<string, int, void> ptr = &M;
ptr(""1"", 2);
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (delegate*<string, int, void> V_0)
IL_0000: ldftn ""void C.M(string, int)""
IL_0006: stloc.0
IL_0007: ldstr ""1""
IL_000c: ldc.i4.2
IL_000d: ldloc.0
IL_000e: calli ""delegate*<string, int, void>""
IL_0013: ret
}");
}
[Fact]
public void AddressOf_Initializer_VoidReturnRefParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(ref string s, in int i, out object o)
{
Console.Write(s + i.ToString());
s = ""3"";
o = ""4"";
}
static void Main()
{
delegate*<ref string, in int, out object, void> ptr = &M;
string s = ""1"";
int i = 2;
ptr(ref s, in i, out var o);
Console.Write(s);
Console.Write(o);
}
}", expectedOutput: "1234");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 4
.locals init (string V_0, //s
int V_1, //i
object V_2, //o
delegate*<ref string, in int, out object, void> V_3)
IL_0000: ldftn ""void C.M(ref string, in int, out object)""
IL_0006: ldstr ""1""
IL_000b: stloc.0
IL_000c: ldc.i4.2
IL_000d: stloc.1
IL_000e: stloc.3
IL_000f: ldloca.s V_0
IL_0011: ldloca.s V_1
IL_0013: ldloca.s V_2
IL_0015: ldloc.3
IL_0016: calli ""delegate*<ref string, in int, out object, void>""
IL_001b: ldloc.0
IL_001c: call ""void System.Console.Write(string)""
IL_0021: ldloc.2
IL_0022: call ""void System.Console.Write(object)""
IL_0027: ret
}");
}
[Fact]
public void AddressOf_Initializer_ReturnStruct()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe struct S
{
int i;
public S(int i)
{
this.i = i;
}
void M() => Console.Write(i);
static S MakeS(int i) => new S(i);
public static void Main()
{
delegate*<int, S> ptr = &MakeS;
ptr(1).M();
}
}", expectedOutput: "1");
verifier.VerifyIL("S.Main()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (delegate*<int, S> V_0,
S V_1)
IL_0000: ldftn ""S S.MakeS(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, S>""
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: call ""void S.M()""
IL_0016: ret
}");
}
[Fact]
public void AddressOf_Initializer_ReturnClass()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
int i;
public C(int i)
{
this.i = i;
}
void M() => Console.Write(i);
static C MakeC(int i) => new C(i);
public static void Main()
{
delegate*<int, C> ptr = &MakeC;
ptr(1).M();
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
.locals init (delegate*<int, C> V_0)
IL_0000: ldftn ""C C.MakeC(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, C>""
IL_000e: callvirt ""void C.M()""
IL_0013: ret
}");
}
[Fact]
public void AddressOf_Initializer_ContravariantParameters()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(object o, void* i) => Console.Write(o.ToString() + (*((int*)i)).ToString());
static void Main()
{
delegate*<string, int*, void> ptr = &M;
int i = 2;
ptr(""1"", &i);
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //i
delegate*<string, int*, void> V_1)
IL_0000: ldftn ""void C.M(object, void*)""
IL_0006: ldc.i4.2
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldstr ""1""
IL_000e: ldloca.s V_0
IL_0010: conv.u
IL_0011: ldloc.1
IL_0012: calli ""delegate*<string, int*, void>""
IL_0017: ret
}");
}
[Fact]
public void AddressOf_Initializer_CovariantReturns()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
public unsafe class C
{
static string M1() => ""1"";
static int i = 2;
static int* M2()
{
fixed (int* i1 = &i)
{
return i1;
}
}
static void Main()
{
delegate*<object> ptr1 = &M1;
Console.Write(ptr1());
delegate*<void*> ptr2 = &M2;
Console.Write(*(int*)ptr2());
}
}
", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 34 (0x22)
.maxstack 1
IL_0000: ldftn ""string C.M1()""
IL_0006: calli ""delegate*<object>""
IL_000b: call ""void System.Console.Write(object)""
IL_0010: ldftn ""int* C.M2()""
IL_0016: calli ""delegate*<void*>""
IL_001b: ldind.i4
IL_001c: call ""void System.Console.Write(int)""
IL_0021: ret
}");
}
[Fact]
public void AddressOf_FunctionPointerConversionReturn()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static string ToStringer(object o) => o.ToString();
static delegate*<object, string> Returner() => &ToStringer;
public static void Main()
{
delegate*<delegate*<string, object>> ptr = &Returner;
Console.Write(ptr()(""1""));
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<string, object> V_0)
IL_0000: ldftn ""delegate*<object, string> C.Returner()""
IL_0006: calli ""delegate*<delegate*<string, object>>""
IL_000b: stloc.0
IL_000c: ldstr ""1""
IL_0011: ldloc.0
IL_0012: calli ""delegate*<string, object>""
IL_0017: call ""void System.Console.Write(object)""
IL_001c: ret
}
");
}
[Theory]
[InlineData("in")]
[InlineData("ref")]
public void AddressOf_Initializer_Overloads(string refType)
{
var verifier = CompileAndVerifyFunctionPointers($@"
using System;
unsafe class C
{{
static void M(object o) => Console.Write(""object"" + o.ToString());
static void M(string s) => Console.Write(""string"" + s);
static void M({refType} string s) {{ Console.Write(""{refType}"" + s); }}
static void M(int i) => Console.Write(""int"" + i.ToString());
static void Main()
{{
delegate*<string, void> ptr = &M;
ptr(""1"");
string s = ""2"";
delegate*<{refType} string, void> ptr2 = &M;
ptr2({refType} s);
}}
}}", expectedOutput: $"string1{refType}2");
verifier.VerifyIL("C.Main()", expectedIL: $@"
{{
// Code size 40 (0x28)
.maxstack 2
.locals init (string V_0, //s
delegate*<string, void> V_1,
delegate*<{refType} string, void> V_2)
IL_0000: ldftn ""void C.M(string)""
IL_0006: stloc.1
IL_0007: ldstr ""1""
IL_000c: ldloc.1
IL_000d: calli ""delegate*<string, void>""
IL_0012: ldstr ""2""
IL_0017: stloc.0
IL_0018: ldftn ""void C.M({refType} string)""
IL_001e: stloc.2
IL_001f: ldloca.s V_0
IL_0021: ldloc.2
IL_0022: calli ""delegate*<{refType} string, void>""
IL_0027: ret
}}
");
}
[Fact]
public void AddressOf_Initializer_Overloads_Out()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(object o) => Console.Write(""object"" + o.ToString());
static void M(string s) => Console.Write(""string"" + s);
static void M(out string s) { s = ""2""; }
static void M(int i) => Console.Write(""int"" + i.ToString());
static void Main()
{
delegate*<string, void> ptr = &M;
ptr(""1"");
delegate*<out string, void> ptr2 = &M;
ptr2(out string s);
Console.Write(s);
}
}", expectedOutput: $"string12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (string V_0, //s
delegate*<string, void> V_1,
delegate*<out string, void> V_2)
IL_0000: ldftn ""void C.M(string)""
IL_0006: stloc.1
IL_0007: ldstr ""1""
IL_000c: ldloc.1
IL_000d: calli ""delegate*<string, void>""
IL_0012: ldftn ""void C.M(out string)""
IL_0018: stloc.2
IL_0019: ldloca.s V_0
IL_001b: ldloc.2
IL_001c: calli ""delegate*<out string, void>""
IL_0021: ldloc.0
IL_0022: call ""void System.Console.Write(string)""
IL_0027: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var addressOfs = syntaxTree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[0],
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.String, System.Void>",
expectedSymbol: "void C.M(System.String s)");
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[1],
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<out modreq(System.Runtime.InteropServices.OutAttribute) System.String, System.Void>",
expectedSymbol: "void C.M(out System.String s)");
string[] expectedMembers = new[] {
"void C.M(System.Object o)",
"void C.M(System.String s)",
"void C.M(out System.String s)",
"void C.M(System.Int32 i)"
};
AssertEx.Equal(expectedMembers, model.GetMemberGroup(addressOfs[0].Operand).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
AssertEx.Equal(expectedMembers, model.GetMemberGroup(addressOfs[1].Operand).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
}
[Fact]
public void AddressOf_Initializer_Overloads_NoMostSpecific()
{
var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
static class IHelpers
{
public static void M(I1 i1) {}
public static void M(I2 i2) {}
}
class C : I1, I2
{
unsafe static void Main()
{
delegate*<C, void> ptr = &IHelpers.M;
}
}");
comp.VerifyDiagnostics(
// (13,35): error CS0121: The call is ambiguous between the following methods or properties: 'IHelpers.M(I1)' and 'IHelpers.M(I2)'
// delegate*<C, void> ptr = &IHelpers.M;
Diagnostic(ErrorCode.ERR_AmbigCall, "IHelpers.M").WithArguments("IHelpers.M(I1)", "IHelpers.M(I2)").WithLocation(13, 35)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var addressOf = syntaxTree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
expectedSyntax: "&IHelpers.M",
expectedType: null,
expectedConvertedType: "delegate*<C, System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void IHelpers.M(I1 i1)", "void IHelpers.M(I2 i2)" });
}
[Fact]
public void AddressOf_Initializer_Overloads_RefNotCovariant()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
void M1(ref object o) {}
void M2(in object o) {}
void M3(out string s) => throw null;
void M()
{
delegate*<ref string, void> ptr1 = &M1;
delegate*<string, void> ptr2 = &M1;
delegate*<in string, void> ptr3 = &M2;
delegate*<string, void> ptr4 = &M2;
delegate*<out object, void> ptr5 = &M3;
delegate*<string, void> ptr6 = &M3;
}
}");
comp.VerifyDiagnostics(
// (9,44): error CS8757: No overload for 'M1' matches function pointer 'delegate*<ref string, void>'
// delegate*<ref string, void> ptr1 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<ref string, void>").WithLocation(9, 44),
// (10,40): error CS8757: No overload for 'M1' matches function pointer 'delegate*<string, void>'
// delegate*<string, void> ptr2 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<string, void>").WithLocation(10, 40),
// (11,43): error CS8757: No overload for 'M2' matches function pointer 'delegate*<in string, void>'
// delegate*<in string, void> ptr3 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<in string, void>").WithLocation(11, 43),
// (12,40): error CS8757: No overload for 'M2' matches function pointer 'delegate*<string, void>'
// delegate*<string, void> ptr4 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<string, void>").WithLocation(12, 40),
// (13,44): error CS8757: No overload for 'M3' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr5 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<out object, void>").WithLocation(13, 44),
// (14,40): error CS8757: No overload for 'M3' matches function pointer 'delegate*<string, void>'
// delegate*<string, void> ptr6 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<string, void>").WithLocation(14, 40)
);
}
[Fact]
public void AddressOf_RefsMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
void M1(ref object o) {}
void M2(in object o) {}
void M3(out object s) => throw null;
void M4(object s) => throw null;
ref object M5() => throw null;
ref readonly object M6() => throw null;
object M7() => throw null!;
void M()
{
delegate*<object, void> ptr1 = &M1;
delegate*<object, void> ptr2 = &M2;
delegate*<object, void> ptr3 = &M3;
delegate*<ref object, void> ptr4 = &M2;
delegate*<ref object, void> ptr5 = &M3;
delegate*<ref object, void> ptr6 = &M4;
delegate*<in object, void> ptr7 = &M1;
delegate*<in object, void> ptr8 = &M3;
delegate*<in object, void> ptr9 = &M4;
delegate*<out object, void> ptr10 = &M1;
delegate*<out object, void> ptr11 = &M2;
delegate*<out object, void> ptr12 = &M4;
delegate*<object> ptr13 = &M5;
delegate*<object> ptr14 = &M6;
delegate*<ref object> ptr15 = &M6;
delegate*<ref object> ptr16 = &M7;
delegate*<ref readonly object> ptr17 = &M5;
delegate*<ref readonly object> ptr18 = &M7;
}
}");
comp.VerifyDiagnostics(
// (13,40): error CS8757: No overload for 'M1' matches function pointer 'delegate*<object, void>'
// delegate*<object, void> ptr1 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<object, void>").WithLocation(13, 40),
// (14,40): error CS8757: No overload for 'M2' matches function pointer 'delegate*<object, void>'
// delegate*<object, void> ptr2 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<object, void>").WithLocation(14, 40),
// (15,40): error CS8757: No overload for 'M3' matches function pointer 'delegate*<object, void>'
// delegate*<object, void> ptr3 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<object, void>").WithLocation(15, 40),
// (16,44): error CS8757: No overload for 'M2' matches function pointer 'delegate*<ref object, void>'
// delegate*<ref object, void> ptr4 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<ref object, void>").WithLocation(16, 44),
// (17,44): error CS8757: No overload for 'M3' matches function pointer 'delegate*<ref object, void>'
// delegate*<ref object, void> ptr5 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<ref object, void>").WithLocation(17, 44),
// (18,44): error CS8757: No overload for 'M4' matches function pointer 'delegate*<ref object, void>'
// delegate*<ref object, void> ptr6 = &M4;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<ref object, void>").WithLocation(18, 44),
// (19,43): error CS8757: No overload for 'M1' matches function pointer 'delegate*<in object, void>'
// delegate*<in object, void> ptr7 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<in object, void>").WithLocation(19, 43),
// (20,43): error CS8757: No overload for 'M3' matches function pointer 'delegate*<in object, void>'
// delegate*<in object, void> ptr8 = &M3;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M3").WithArguments("M3", "delegate*<in object, void>").WithLocation(20, 43),
// (21,43): error CS8757: No overload for 'M4' matches function pointer 'delegate*<in object, void>'
// delegate*<in object, void> ptr9 = &M4;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<in object, void>").WithLocation(21, 43),
// (22,45): error CS8757: No overload for 'M1' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr10 = &M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M1").WithArguments("M1", "delegate*<out object, void>").WithLocation(22, 45),
// (23,45): error CS8757: No overload for 'M2' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr11 = &M2;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M2").WithArguments("M2", "delegate*<out object, void>").WithLocation(23, 45),
// (24,45): error CS8757: No overload for 'M4' matches function pointer 'delegate*<out object, void>'
// delegate*<out object, void> ptr12 = &M4;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M4").WithArguments("M4", "delegate*<out object, void>").WithLocation(24, 45),
// (25,36): error CS8758: Ref mismatch between 'C.M5()' and function pointer 'delegate*<object>'
// delegate*<object> ptr13 = &M5;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M5").WithArguments("C.M5()", "delegate*<object>").WithLocation(25, 36),
// (26,36): error CS8758: Ref mismatch between 'C.M6()' and function pointer 'delegate*<object>'
// delegate*<object> ptr14 = &M6;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M6").WithArguments("C.M6()", "delegate*<object>").WithLocation(26, 36),
// (27,40): error CS8758: Ref mismatch between 'C.M6()' and function pointer 'delegate*<ref object>'
// delegate*<ref object> ptr15 = &M6;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M6").WithArguments("C.M6()", "delegate*<ref object>").WithLocation(27, 40),
// (28,40): error CS8758: Ref mismatch between 'C.M7()' and function pointer 'delegate*<ref object>'
// delegate*<ref object> ptr16 = &M7;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M7").WithArguments("C.M7()", "delegate*<ref object>").WithLocation(28, 40),
// (29,49): error CS8758: Ref mismatch between 'C.M5()' and function pointer 'delegate*<ref readonly object>'
// delegate*<ref readonly object> ptr17 = &M5;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M5").WithArguments("C.M5()", "delegate*<ref readonly object>").WithLocation(29, 49),
// (30,49): error CS8758: Ref mismatch between 'C.M7()' and function pointer 'delegate*<ref readonly object>'
// delegate*<ref readonly object> ptr18 = &M7;
Diagnostic(ErrorCode.ERR_FuncPtrRefMismatch, "M7").WithArguments("C.M7()", "delegate*<ref readonly object>").WithLocation(30, 49)
);
}
[Theory]
[InlineData("unmanaged[Cdecl]", "CDecl")]
[InlineData("unmanaged[Stdcall]", "Standard")]
[InlineData("unmanaged[Thiscall]", "ThisCall")]
public void AddressOf_CallingConventionMustMatch(string callingConventionKeyword, string callingConvention)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
static void M1() {{}}
static void M()
{{
delegate* {callingConventionKeyword}<void> ptr = &M1;
}}
}}");
comp.VerifyDiagnostics(
// (7,41): error CS8786: Calling convention of 'C.M1()' is not compatible with '{callingConvention}'.
// delegate* {callingConventionKeyword}<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1").WithArguments("C.M1()", callingConvention).WithLocation(7, 33 + callingConventionKeyword.Length));
}
[Fact]
public void AddressOf_Assignment()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static string Convert(int i) => i.ToString();
static void Main()
{
delegate*<int, string> ptr;
ptr = &Convert;
Console.Write(ptr(1));
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
.locals init (delegate*<int, string> V_0)
IL_0000: ldftn ""string C.Convert(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, string>""
IL_000e: call ""void System.Console.Write(string)""
IL_0013: ret
}");
}
[Fact]
public void AddressOf_NonStaticMethods()
{
var comp = CreateCompilationWithFunctionPointers(@"
public class C
{
public unsafe void M()
{
delegate*<void> ptr1 = &M;
int? i = null;
delegate*<int> ptr2 = &i.GetValueOrDefault;
}
}", targetFramework: TargetFramework.Standard);
comp.VerifyDiagnostics(
// (6,33): error CS8759: Cannot bind function pointer to 'C.M()' because it is not a static method
// delegate*<void> ptr1 = &M;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "M").WithArguments("C.M()").WithLocation(6, 33),
// (8,32): error CS8759: Cannot bind function pointer to 'int?.GetValueOrDefault()' because it is not a static method
// delegate*<int> ptr2 = &i.GetValueOrDefault;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "i.GetValueOrDefault").WithArguments("int?.GetValueOrDefault()").WithLocation(8, 32)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var declarators = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Initializer!.Value.IsKind(SyntaxKind.AddressOfExpression)).ToArray();
var addressOfs = declarators.Select(d => d.Initializer!.Value).ToArray();
Assert.Equal(2, addressOfs.Length);
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[0],
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
VerifyOperationTreeForNode(comp, model, declarators[0], expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Void> ptr1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr1 = &M')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Void>, IsInvalid, IsImplicit) (Syntax: '&M')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOfs[1],
expectedSyntax: "&i.GetValueOrDefault",
expectedType: null,
expectedConvertedType: "delegate*<System.Int32>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "System.Int32 System.Int32?.GetValueOrDefault()", "System.Int32 System.Int32?.GetValueOrDefault(System.Int32 defaultValue)" });
VerifyOperationTreeForNode(comp, model, declarators[1], expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Int32> ptr2) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr2 = &i.G ... ueOrDefault')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &i.GetValueOrDefault')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Int32>, IsInvalid, IsImplicit) (Syntax: '&i.GetValueOrDefault')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&i.GetValueOrDefault')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i.GetValueOrDefault')
Children(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32?, IsInvalid) (Syntax: 'i')
");
}
[Fact]
public void AddressOf_MultipleInvalidOverloads()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static int M(string s) => throw null;
static int M(ref int i) => throw null;
static void M1()
{
delegate*<int, int> ptr = &M;
}
}");
comp.VerifyDiagnostics(
// (9,35): error CS8757: No overload for 'M' matches function pointer 'delegate*<int, int>'
// delegate*<int, int> ptr = &M;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&M").WithArguments("M", "delegate*<int, int>").WithLocation(9, 35)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var declarator = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var addressOf = declarator.Initializer!.Value;
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.Int32, System.Int32>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "System.Int32 C.M(System.String s)", "System.Int32 C.M(ref System.Int32 i)" });
VerifyOperationTreeForNode(comp, model, declarator, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Int32, System.Int32> ptr) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr = &M')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Int32, System.Int32>, IsInvalid, IsImplicit) (Syntax: '&M')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
}
[Fact]
public void AddressOf_AmbiguousBestMethod()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M(string s, object o) {}
static void M(object o, string s) {}
static void M1()
{
delegate*<string, string, void> ptr = &M;
}
}");
comp.VerifyDiagnostics(
// (8,48): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(string, object)' and 'C.M(object, string)'
// delegate*<string, string, void> ptr = &M;
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(string, object)", "C.M(object, string)").WithLocation(8, 48)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var declarator = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var addressOf = declarator.Initializer!.Value;
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, addressOf,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "delegate*<System.String, System.String, System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M(System.String s, System.Object o)", "void C.M(System.Object o, System.String s)" });
VerifyOperationTreeForNode(comp, model, declarator, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.String, System.String, System.Void> ptr) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'ptr = &M')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= &M')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.String, System.String, System.Void>, IsInvalid, IsImplicit) (Syntax: '&M')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IAddressOfOperation (OperationKind.AddressOf, Type: null, IsInvalid) (Syntax: '&M')
Reference:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
");
}
[Fact]
public void AddressOf_AsLvalue()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M() {}
static void M1()
{
delegate*<void> ptr = &M;
&M = ptr;
M2(&M);
M2(ref &M);
ref delegate*<void> ptr2 = ref &M;
}
static void M2(ref delegate*<void> ptr) {}
}");
comp.VerifyDiagnostics(
// (8,9): error CS1656: Cannot assign to 'M' because it is a '&method group'
// &M = ptr;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(8, 9),
// (9,12): error CS1503: Argument 1: cannot convert from '&method group' to 'ref delegate*<void>'
// M2(&M);
Diagnostic(ErrorCode.ERR_BadArgType, "&M").WithArguments("1", "&method group", "ref delegate*<void>").WithLocation(9, 12),
// (10,16): error CS1657: Cannot use 'M' as a ref or out value because it is a '&method group'
// M2(ref &M);
Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(10, 16),
// (11,40): error CS1657: Cannot use 'M' as a ref or out value because it is a '&method group'
// ref delegate*<void> ptr2 = ref &M;
Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "&M").WithArguments("M", "&method group").WithLocation(11, 40)
);
}
[Fact]
public void AddressOf_MethodParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(string s) => Console.Write(s);
static void Caller(delegate*<string, void> ptr) => ptr(""1"");
static void Main()
{
Caller(&M);
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void C.M(string)""
IL_0006: call ""void C.Caller(delegate*<string, void>)""
IL_000b: ret
}
");
}
[Fact]
[WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
public void AddressOf_CannotAssignToVoidStar()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M()
{
void* ptr1 = &M;
void* ptr2 = (void*)&M;
}
}");
comp.VerifyDiagnostics(
// (6,22): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'void*'.
// void* ptr1 = &M;
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "void*").WithLocation(6, 22),
// (7,22): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'void*'.
// void* ptr2 = (void*)&M;
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "(void*)&M").WithArguments("M", "void*").WithLocation(7, 22)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[0].Initializer!.Value,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "System.Void*",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
[WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
public void AddressOf_ToDelegateType()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
class C
{
unsafe void M()
{
// This actually gets bound as a binary expression: (Action) & M
Action ptr1 = (Action)&M;
Action ptr2 = (Action)(&M);
Action ptr3 = &M;
}
}");
comp.VerifyDiagnostics(
// (8,24): error CS0119: 'Action' is a type, which is not valid in the given context
// Action ptr1 = (Action)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "Action").WithArguments("System.Action", "type").WithLocation(8, 24),
// (8,24): error CS0119: 'Action' is a type, which is not valid in the given context
// Action ptr1 = (Action)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "Action").WithArguments("System.Action", "type").WithLocation(8, 24),
// (9,23): error CS8811: Cannot convert &method group 'M' to delegate type 'M'.
// Action ptr2 = (Action)(&M);
Diagnostic(ErrorCode.ERR_CannotConvertAddressOfToDelegate, "(Action)(&M)").WithArguments("M", "System.Action").WithLocation(9, 23),
// (10,23): error CS8811: Cannot convert &method group 'M' to delegate type 'M'.
// Action ptr3 = &M;
Diagnostic(ErrorCode.ERR_CannotConvertAddressOfToDelegate, "&M").WithArguments("M", "System.Action").WithLocation(10, 23)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
expectedSyntax: "(&M)",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[2].Initializer!.Value,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "System.Action",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
[WorkItem(44489, "https://github.com/dotnet/roslyn/issues/44489")]
public void AddressOf_ToNonDelegateOrPointerType()
{
var comp = CreateCompilationWithFunctionPointers(@"
class C
{
unsafe void M()
{
// This actually gets bound as a binary expression: (C) & M
C ptr1 = (C)&M;
C ptr2 = (C)(&M);
C ptr3 = &M;
}
}");
comp.VerifyDiagnostics(
// (7,19): error CS0119: 'C' is a type, which is not valid in the given context
// C ptr1 = (C)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 19),
// (7,19): error CS0119: 'C' is a type, which is not valid in the given context
// C ptr1 = (C)&M;
Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 19),
// (8,18): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'C'.
// C ptr2 = (C)(&M);
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "(C)(&M)").WithArguments("M", "C").WithLocation(8, 18),
// (9,18): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'C'.
// C ptr3 = &M;
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "C").WithLocation(9, 18)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[1].Initializer!.Value).Expression,
expectedSyntax: "(&M)",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, decls[2].Initializer!.Value,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: "C",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
public void AddressOf_ExplicitCastToNonCompatibleFunctionPointerType()
{
var comp = CreateCompilationWithFunctionPointers(@"
class C
{
unsafe void M()
{
var ptr = (delegate*<string>)&M;
}
}
");
comp.VerifyDiagnostics(
// (6,19): error CS8757: No overload for 'M' matches function pointer 'delegate*<string>'
// var ptr = (delegate*<string>)&M;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<string>)&M").WithArguments("M", "delegate*<string>").WithLocation(6, 19)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var decls = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray();
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, ((CastExpressionSyntax)decls[0].Initializer!.Value).Expression,
expectedSyntax: "&M",
expectedType: null,
expectedConvertedType: null,
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M()" });
}
[Fact]
public void AddressOf_DisallowedInExpressionTree()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
using System.Linq.Expressions;
unsafe class C
{
static string M1(delegate*<string> ptr) => ptr();
static string M2() => string.Empty;
static void M()
{
Expression<Func<string>> a = () => M1(&M2);
Expression<Func<string>> b = () => (&M2)();
}
}");
comp.VerifyDiagnostics(
// (11,47): error CS1944: An expression tree may not contain an unsafe pointer operation
// Expression<Func<string>> a = () => M1(&M2);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&M2").WithLocation(11, 47),
// (11,48): error CS8810: '&' on method groups cannot be used in expression trees
// Expression<Func<string>> a = () => M1(&M2);
Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "M2").WithLocation(11, 48),
// (12,44): error CS0149: Method name expected
// Expression<Func<string>> b = () => (&M2)();
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(&M2)").WithLocation(12, 44)
);
}
[Fact]
public void FunctionPointerTypeUsageInExpressionTree()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
using System.Linq.Expressions;
unsafe class C
{
void M1(delegate*<void> ptr)
{
Expression<Action> a = () => M2(ptr);
}
void M2(void* ptr) {}
}
");
comp.VerifyDiagnostics(
// (8,41): error CS1944: An expression tree may not contain an unsafe pointer operation
// Expression<Action> a = () => M2(ptr);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "ptr").WithLocation(8, 41)
);
}
[Fact]
public void AmbiguousApplicableMethodsAreFilteredForStatic()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
interface I1{}
interface I2
{
string Prop { get; }
}
public unsafe class C : I1, I2 {
void M(I1 i) {}
static void M(I2 i) => Console.Write(i.Prop);
public static void Main() {
delegate*<C, void> a = &M;
a(new C());
}
public string Prop { get => ""I2""; }
}", expectedOutput: "I2");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (delegate*<C, void> V_0)
IL_0000: ldftn ""void C.M(I2)""
IL_0006: stloc.0
IL_0007: newobj ""C..ctor()""
IL_000c: ldloc.0
IL_000d: calli ""delegate*<C, void>""
IL_0012: ret
}
");
}
[Fact]
public void TypeArgumentNotSpecifiedNotInferred()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M1<T>(int i) {}
static T M2<T>() => throw null;
static void M()
{
delegate*<int, void> ptr1 = &C.M1;
delegate*<string> ptr2 = &C.M2;
}
}");
comp.VerifyDiagnostics(
// (9,38): error CS0411: The type arguments for method 'C.M1<T>(int)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// delegate*<int, void> ptr1 = &C.M1;
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "C.M1").WithArguments("C.M1<T>(int)").WithLocation(9, 38),
// (10,35): error CS0411: The type arguments for method 'C.M2<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// delegate*<string> ptr2 = &C.M2;
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "C.M2").WithArguments("C.M2<T>()").WithLocation(10, 35)
);
}
[Fact]
public void TypeArgumentSpecifiedOrInferred()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M1<T>(T t) => Console.Write(t);
static void Main()
{
delegate*<int, void> ptr = &C.M1<int>;
ptr(1);
ptr = &C.M1;
ptr(2);
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<int, void> V_0)
IL_0000: ldftn ""void C.M1<int>(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: ldloc.0
IL_0009: calli ""delegate*<int, void>""
IL_000e: ldftn ""void C.M1<int>(int)""
IL_0014: stloc.0
IL_0015: ldc.i4.2
IL_0016: ldloc.0
IL_0017: calli ""delegate*<int, void>""
IL_001c: ret
}
");
}
[Fact]
public void ReducedExtensionMethod()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe static class CHelper
{
public static void M1(this C c) {}
}
unsafe class C
{
static void M(C c)
{
delegate*<C, void> ptr1 = &c.M1;
delegate*<void> ptr2 = &c.M1;
}
}");
comp.VerifyDiagnostics(
// (10,35): error CS8757: No overload for 'M1' matches function pointer 'delegate*<C, void>'
// delegate*<C, void> ptr1 = &c.M1;
Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "&c.M1").WithArguments("M1", "delegate*<C, void>").WithLocation(10, 35),
// (11,32): error CS8788: Cannot use an extension method with a receiver as the target of a '&' operator.
// delegate*<void> ptr2 = &c.M1;
Diagnostic(ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, "&c.M1").WithLocation(11, 32)
);
}
[Fact]
public void UnreducedExtensionMethod()
{
var verifier = CompileAndVerifyFunctionPointers(@"
#pragma warning suppress CS0414 // Field never used
using System;
unsafe static class CHelper
{
public static void M1(this C c) => Console.Write(c.i);
}
unsafe class C
{
public int i;
static void Main()
{
delegate*<C, void> ptr = &CHelper.M1;
var c = new C();
c.i = 1;
ptr(c);
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (C V_0, //c
delegate*<C, void> V_1)
IL_0000: ldftn ""void CHelper.M1(C)""
IL_0006: newobj ""C..ctor()""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: stfld ""int C.i""
IL_0013: stloc.1
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: calli ""delegate*<C, void>""
IL_001b: ret
}
");
}
[Fact]
public void BadScenariosDontCrash()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M1() {}
static void M2()
{
&delegate*<void> ptr = &M1;
}
}
");
comp.VerifyDiagnostics(
// (7,18): error CS1514: { expected
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_LbraceExpected, "*").WithLocation(7, 18),
// (7,19): error CS1525: Invalid expression term '<'
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(7, 19),
// (7,20): error CS1525: Invalid expression term 'void'
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "void").WithArguments("void").WithLocation(7, 20),
// (7,26): error CS0103: The name 'ptr' does not exist in the current context
// &delegate*<void> ptr = &M1;
Diagnostic(ErrorCode.ERR_NameNotInContext, "ptr").WithArguments("ptr").WithLocation(7, 26)
);
}
[Fact]
public void EmptyMethodGroups()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
static void M1()
{
delegate*<C, void> ptr1 = &C.NonExistent;
delegate*<C, void> ptr2 = &NonExistent;
}
}
");
comp.VerifyDiagnostics(
// (6,38): error CS0117: 'C' does not contain a definition for 'NonExistent'
// delegate*<C, void> ptr1 = &C.NonExistent;
Diagnostic(ErrorCode.ERR_NoSuchMember, "NonExistent").WithArguments("C", "NonExistent").WithLocation(6, 38),
// (7,36): error CS0103: The name 'NonExistent' does not exist in the current context
// delegate*<C, void> ptr2 = &NonExistent;
Diagnostic(ErrorCode.ERR_NameNotInContext, "NonExistent").WithArguments("NonExistent").WithLocation(7, 36)
);
}
[Fact]
public void MultipleApplicableMethods()
{
// This is analogous to MethodBodyModelTests.MethodGroupToDelegate04, where both methods
// are applicable even though D(delegate*<int, void>) is not compatible.
var comp = CreateCompilationWithFunctionPointers(@"
public unsafe class Program1
{
static void Y(long x) { }
static void D(delegate*<int, void> o) { }
static void D(delegate*<long, void> o) { }
void T()
{
D(&Y);
}
}
");
comp.VerifyDiagnostics(
// (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program1.D(delegate*<int, void>)' and 'Program1.D(delegate*<long, void>)'
// D(&Y);
Diagnostic(ErrorCode.ERR_AmbigCall, "D").WithArguments("Program1.D(delegate*<int, void>)", "Program1.D(delegate*<long, void>)").WithLocation(11, 9)
);
}
[Fact]
public void InvalidTopAttributeErrors()
{
using var peStream = new MemoryStream();
var ilBuilder = new BlobBuilder();
var metadataBuilder = new MetadataBuilder();
// SignatureAttributes has the following values:
// 0x00 - default
// 0x10 - Generic
// 0x20 - Instance
// 0x40 - ExplicitThis
// There is no defined meaning for 0x80, the 8th bit here, so this signature is invalid.
// ldftn throws an invalid signature exception at runtime, so we error here for function
// pointers.
DefineInvalidSignatureAttributeIL(metadataBuilder, ilBuilder, headerToUseForM: new SignatureHeader(SignatureKind.Method, SignatureCallingConvention.Default, ((SignatureAttributes)0x80)));
WritePEImage(peStream, metadataBuilder, ilBuilder);
peStream.Position = 0;
var invalidAttributeReference = MetadataReference.CreateFromStream(peStream);
var comp = CreateCompilationWithFunctionPointers(@"
using ConsoleApplication;
unsafe class C
{
static void Main()
{
delegate*<void> ptr = &Program.M;
}
}", references: new[] { invalidAttributeReference });
comp.VerifyEmitDiagnostics(
// (7,32): error CS8776: Calling convention of 'Program.M()' is not compatible with 'Default'.
// delegate*<void> ptr = &Program.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "Program.M").WithArguments("ConsoleApplication.Program.M()", "Default").WithLocation(7, 32)
);
}
[Fact]
public void MissingAddressOf()
{
var comp = CreateCompilationWithFunctionPointers(@"
class C
{
static void M1() {}
static unsafe void M2(delegate*<void> b)
{
delegate*<void> a = M1;
M2(M1);
}
}");
comp.VerifyDiagnostics(
// (7,29): error CS8787: Cannot convert method group to function pointer (Are you missing a '&'?)
// delegate*<void> a = M1;
Diagnostic(ErrorCode.ERR_MissingAddressOf, "M1").WithLocation(7, 29),
// (8,12): error CS8787: Cannot convert method group to function pointer (Are you missing a '&'?)
// M2(M1);
Diagnostic(ErrorCode.ERR_MissingAddressOf, "M1").WithLocation(8, 12)
);
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
var variableDeclaratorSyntax = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single();
var methodGroup1 = variableDeclaratorSyntax.Initializer!.Value;
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model, methodGroup1,
expectedSyntax: "M1",
expectedType: null,
expectedConvertedType: "delegate*<System.Void>",
expectedCandidateReason: CandidateReason.OverloadResolutionFailure,
expectedSymbolCandidates: new[] { "void C.M1()" });
AssertEx.Equal(new[] { "void C.M1()" }, model.GetMemberGroup(methodGroup1).Select(m => m.ToTestDisplayString(includeNonNullable: false)));
VerifyOperationTreeForNode(comp, model, variableDeclaratorSyntax, expectedOperationTree: @"
IVariableDeclaratorOperation (Symbol: delegate*<System.Void> a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: delegate*<System.Void>, IsInvalid, IsImplicit) (Syntax: 'M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M1')
");
}
[Fact]
public void NestedFunctionPointerVariantConversion()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void Printer(object o) => Console.Write(o);
public static void PrintWrapper(delegate*<string, void> printer, string o) => printer(o);
static void Main()
{
delegate*<delegate*<object, void>, string, void> wrapper = &PrintWrapper;
delegate*<object, void> printer = &Printer;
wrapper(printer, ""1"");
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main()", expectedIL: @"
{
// Code size 27 (0x1b)
.maxstack 3
.locals init (delegate*<object, void> V_0, //printer
delegate*<delegate*<object, void>, string, void> V_1)
IL_0000: ldftn ""void C.PrintWrapper(delegate*<string, void>, string)""
IL_0006: ldftn ""void C.Printer(object)""
IL_000c: stloc.0
IL_000d: stloc.1
IL_000e: ldloc.0
IL_000f: ldstr ""1""
IL_0014: ldloc.1
IL_0015: calli ""delegate*<delegate*<object, void>, string, void>""
IL_001a: ret
}
");
}
[Fact]
public void ArraysSupport()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void M(string s) => Console.Write(s);
public static void Main()
{
delegate*<string, void>[] ptrs = new delegate*<string, void>[] { &M, &M };
for (int i = 0; i < ptrs.Length; i++)
{
ptrs[i](i.ToString());
}
}
}", expectedOutput: "01");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (delegate*<string, void>[] V_0, //ptrs
int V_1, //i
delegate*<string, void> V_2)
IL_0000: ldc.i4.2
IL_0001: newarr ""delegate*<string, void>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldftn ""void C.M(string)""
IL_000e: stelem.i
IL_000f: dup
IL_0010: ldc.i4.1
IL_0011: ldftn ""void C.M(string)""
IL_0017: stelem.i
IL_0018: stloc.0
IL_0019: ldc.i4.0
IL_001a: stloc.1
IL_001b: br.s IL_0032
IL_001d: ldloc.0
IL_001e: ldloc.1
IL_001f: ldelem.i
IL_0020: stloc.2
IL_0021: ldloca.s V_1
IL_0023: call ""string int.ToString()""
IL_0028: ldloc.2
IL_0029: calli ""delegate*<string, void>""
IL_002e: ldloc.1
IL_002f: ldc.i4.1
IL_0030: add
IL_0031: stloc.1
IL_0032: ldloc.1
IL_0033: ldloc.0
IL_0034: ldlen
IL_0035: conv.i4
IL_0036: blt.s IL_001d
IL_0038: ret
}
");
}
[Fact]
public void ArrayElementRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void Print() => Console.Write(1);
public static void M(delegate*<void>[] a)
{
ref delegate*<void> ptr = ref a[0];
ptr = &Print;
}
public static void Main()
{
var a = new delegate*<void>[1];
M(a);
a[0]();
}
}");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelema ""delegate*<void>""
IL_0007: ldftn ""void C.Print()""
IL_000d: stind.i
IL_000e: ret
}
");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: newarr ""delegate*<void>""
IL_0006: dup
IL_0007: call ""void C.M(delegate*<void>[])""
IL_000c: ldc.i4.0
IL_000d: ldelem.i
IL_000e: calli ""delegate*<void>""
IL_0013: ret
}
");
}
[Fact]
public void FixedSizeBufferOfFunctionPointers()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe struct S
{
fixed delegate*<void> ptrs[1];
}");
comp.VerifyDiagnostics(
// (4,11): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double
// fixed delegate*<void> ptrs[1];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "delegate*<void>").WithLocation(4, 11)
);
}
[Fact]
public void IndirectLoadsAndStores()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static delegate*<void> field;
static void Printer() => Console.Write(1);
static ref delegate*<void> Getter() => ref field;
static void Main()
{
ref var printer = ref Getter();
printer = &Printer;
printer();
field();
}
}", expectedOutput: "11");
verifier.VerifyIL(@"C.Main", expectedIL: @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: call ""ref delegate*<void> C.Getter()""
IL_0005: dup
IL_0006: ldftn ""void C.Printer()""
IL_000c: stind.i
IL_000d: ldind.i
IL_000e: calli ""delegate*<void>""
IL_0013: ldsfld ""delegate*<void> C.field""
IL_0018: calli ""delegate*<void>""
IL_001d: ret
}
");
}
[Fact]
public void Foreach()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
public static void M(string s) => Console.Write(s);
public static void Main()
{
delegate*<string, void>[] ptrs = new delegate*<string, void>[] { &M, &M };
int i = 0;
foreach (delegate*<string, void> ptr in ptrs)
{
ptr(i++.ToString());
}
}
}", expectedOutput: "01");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 66 (0x42)
.maxstack 4
.locals init (int V_0, //i
delegate*<string, void>[] V_1,
int V_2,
delegate*<string, void> V_3,
int V_4)
IL_0000: ldc.i4.2
IL_0001: newarr ""delegate*<string, void>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldftn ""void C.M(string)""
IL_000e: stelem.i
IL_000f: dup
IL_0010: ldc.i4.1
IL_0011: ldftn ""void C.M(string)""
IL_0017: stelem.i
IL_0018: ldc.i4.0
IL_0019: stloc.0
IL_001a: stloc.1
IL_001b: ldc.i4.0
IL_001c: stloc.2
IL_001d: br.s IL_003b
IL_001f: ldloc.1
IL_0020: ldloc.2
IL_0021: ldelem.i
IL_0022: stloc.3
IL_0023: ldloc.0
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: add
IL_0027: stloc.0
IL_0028: stloc.s V_4
IL_002a: ldloca.s V_4
IL_002c: call ""string int.ToString()""
IL_0031: ldloc.3
IL_0032: calli ""delegate*<string, void>""
IL_0037: ldloc.2
IL_0038: ldc.i4.1
IL_0039: add
IL_003a: stloc.2
IL_003b: ldloc.2
IL_003c: ldloc.1
IL_003d: ldlen
IL_003e: conv.i4
IL_003f: blt.s IL_001f
IL_0041: ret
}
");
}
[Fact]
public void FieldInitializers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
delegate*<string, void>[] arr1;
delegate*<string, void>[] arr2 = new delegate*<string, void>[1];
static void Print(string s) => Console.Write(s);
static void Main()
{
var c = new C()
{
arr1 = new delegate*<string, void>[] { &Print },
arr2 = { [0] = &Print }
};
c.arr1[0](""1"");
c.arr2[0](""2"");
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 82 (0x52)
.maxstack 5
.locals init (C V_0,
delegate*<string, void> V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: newarr ""delegate*<string, void>""
IL_000d: dup
IL_000e: ldc.i4.0
IL_000f: ldftn ""void C.Print(string)""
IL_0015: stelem.i
IL_0016: stfld ""delegate*<string, void>[] C.arr1""
IL_001b: ldloc.0
IL_001c: ldfld ""delegate*<string, void>[] C.arr2""
IL_0021: ldc.i4.0
IL_0022: ldftn ""void C.Print(string)""
IL_0028: stelem.i
IL_0029: ldloc.0
IL_002a: dup
IL_002b: ldfld ""delegate*<string, void>[] C.arr1""
IL_0030: ldc.i4.0
IL_0031: ldelem.i
IL_0032: stloc.1
IL_0033: ldstr ""1""
IL_0038: ldloc.1
IL_0039: calli ""delegate*<string, void>""
IL_003e: ldfld ""delegate*<string, void>[] C.arr2""
IL_0043: ldc.i4.0
IL_0044: ldelem.i
IL_0045: stloc.1
IL_0046: ldstr ""2""
IL_004b: ldloc.1
IL_004c: calli ""delegate*<string, void>""
IL_0051: ret
}
");
}
[Fact]
public void InitializeFunctionPointerWithNull()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Main()
{
delegate*<string, void>[] ptrs = new delegate*<string, void>[] { null, null, null };
Console.Write(ptrs[0] is null);
}
}", expectedOutput: "True");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 33 (0x21)
.maxstack 4
IL_0000: ldc.i4.3
IL_0001: newarr ""delegate*<string, void>""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: stelem.i
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.0
IL_000e: conv.u
IL_000f: stelem.i
IL_0010: dup
IL_0011: ldc.i4.2
IL_0012: ldc.i4.0
IL_0013: conv.u
IL_0014: stelem.i
IL_0015: ldc.i4.0
IL_0016: ldelem.i
IL_0017: ldc.i4.0
IL_0018: conv.u
IL_0019: ceq
IL_001b: call ""void System.Console.Write(bool)""
IL_0020: ret
}
");
}
[Fact]
public void InferredArrayInitializer_ParameterVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(object o) => Console.Write(o);
static void Print(string s) => Console.Write(s);
static void Main()
{
delegate*<string, void> ptr1 = &Print;
delegate*<object, void> ptr2 = &Print;
var ptrs = new[] { ptr1, ptr2 };
ptrs[0](""1"");
ptrs[1](""2"");
}
}", expectedOutput: "12");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 58 (0x3a)
.maxstack 4
.locals init (delegate*<string, void> V_0, //ptr1
delegate*<object, void> V_1, //ptr2
delegate*<string, void> V_2)
IL_0000: ldftn ""void C.Print(string)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.Print(object)""
IL_000d: stloc.1
IL_000e: ldc.i4.2
IL_000f: newarr ""delegate*<string, void>""
IL_0014: dup
IL_0015: ldc.i4.0
IL_0016: ldloc.0
IL_0017: stelem.i
IL_0018: dup
IL_0019: ldc.i4.1
IL_001a: ldloc.1
IL_001b: stelem.i
IL_001c: dup
IL_001d: ldc.i4.0
IL_001e: ldelem.i
IL_001f: stloc.2
IL_0020: ldstr ""1""
IL_0025: ldloc.2
IL_0026: calli ""delegate*<string, void>""
IL_002b: ldc.i4.1
IL_002c: ldelem.i
IL_002d: stloc.2
IL_002e: ldstr ""2""
IL_0033: ldloc.2
IL_0034: calli ""delegate*<string, void>""
IL_0039: ret
}
");
}
[Fact]
public void InferredArrayInitializer_ReturnVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object GetObject() => 1.ToString();
static string GetString() => 2.ToString();
static void Print(delegate*<object>[] ptrs)
{
Console.Write(""Object"");
foreach (var ptr in ptrs)
{
Console.Write(ptr());
}
}
static void Print(delegate*<string>[] ptrs)
{
Console.Write(""String"");
foreach (var ptr in ptrs)
{
Console.Write(ptr());
}
}
static void Main()
{
delegate*<object> ptr1 = &GetObject;
delegate*<string> ptr2 = &GetString;
Print(new[] { ptr1, ptr2 });
}
}", expectedOutput: "Object12");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 34 (0x22)
.maxstack 4
.locals init (delegate*<object> V_0, //ptr1
delegate*<string> V_1) //ptr2
IL_0000: ldftn ""object C.GetObject()""
IL_0006: stloc.0
IL_0007: ldftn ""string C.GetString()""
IL_000d: stloc.1
IL_000e: ldc.i4.2
IL_000f: newarr ""delegate*<object>""
IL_0014: dup
IL_0015: ldc.i4.0
IL_0016: ldloc.0
IL_0017: stelem.i
IL_0018: dup
IL_0019: ldc.i4.1
IL_001a: ldloc.1
IL_001b: stelem.i
IL_001c: call ""void C.Print(delegate*<object>[])""
IL_0021: ret
}
");
}
[Fact]
public void BestTypeForConditional_ParameterVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(object o) => Console.Write(o + ""Object"");
static void Print(string s) => Console.Write(s + ""String"");
static void M(bool b)
{
delegate*<object, void> ptr1 = &Print;
delegate*<string, void> ptr2 = &Print;
var ptr3 = b ? ptr1 : ptr2;
ptr3(""1"");
ptr3 = b ? ptr2 : ptr1;
ptr3(""2"");
}
static void Main() => M(true);
}", expectedOutput: "1Object2String");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 53 (0x35)
.maxstack 2
.locals init (delegate*<object, void> V_0, //ptr1
delegate*<string, void> V_1, //ptr2
delegate*<string, void> V_2)
IL_0000: ldftn ""void C.Print(object)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.Print(string)""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.1
IL_0012: br.s IL_0015
IL_0014: ldloc.0
IL_0015: stloc.2
IL_0016: ldstr ""1""
IL_001b: ldloc.2
IL_001c: calli ""delegate*<string, void>""
IL_0021: ldarg.0
IL_0022: brtrue.s IL_0027
IL_0024: ldloc.0
IL_0025: br.s IL_0028
IL_0027: ldloc.1
IL_0028: stloc.2
IL_0029: ldstr ""2""
IL_002e: ldloc.2
IL_002f: calli ""delegate*<string, void>""
IL_0034: ret
}
");
}
[Fact]
public void BestTypeForConditional_ReturnVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object GetObject() => 1.ToString();
static string GetString() => 2.ToString();
static void Print(delegate*<object> ptr)
{
Console.Write(ptr());
Console.Write(""Object"");
}
static void Print(delegate*<string> ptr)
{
Console.Write(ptr());
Console.Write(""String"");
}
static void M(bool b)
{
delegate*<object> ptr1 = &GetObject;
delegate*<string> ptr2 = &GetString;
Print(b ? ptr1 : ptr2);
Print(b ? ptr2 : ptr1);
}
static void Main() => M(true);
}", expectedOutput: "1Object2Object");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init (delegate*<object> V_0, //ptr1
delegate*<string> V_1) //ptr2
IL_0000: ldftn ""object C.GetObject()""
IL_0006: stloc.0
IL_0007: ldftn ""string C.GetString()""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.1
IL_0012: br.s IL_0015
IL_0014: ldloc.0
IL_0015: call ""void C.Print(delegate*<object>)""
IL_001a: ldarg.0
IL_001b: brtrue.s IL_0020
IL_001d: ldloc.0
IL_001e: br.s IL_0021
IL_0020: ldloc.1
IL_0021: call ""void C.Print(delegate*<object>)""
IL_0026: ret
}
");
}
[Fact]
public void BestTypeForConditional_NestedParameterVariance()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(object o)
{
Console.Write(o);
}
static void PrintObject(delegate*<object, void> ptr, string o)
{
ptr(o);
}
static void PrintString(delegate*<string, void> ptr, string s)
{
ptr(s);
}
static void Invoke(delegate*<delegate*<object, void>, string, void> ptr, string s)
{
Console.Write(""Object"");
delegate*<object, void> print = &Print;
ptr(print, s);
}
static void Invoke(delegate*<delegate*<string, void>, string, void> ptr, string s)
{
Console.Write(""String"");
delegate*<string, void> print = &Print;
ptr(print, s);
}
static void M(bool b)
{
delegate*<delegate*<object, void>, string, void> printObject = &PrintObject;
delegate*<delegate*<string, void>, string, void> printString = &PrintString;
Invoke(b ? printObject : printString, ""1"");
}
static void Main() => M(true);
}", expectedOutput: "Object1");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (delegate*<delegate*<object, void>, string, void> V_0, //printObject
delegate*<delegate*<string, void>, string, void> V_1) //printString
IL_0000: ldftn ""void C.PrintObject(delegate*<object, void>, string)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.PrintString(delegate*<string, void>, string)""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0014
IL_0011: ldloc.1
IL_0012: br.s IL_0015
IL_0014: ldloc.0
IL_0015: ldstr ""1""
IL_001a: call ""void C.Invoke(delegate*<delegate*<object, void>, string, void>, string)""
IL_001f: ret
}
");
}
[Fact]
public void BestTypeForConditional_NestedParameterRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Print(ref object o1, object o2)
{
o1 = o2;
}
static void PrintObject(delegate*<ref object, object, void> ptr, ref object o, object arg)
{
ptr(ref o, arg);
}
static void PrintString(delegate*<ref object, string, void> ptr, ref object o, string arg)
{
ptr(ref o, arg);
}
static void Invoke(delegate*<delegate*<ref object, object, void>, ref object, string, void> ptr, ref object s, object arg)
{
Console.Write(""Object"");
delegate*<ref object, object, void> print = &Print;
ptr(print, ref s, arg.ToString());
}
static void Invoke(delegate*<delegate*<ref object, string, void>, ref object, string, void> ptr, ref object s, string arg)
{
Console.Write(""String"");
delegate*<ref object, string, void> print = &Print;
ptr(print, ref s, arg);
}
static void M(bool b)
{
delegate*<delegate*<ref object, object, void>, ref object, string, void> printObject1 = &PrintObject;
delegate*<delegate*<ref object, string, void>, ref object, string, void> printObject2 = &PrintString;
object o = null;
Invoke(b ? printObject1 : printObject2, ref o, ""1"");
Console.Write(o);
}
static void Main() => M(true);
}", expectedOutput: "Object1");
verifier.VerifyIL("C.M", expectedIL: @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (delegate*<delegate*<ref object, object, void>, ref object, string, void> V_0, //printObject1
delegate*<delegate*<ref object, string, void>, ref object, string, void> V_1, //printObject2
object V_2) //o
IL_0000: ldftn ""void C.PrintObject(delegate*<ref object, object, void>, ref object, object)""
IL_0006: stloc.0
IL_0007: ldftn ""void C.PrintString(delegate*<ref object, string, void>, ref object, string)""
IL_000d: stloc.1
IL_000e: ldnull
IL_000f: stloc.2
IL_0010: ldarg.0
IL_0011: brtrue.s IL_0016
IL_0013: ldloc.1
IL_0014: br.s IL_0017
IL_0016: ldloc.0
IL_0017: ldloca.s V_2
IL_0019: ldstr ""1""
IL_001e: call ""void C.Invoke(delegate*<delegate*<ref object, object, void>, ref object, string, void>, ref object, object)""
IL_0023: ldloc.2
IL_0024: call ""void System.Console.Write(object)""
IL_0029: ret
}
");
}
[Fact]
public void DefaultOfFunctionPointerType()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void Main()
{
delegate*<void> ptr = default;
Console.Write(ptr is null);
}
}", expectedOutput: "True");
verifier.VerifyIL("C.Main", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: ldc.i4.0
IL_0003: conv.u
IL_0004: ceq
IL_0006: call ""void System.Console.Write(bool)""
IL_000b: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var syntaxTree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(syntaxTree);
FunctionPointerUtilities.VerifyFunctionPointerSemanticInfo(model,
syntaxTree.GetRoot()
.DescendantNodes()
.OfType<LiteralExpressionSyntax>()
.Where(l => l.IsKind(SyntaxKind.DefaultLiteralExpression))
.Single(),
expectedSyntax: "default",
expectedType: "delegate*<System.Void>",
expectedSymbol: null,
expectedSymbolCandidates: null);
}
[Fact]
public void ParamsArrayOfFunctionPointers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
static void Params(params delegate*<void>[] funcs)
{
foreach (var f in funcs)
{
f();
}
}
static void Main()
{
Params();
}
}", expectedOutput: "");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: newarr ""delegate*<void>""
IL_0006: call ""void C.Params(params delegate*<void>[])""
IL_000b: ret
}
");
}
[Fact]
public void StackallocOfFunctionPointers()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
static unsafe class C
{
static int Getter(int i) => i;
static void Print(delegate*<int, int>* p)
{
for (int i = 0; i < 3; i++)
Console.Write(p[i](i));
}
static void Main()
{
delegate*<int, int>* p = stackalloc delegate*<int, int>[] { &Getter, &Getter, &Getter };
Print(p);
}
}
", expectedOutput: "012");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 58 (0x3a)
.maxstack 4
IL_0000: ldc.i4.3
IL_0001: conv.u
IL_0002: sizeof ""delegate*<int, int>""
IL_0008: mul.ovf.un
IL_0009: localloc
IL_000b: dup
IL_000c: ldftn ""int C.Getter(int)""
IL_0012: stind.i
IL_0013: dup
IL_0014: sizeof ""delegate*<int, int>""
IL_001a: add
IL_001b: ldftn ""int C.Getter(int)""
IL_0021: stind.i
IL_0022: dup
IL_0023: ldc.i4.2
IL_0024: conv.i
IL_0025: sizeof ""delegate*<int, int>""
IL_002b: mul
IL_002c: add
IL_002d: ldftn ""int C.Getter(int)""
IL_0033: stind.i
IL_0034: call ""void C.Print(delegate*<int, int>*)""
IL_0039: ret
}
");
}
[Fact]
public void FunctionPointerCannotBeUsedAsSpanArgument()
{
var comp = CreateCompilationWithSpan(@"
using System;
static unsafe class C
{
static void Main()
{
Span<delegate*<int, int>> p = stackalloc delegate*<int, int>[1];
}
}
", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,14): error CS0306: The type 'delegate*<int, int>' may not be used as a type argument
// Span<delegate*<int, int>> p = stackalloc delegate*<int, int>[1];
Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, int>").WithArguments("delegate*<int, int>").WithLocation(7, 14)
);
}
[Fact]
public void RecursivelyUsedTypeInFunctionPointer()
{
var verifier = CompileAndVerifyFunctionPointers(@"
namespace Interop
{
public unsafe struct PROPVARIANT
{
public CAPROPVARIANT ca;
}
public unsafe struct CAPROPVARIANT
{
public uint cElems;
public delegate*<PROPVARIANT> pElems;
public delegate*<PROPVARIANT> pElemsProp { get; }
}
}");
}
[Fact]
public void VolatileFunctionPointerField()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static volatile delegate*<void> ptr;
static void Print() => Console.Write(1);
static void Main()
{
ptr = &Print;
ptr();
}
}", expectedOutput: "1");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: ldftn ""void C.Print()""
IL_0006: volatile.
IL_0008: stsfld ""delegate*<void> C.ptr""
IL_000d: volatile.
IL_000f: ldsfld ""delegate*<void> C.ptr""
IL_0014: calli ""delegate*<void>""
IL_0019: ret
}
");
}
[Fact]
public void SupportedBinaryOperators()
{
var verifier = CompileAndVerifyFunctionPointers(@"
#pragma warning disable CS8909 // Function pointers should not be compared
using System;
unsafe class C
{
static (bool, bool, bool, bool, bool, bool) DoCompare(delegate*<void> func_1a, delegate*<string, void> func_1b)
{
return (func_1a == func_1b,
func_1a != func_1b,
func_1a > func_1b,
func_1a >= func_1b,
func_1a < func_1b,
func_1a <= func_1b);
}
static void M(delegate*<void> func_1a, delegate*<string, void> func_1b, delegate*<int> func_2, int* int_1, int* int_2)
{
var compareResults = DoCompare(func_1a, func_1b);
Console.WriteLine(""func_1a == func_1b: "" + compareResults.Item1);
Console.WriteLine(""func_1a != func_1b: "" + compareResults.Item2);
Console.WriteLine(""func_1a > func_1b: "" + compareResults.Item3);
Console.WriteLine(""func_1a >= func_1b: "" + compareResults.Item4);
Console.WriteLine(""func_1a < func_1b: "" + compareResults.Item5);
Console.WriteLine(""func_1a <= func_1b: "" + compareResults.Item6);
Console.WriteLine(""func_1a == func_2: "" + (func_1a == func_2));
Console.WriteLine(""func_1a != func_2: "" + (func_1a != func_2));
Console.WriteLine(""func_1a > func_2: "" + (func_1a > func_2));
Console.WriteLine(""func_1a >= func_2: "" + (func_1a >= func_2));
Console.WriteLine(""func_1a < func_2: "" + (func_1a < func_2));
Console.WriteLine(""func_1a <= func_2: "" + (func_1a <= func_2));
Console.WriteLine(""func_1a == int_1: "" + (func_1a == int_1));
Console.WriteLine(""func_1a != int_1: "" + (func_1a != int_1));
Console.WriteLine(""func_1a > int_1: "" + (func_1a > int_1));
Console.WriteLine(""func_1a >= int_1: "" + (func_1a >= int_1));
Console.WriteLine(""func_1a < int_1: "" + (func_1a < int_1));
Console.WriteLine(""func_1a <= int_1: "" + (func_1a <= int_1));
Console.WriteLine(""func_1a == int_2: "" + (func_1a == int_2));
Console.WriteLine(""func_1a != int_2: "" + (func_1a != int_2));
Console.WriteLine(""func_1a > int_2: "" + (func_1a > int_2));
Console.WriteLine(""func_1a >= int_2: "" + (func_1a >= int_2));
Console.WriteLine(""func_1a < int_2: "" + (func_1a < int_2));
Console.WriteLine(""func_1a <= int_2: "" + (func_1a <= int_2));
}
static void Main()
{
delegate*<void> func_1a = (delegate*<void>)1;
delegate*<string, void> func_1b = (delegate*<string, void>)1;
delegate*<int> func_2 = (delegate*<int>)2;
int* int_1 = (int*)1;
int* int_2 = (int*)2;
M(func_1a, func_1b, func_2, int_1, int_2);
}
}", expectedOutput: @"
func_1a == func_1b: True
func_1a != func_1b: False
func_1a > func_1b: False
func_1a >= func_1b: True
func_1a < func_1b: False
func_1a <= func_1b: True
func_1a == func_2: False
func_1a != func_2: True
func_1a > func_2: False
func_1a >= func_2: False
func_1a < func_2: True
func_1a <= func_2: True
func_1a == int_1: True
func_1a != int_1: False
func_1a > int_1: False
func_1a >= int_1: True
func_1a < int_1: False
func_1a <= int_1: True
func_1a == int_2: False
func_1a != int_2: True
func_1a > int_2: False
func_1a >= int_2: False
func_1a < int_2: True
func_1a <= int_2: True");
verifier.VerifyIL("C.DoCompare", expectedIL: @"
{
// Code size 39 (0x27)
.maxstack 7
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ceq
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: ceq
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: ldarg.0
IL_000c: ldarg.1
IL_000d: cgt.un
IL_000f: ldarg.0
IL_0010: ldarg.1
IL_0011: clt.un
IL_0013: ldc.i4.0
IL_0014: ceq
IL_0016: ldarg.0
IL_0017: ldarg.1
IL_0018: clt.un
IL_001a: ldarg.0
IL_001b: ldarg.1
IL_001c: cgt.un
IL_001e: ldc.i4.0
IL_001f: ceq
IL_0021: newobj ""System.ValueTuple<bool, bool, bool, bool, bool, bool>..ctor(bool, bool, bool, bool, bool, bool)""
IL_0026: ret
}
");
}
[Theory, WorkItem(48919, "https://github.com/dotnet/roslyn/issues/48919")]
[InlineData("==")]
[InlineData("!=")]
[InlineData(">=")]
[InlineData(">")]
[InlineData("<=")]
[InlineData("<")]
public void BinaryComparisonWarnings(string @operator)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe
{{
delegate*<void> a = null, b = null;
_ = a {@operator} b;
}}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (5,9): error CS8909: Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct.
// _ = a {@operator} b;
Diagnostic(ErrorCode.WRN_DoNotCompareFunctionPointers, @operator).WithLocation(5, 11)
);
}
[Theory, WorkItem(48919, "https://github.com/dotnet/roslyn/issues/48919")]
[InlineData("==")]
[InlineData("!=")]
[InlineData(">=")]
[InlineData(">")]
[InlineData("<=")]
[InlineData("<")]
public void BinaryComparisonCastToVoidStar_NoWarning(string @operator)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe
{{
delegate*<void> a = null, b = null;
_ = (void*)a {@operator} b;
_ = a {@operator} (void*)b;
}}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData("+")]
[InlineData("-")]
[InlineData("*")]
[InlineData("/")]
[InlineData("%")]
[InlineData("<<")]
[InlineData(">>")]
[InlineData("&&")]
[InlineData("||")]
[InlineData("&")]
[InlineData("|")]
[InlineData("^")]
public void UnsupportedBinaryOps(string op)
{
bool isLogical = op == "&&" || op == "||";
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
static void M(delegate*<void> ptr1, delegate*<void> ptr2, int* ptr3)
{{
_ = ptr1 {op} ptr2;
_ = ptr1 {op} ptr3;
_ = ptr1 {op} 1;
{(isLogical ? "" : $@"ptr1 {op}= ptr2;
ptr1 {op}= ptr3;
ptr1 {op}= 1;")}
}}
}}");
var expectedDiagnostics = ArrayBuilder<DiagnosticDescription>.GetInstance();
expectedDiagnostics.AddRange(
// (6,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'delegate*<void>'
// _ = ptr1 op ptr2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} ptr2").WithArguments(op, "delegate*<void>", "delegate*<void>").WithLocation(6, 13),
// (7,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'int*'
// _ = ptr1 op ptr3;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} ptr3").WithArguments(op, "delegate*<void>", "int*").WithLocation(7, 13),
// (8,13): error CS0019: Operator 'op' cannot be applied to operands of type 'delegate*<void>' and 'int'
// _ = ptr1 op 1;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op} 1").WithArguments(op, "delegate*<void>", "int").WithLocation(8, 13));
if (!isLogical)
{
expectedDiagnostics.AddRange(
// (9,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'delegate*<void>'
// ptr1 op= ptr2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= ptr2").WithArguments($"{op}=", "delegate*<void>", "delegate*<void>").WithLocation(9, 9),
// (10,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'int*'
// ptr1 op= ptr3;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= ptr3").WithArguments($"{op}=", "delegate*<void>", "int*").WithLocation(10, 9),
// (11,9): error CS0019: Operator 'op=' cannot be applied to operands of type 'delegate*<void>' and 'int'
// ptr1 op= 1;
Diagnostic(ErrorCode.ERR_BadBinaryOps, $"ptr1 {op}= 1").WithArguments($"{op}=", "delegate*<void>", "int").WithLocation(11, 9));
}
comp.VerifyDiagnostics(expectedDiagnostics.ToArrayAndFree());
}
[Theory]
[InlineData("+")]
[InlineData("++")]
[InlineData("-")]
[InlineData("--")]
[InlineData("!")]
[InlineData("~")]
public void UnsupportedPrefixUnaryOps(string op)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
public static void M(delegate*<void> ptr)
{{
_ = {op}ptr;
}}
}}");
comp.VerifyDiagnostics(
// (6,13): error CS0023: Operator 'op' cannot be applied to operand of type 'delegate*<void>'
// _ = {op}ptr;
Diagnostic(ErrorCode.ERR_BadUnaryOp, $"{op}ptr").WithArguments(op, "delegate*<void>").WithLocation(6, 13)
);
}
[Theory]
[InlineData("++")]
[InlineData("--")]
public void UnsupportedPostfixUnaryOps(string op)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C
{{
public static void M(delegate*<void> ptr)
{{
_ = ptr{op};
}}
}}");
comp.VerifyDiagnostics(
// (6,13): error CS0023: Operator 'op' cannot be applied to operand of type 'delegate*<void>'
// _ = ptr{op};
Diagnostic(ErrorCode.ERR_BadUnaryOp, $"ptr{op}").WithArguments(op, "delegate*<void>").WithLocation(6, 13)
);
}
[Fact]
public void FunctionPointerReturnTypeConstrainedCallVirtIfRef()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
void M1() {}
void M<T>(delegate*<ref T> ptr1, delegate*<T> ptr2) where T : C
{
ptr1().M1();
ptr2().M1();
}
}");
verifier.VerifyIL(@"C.M<T>(delegate*<ref T>, delegate*<T>)", @"
{
// Code size 34 (0x22)
.maxstack 1
IL_0000: ldarg.1
IL_0001: calli ""delegate*<ref T>""
IL_0006: constrained. ""T""
IL_000c: callvirt ""void C.M1()""
IL_0011: ldarg.2
IL_0012: calli ""delegate*<T>""
IL_0017: box ""T""
IL_001c: callvirt ""void C.M1()""
IL_0021: ret
}
");
}
[Fact]
public void NullableAnnotationsInMetadata()
{
var source = @"
public unsafe class C
{
public delegate*<string, object, C> F1;
public delegate*<string?, object, C> F2;
public delegate*<string, object?, C> F3;
public delegate*<string, object, C?> F4;
public delegate*<string?, object?, C?> F5;
public delegate*<delegate*<string, int*>, delegate*<string?>, delegate*<void*, string>> F6;
}";
var comp = CreateCompilationWithFunctionPointers(source, options: WithNullableEnable(TestOptions.UnsafeReleaseDll));
comp.VerifyDiagnostics();
verifySymbolNullabilities(comp.GetTypeByMetadataName("C")!);
CompileAndVerify(comp, symbolValidator: symbolValidator, verify: Verification.Skipped);
static void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetTypeMember("C");
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 1, 1})", getAttribute("F1"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 2, 1})", getAttribute("F2"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 1, 1, 2})", getAttribute("F3"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 2, 1, 1})", getAttribute("F4"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 2, 2, 2})", getAttribute("F5"));
Assert.Equal("System.Runtime.CompilerServices.NullableAttribute({0, 0, 1, 0, 0, 0, 1, 0, 2})", getAttribute("F6"));
verifySymbolNullabilities(c);
string getAttribute(string fieldName) => c.GetField(fieldName).GetAttributes().Single().ToString()!;
}
static void verifySymbolNullabilities(NamedTypeSymbol c)
{
assertExpected("delegate*<System.String!, System.Object!, C!>", "F1");
assertExpected("delegate*<System.String?, System.Object!, C!>", "F2");
assertExpected("delegate*<System.String!, System.Object?, C!>", "F3");
assertExpected("delegate*<System.String!, System.Object!, C?>", "F4");
assertExpected("delegate*<System.String?, System.Object?, C?>", "F5");
assertExpected("delegate*<delegate*<System.String!, System.Int32*>, delegate*<System.String?>, delegate*<System.Void*, System.String!>>", "F6");
void assertExpected(string expectedType, string fieldName)
{
var type = (FunctionPointerTypeSymbol)c.GetField(fieldName).Type;
CommonVerifyFunctionPointer(type);
Assert.Equal(expectedType, type.ToTestDisplayString(includeNonNullable: true));
}
}
}
[Theory]
[InlineData("delegate*<Z, Z, (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
[InlineData("delegate*<(Z a, Z b), Z, Z>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
[InlineData("delegate*<Z, (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})")]
[InlineData("delegate*<(Z c, Z d), (Z e, Z f), (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b"", ""c"", ""d"", ""e"", ""f""})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z a, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b"", null, null, null, null})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z a, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", null, null, null, null, null})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z, Z b)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, ""b"", null, null, null, null})")]
[InlineData("delegate*<(Z c, Z d), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, ""c"", ""d"", null, null})")]
[InlineData("delegate*<(Z c, Z), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, ""c"", null, null, null})")]
[InlineData("delegate*<(Z, Z d), (Z, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, ""d"", null, null})")]
[InlineData("delegate*<(Z, Z), (Z e, Z f), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, ""e"", ""f""})")]
[InlineData("delegate*<(Z, Z), (Z e, Z), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, ""e"", null})")]
[InlineData("delegate*<(Z, Z), (Z, Z f), (Z, Z)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({null, null, null, null, null, ""f""})")]
[InlineData("delegate*<(Z a, (Z b, Z c) d), (Z e, Z f)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""e"", ""f"", ""a"", ""d"", ""b"", ""c""})")]
[InlineData("delegate*<(Z a, Z b), ((Z c, Z d) e, Z f)>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""e"", ""f"", ""c"", ""d"", ""a"", ""b""})")]
[InlineData("delegate*<delegate*<(Z a, Z b), Z>, delegate*<Z, (Z d, Z e)>>", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""d"", ""e"", ""a"", ""b""})")]
[InlineData("delegate*<(Z, Z), (Z, Z), (Z, Z)>", null)]
public void TupleNamesInMetadata(string type, string? expectedAttribute)
{
var comp = CompileAndVerifyFunctionPointers($@"
#pragma warning disable CS0649 // Unassigned field
unsafe class Z
{{
public {type} F;
}}
", symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetTypeMember("Z");
var field = c.GetField("F");
if (expectedAttribute == null)
{
Assert.Empty(field.GetAttributes());
}
else
{
Assert.Equal(expectedAttribute, field.GetAttributes().Single().ToString());
}
CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type);
Assert.Equal(type, field.Type.ToTestDisplayString());
}
}
[Fact]
public void DynamicTypeAttributeInMetadata()
{
var comp = CompileAndVerifyFunctionPointers(@"
#pragma warning disable CS0649 // Unassigned field
unsafe class C
{
public delegate*<dynamic, dynamic, dynamic> F1;
public delegate*<object, object, dynamic> F2;
public delegate*<dynamic, object, object> F3;
public delegate*<object, dynamic, object> F4;
public delegate*<object, object, object> F5;
public delegate*<object, object, ref dynamic> F6;
public delegate*<ref dynamic, object, object> F7;
public delegate*<object, ref dynamic, object> F8;
public delegate*<ref object, ref object, dynamic> F9;
public delegate*<dynamic, ref object, ref object> F10;
public delegate*<ref object, dynamic, ref object> F11;
public delegate*<object, ref readonly dynamic> F12;
public delegate*<in dynamic, object> F13;
public delegate*<out dynamic, object> F14;
public D<delegate*<dynamic>[], dynamic> F15;
public delegate*<A<object>.B<dynamic>> F16;
}
class D<T, U> { }
class A<T>
{
public class B<U> {}
}
", symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
var c = module.GlobalNamespace.GetTypeMember("C");
assertField("F1", "System.Runtime.CompilerServices.DynamicAttribute({false, true, true, true})", "delegate*<dynamic, dynamic, dynamic>");
assertField("F2", "System.Runtime.CompilerServices.DynamicAttribute({false, true, false, false})", "delegate*<System.Object, System.Object, dynamic>");
assertField("F3", "System.Runtime.CompilerServices.DynamicAttribute({false, false, true, false})", "delegate*<dynamic, System.Object, System.Object>");
assertField("F4", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "delegate*<System.Object, dynamic, System.Object>");
assertField("F5", null, "delegate*<System.Object, System.Object, System.Object>");
assertField("F6", "System.Runtime.CompilerServices.DynamicAttribute({false, false, true, false, false})", "delegate*<System.Object, System.Object, ref dynamic>");
assertField("F7", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false})", "delegate*<ref dynamic, System.Object, System.Object>");
assertField("F8", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<System.Object, ref dynamic, System.Object>");
assertField("F9", "System.Runtime.CompilerServices.DynamicAttribute({false, true, false, false, false, false})", "delegate*<ref System.Object, ref System.Object, dynamic>");
assertField("F10", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false, false})", "delegate*<dynamic, ref System.Object, ref System.Object>");
assertField("F11", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, false, true})", "delegate*<ref System.Object, dynamic, ref System.Object>");
assertField("F12", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true, false})", "delegate*<System.Object, ref readonly modreq(System.Runtime.InteropServices.InAttribute) dynamic>");
assertField("F13", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<in modreq(System.Runtime.InteropServices.InAttribute) dynamic, System.Object>");
assertField("F14", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, true})", "delegate*<out modreq(System.Runtime.InteropServices.OutAttribute) dynamic, System.Object>");
// https://github.com/dotnet/roslyn/issues/44160 tracks fixing this. We're not encoding dynamic correctly for function pointers as type parameters
assertField("F15", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "D<delegate*<System.Object>[], System.Object>");
assertField("F16", "System.Runtime.CompilerServices.DynamicAttribute({false, false, false, true})", "delegate*<A<System.Object>.B<dynamic>>");
void assertField(string field, string? expectedAttribute, string expectedType)
{
var f = c.GetField(field);
if (expectedAttribute is null)
{
Assert.Empty(f.GetAttributes());
}
else
{
Assert.Equal(expectedAttribute, f.GetAttributes().Single().ToString());
}
if (f.Type is FunctionPointerTypeSymbol ptrType)
{
CommonVerifyFunctionPointer(ptrType);
}
Assert.Equal(expectedType, f.Type.ToTestDisplayString());
}
}
}
[Fact]
public void DynamicOverriddenWithCustomModifiers()
{
var il = @"
.class public A
{
.method public hidebysig newslot virtual
instance void M(method class [mscorlib]System.Object modopt([mscorlib]System.Object) & modopt([mscorlib]System.Object) modreq([mscorlib]System.Runtime.InteropServices.InAttribute) *(class [mscorlib]System.Object modopt([mscorlib]System.Object)) a) managed
{
.param [1]
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 08 00 00 00 00 00 00 00 00 01 00 01 00 00 )
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
var source = @"
unsafe class B : A
{
public override void M(delegate*<dynamic, ref readonly dynamic> a) {}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var b = module.GlobalNamespace.GetTypeMember("B");
var m = b.GetMethod("M");
var param = m.Parameters.Single();
Assert.Equal("System.Runtime.CompilerServices.DynamicAttribute({false, false, false, false, false, true, false, true})", param.GetAttributes().Single().ToString());
CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)param.Type);
Assert.Equal("delegate*<dynamic modopt(System.Object), ref readonly modreq(System.Runtime.InteropServices.InAttribute) modopt(System.Object) dynamic modopt(System.Object)>", param.Type.ToTestDisplayString());
}
}
[Fact]
public void BadDynamicAttributes()
{
var il = @"
.class public A
{
.method public hidebysig static void TooManyFlags(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void TooFewFlags_MissingParam(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 )
ret
}
.method public hidebysig static void TooFewFlags_MissingReturn(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{false}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 )
ret
}
.method public hidebysig static void PtrTypeIsTrue(method class [mscorlib]System.Object *(class [mscorlib]System.Object) a)
{
.param [1]
//{true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void NonObjectIsTrue(method class [mscorlib]System.String *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 )
ret
}
.method public hidebysig static void RefIsTrue_Return(method class [mscorlib]System.Object& *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void RefIsTrue_Param(method class [mscorlib]System.Object *(class [mscorlib]System.Object&) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_Return(method class [mscorlib]System.Object modopt([mscorlib]System.Object) *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_Param(method class [mscorlib]System.Object *(class [mscorlib]System.Object modopt([mscorlib]System.Object)) a)
{
.param [1]
//{false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 04 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_RefReturn(method class [mscorlib]System.Object & modopt([mscorlib]System.Object) *(class [mscorlib]System.Object) a)
{
.param [1]
//{false, false, true, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 05 00 00 00 00 00 01 01 01 00 00 )
ret
}
.method public hidebysig static void ModIsTrue_RefParam(method class [mscorlib]System.Object *(class [mscorlib]System.Object & modopt([mscorlib]System.Object)) a)
{
.param [1]
//{false, true, false, true, true}
.custom instance void [mscorlib]System.Runtime.CompilerServices.DynamicAttribute::.ctor(bool[]) = ( 01 00 05 00 00 00 00 01 00 01 01 00 00 )
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl("", il);
var a = comp.GetTypeByMetadataName("A");
assert("TooManyFlags", "delegate*<System.Object, System.Object>");
assert("TooFewFlags_MissingParam", "delegate*<System.Object, System.Object>");
assert("TooFewFlags_MissingReturn", "delegate*<System.Object, System.Object>");
assert("PtrTypeIsTrue", "delegate*<System.Object, System.Object>");
assert("NonObjectIsTrue", "delegate*<System.Object, System.String>");
assert("RefIsTrue_Return", "delegate*<System.Object, ref System.Object>");
assert("RefIsTrue_Param", "delegate*<ref System.Object, System.Object>");
assert("ModIsTrue_Return", "delegate*<System.Object, System.Object modopt(System.Object)>");
assert("ModIsTrue_Param", "delegate*<System.Object modopt(System.Object), System.Object>");
assert("ModIsTrue_RefReturn", "delegate*<System.Object, ref modopt(System.Object) System.Object>");
assert("ModIsTrue_RefParam", "delegate*<ref modopt(System.Object) System.Object, System.Object>");
void assert(string methodName, string expectedType)
{
var method = a.GetMethod(methodName);
var param = method.Parameters.Single();
CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)param.Type);
Assert.Equal(expectedType, param.Type.ToTestDisplayString());
}
}
[Fact]
public void BetterFunctionMember_BreakTiesByCustomModifierCount_TypeMods()
{
var il = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
void RetModifiers (method void modopt([mscorlib]System.Object) modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void RetModifiers (method void modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32 modopt([mscorlib]System.Object) modopt([mscorlib]System.Object))) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32) modopt([mscorlib]System.Object)) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
}";
var source = @"
unsafe class C
{
static void Main()
{
delegate*<void> ptr1 = null;
Program.RetModifiers(ptr1);
delegate*<int, void> ptr2 = null;
Program.ParamModifiers(ptr2);
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "LL");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (delegate*<void> V_0, //ptr1
delegate*<int, void> V_1) //ptr2
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call ""void Program.RetModifiers(delegate*<void>)""
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: call ""void Program.ParamModifiers(delegate*<int, void>)""
IL_0012: ret
}
");
}
[Fact]
public void BetterFunctionMember_BreakTiesByCustomModifierCount_Ref()
{
var il = @"
.class public auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
void RetModifiers (method int32 & modopt([mscorlib]System.Object) modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void RetModifiers (method int32 & modopt([mscorlib]System.Object) *()) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32 & modopt([mscorlib]System.Object) modopt([mscorlib]System.Object))) cil managed
{
ldstr ""M""
call void [mscorlib]System.Console::Write(string)
ret
}
.method public hidebysig static
void ParamModifiers (method void *(int32 & modopt([mscorlib]System.Object))) cil managed
{
ldstr ""L""
call void [mscorlib]System.Console::Write(string)
ret
}
}
";
var source = @"
unsafe class C
{
static void Main()
{
delegate*<ref int> ptr1 = null;
Program.RetModifiers(ptr1);
delegate*<ref int, void> ptr2 = null;
Program.ParamModifiers(ptr2);
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: "LL");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (delegate*<ref int> V_0, //ptr1
delegate*<ref int, void> V_1) //ptr2
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call ""void Program.RetModifiers(delegate*<ref int>)""
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: call ""void Program.ParamModifiers(delegate*<ref int, void>)""
IL_0012: ret
}
");
}
[Fact]
public void Overloading_ReturnTypes()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(delegate*<void> ptr) => ptr();
static void M(delegate*<object> ptr) => Console.WriteLine(ptr());
static void M(delegate*<string> ptr) => Console.WriteLine(ptr());
static void Ptr_Void() => Console.WriteLine(""Void"");
static object Ptr_Obj() => ""Object"";
static string Ptr_Str() => ""String"";
static void Main()
{
M(&Ptr_Void);
M(&Ptr_Obj);
M(&Ptr_Str);
}
}
", expectedOutput: @"
Void
Object
String");
verifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 1
IL_0000: ldftn ""void C.Ptr_Void()""
IL_0006: call ""void C.M(delegate*<void>)""
IL_000b: ldftn ""object C.Ptr_Obj()""
IL_0011: call ""void C.M(delegate*<object>)""
IL_0016: ldftn ""string C.Ptr_Str()""
IL_001c: call ""void C.M(delegate*<string>)""
IL_0021: ret
}
");
}
[Fact]
public void Overloading_ValidReturnRefness()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object field = ""R"";
static void M(delegate*<object> ptr) => Console.WriteLine(ptr());
static void M(delegate*<ref object> ptr)
{
Console.Write(field);
ref var local = ref ptr();
local = ""ef"";
Console.WriteLine(field);
}
static object Ptr_NonRef() => ""NonRef"";
static ref object Ptr_Ref() => ref field;
static void Main()
{
M(&Ptr_NonRef);
M(&Ptr_Ref);
}
}
", expectedOutput: @"
NonRef
Ref");
verifier.VerifyIL("C.Main", @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldftn ""object C.Ptr_NonRef()""
IL_0006: call ""void C.M(delegate*<object>)""
IL_000b: ldftn ""ref object C.Ptr_Ref()""
IL_0011: call ""void C.M(delegate*<ref object>)""
IL_0016: ret
}
");
}
[Fact]
public void Overloading_InvalidReturnRefness()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C<T>
{
static void M1(delegate*<ref readonly object> ptr) => throw null;
static void M1(delegate*<ref object> ptr) => throw null;
static void M2(C<delegate*<ref readonly object>[]> c) => throw null;
static void M2(C<delegate*<ref object>[]> c) => throw null;
}
");
comp.VerifyDiagnostics(
// (5,17): error CS0111: Type 'C<T>' already defines a member called 'M1' with the same parameter types
// static void M1(delegate*<ref object> ptr) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C<T>").WithLocation(5, 17),
// (8,17): error CS0111: Type 'C<T>' already defines a member called 'M2' with the same parameter types
// static void M2(C<delegate*<ref object>[]> c) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C<T>").WithLocation(8, 17)
);
}
[Fact]
public void Overloading_ReturnNoBetterFunction()
{
var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
unsafe class C : I1, I2
{
static void M1(delegate*<I1> ptr) => throw null;
static void M1(delegate*<I2> ptr) => throw null;
static void M2(delegate*<C> ptr)
{
M1(ptr);
}
}
");
comp.VerifyDiagnostics(
// (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1(delegate*<I1>)' and 'C.M1(delegate*<I2>)'
// M1(ptr);
Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1(delegate*<I1>)", "C.M1(delegate*<I2>)").WithLocation(11, 9)
);
}
[Fact]
public void Overloading_ParameterTypes()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static void M(delegate*<object, void> ptr) => ptr(""Object"");
static void M(delegate*<string, void> ptr) => ptr(""String"");
static void Main()
{
delegate*<object, void> ptr1 = &Console.WriteLine;
delegate*<string, void> ptr2 = &Console.WriteLine;
M(ptr1);
M(ptr2);
}
}
", expectedOutput: @"
Object
String");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 25 (0x19)
.maxstack 2
.locals init (delegate*<string, void> V_0) //ptr2
IL_0000: ldftn ""void System.Console.WriteLine(object)""
IL_0006: ldftn ""void System.Console.WriteLine(string)""
IL_000c: stloc.0
IL_000d: call ""void C.M(delegate*<object, void>)""
IL_0012: ldloc.0
IL_0013: call ""void C.M(delegate*<string, void>)""
IL_0018: ret
}
");
}
[Fact]
public void Overloading_ValidParameterRefness()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe class C
{
static object field = ""R"";
static void M(delegate*<ref object, void> ptr)
{
Console.Write(field);
ref var local = ref field;
ptr(ref local);
Console.WriteLine(field);
}
static void M(delegate*<object, void> ptr) => ptr(""NonRef"");
static void Ptr(ref object param) => param = ""ef"";
static void Main()
{
M(&Console.WriteLine);
M(&Ptr);
}
}
", expectedOutput: @"
NonRef
Ref");
verifier.VerifyIL("C.Main", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldftn ""void System.Console.WriteLine(object)""
IL_0006: call ""void C.M(delegate*<object, void>)""
IL_000b: ldftn ""void C.Ptr(ref object)""
IL_0011: call ""void C.M(delegate*<ref object, void>)""
IL_0016: ret
}
");
}
[Theory]
[InlineData("ref", "out")]
[InlineData("ref", "in")]
[InlineData("out", "in")]
public void Overloading_InvalidParameterRefness(string refKind1, string refKind2)
{
var comp = CreateCompilationWithFunctionPointers($@"
unsafe class C<T>
{{
static void M1(delegate*<{refKind1} object, void> ptr) => throw null;
static void M1(delegate*<{refKind2} object, void> ptr) => throw null;
static void M2(C<delegate*<{refKind1} object, void>[]> c) => throw null;
static void M2(C<delegate*<{refKind2} object, void>[]> c) => throw null;
}}
");
comp.VerifyDiagnostics(
// (5,17): error CS0111: Type 'C<T>' already defines a member called 'M1' with the same parameter types
// static void M1(delegate*<{refKind2} object, void> ptr) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M1").WithArguments("M1", "C<T>").WithLocation(5, 17),
// (8,17): error CS0111: Type 'C<T>' already defines a member called 'M2' with the same parameter types
// static void M2(C<delegate*<{refKind2} object, void>[]> c) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M2").WithArguments("M2", "C<T>").WithLocation(8, 17)
);
}
[Fact]
public void Overloading_ParameterTypesNoBetterFunctionMember()
{
var comp = CreateCompilationWithFunctionPointers(@"
interface I1 {}
interface I2 {}
unsafe class C : I1, I2
{
static void M1(delegate*<delegate*<I1, void>, void> ptr) => throw null;
static void M1(delegate*<delegate*<I2, void>, void> ptr) => throw null;
static void M2(delegate*<delegate*<C, void>, void> ptr)
{
M1(ptr);
}
}
");
comp.VerifyDiagnostics(
// (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M1(delegate*<delegate*<I1, void>, void>)' and 'C.M1(delegate*<delegate*<I2, void>, void>)'
// M1(ptr);
Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("C.M1(delegate*<delegate*<I1, void>, void>)", "C.M1(delegate*<delegate*<I2, void>, void>)").WithLocation(11, 9)
);
}
[Fact]
public void Override_CallingConventionMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<void> ptr) {}
protected virtual delegate*<void> M2() => throw null;
protected virtual void M3(delegate* unmanaged[Stdcall, Thiscall]<void> ptr) {}
protected virtual delegate* unmanaged[Stdcall, Thiscall]<void> M4() => throw null;
}
unsafe class Derived1 : Base
{
protected override void M1(delegate* unmanaged[Cdecl]<void> ptr) {}
protected override delegate* unmanaged[Cdecl]<void> M2() => throw null;
protected override void M3(delegate* unmanaged[Fastcall, Thiscall]<void> ptr) {}
protected override delegate* unmanaged[Fastcall, Thiscall]<void> M4() => throw null;
}
unsafe class Derived2 : Base
{
protected override void M1(delegate*<void> ptr) {} // Implemented correctly
protected override delegate*<void> M2() => throw null; // Implemented correctly
protected override void M3(delegate* unmanaged[Stdcall, Fastcall]<void> ptr) {}
protected override delegate* unmanaged[Stdcall, Fastcall]<void> M4() => throw null;
}
");
comp.VerifyDiagnostics(
// (11,29): error CS0115: 'Derived1.M1(delegate* unmanaged[Cdecl]<void>)': no suitable method found to override
// protected override void M1(delegate* unmanaged[Cdecl]<void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived1.M1(delegate* unmanaged[Cdecl]<void>)").WithLocation(11, 29),
// (12,57): error CS0508: 'Derived1.M2()': return type must be 'delegate*<void>' to match overridden member 'Base.M2()'
// protected override delegate* unmanaged[Cdecl]<void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived1.M2()", "Base.M2()", "delegate*<void>").WithLocation(12, 57),
// (13,29): error CS0115: 'Derived1.M3(delegate* unmanaged[Fastcall, Thiscall]<void>)': no suitable method found to override
// protected override void M3(delegate* unmanaged[Fastcall, Thiscall]<void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived1.M3(delegate* unmanaged[Fastcall, Thiscall]<void>)").WithLocation(13, 29),
// (14,70): error CS0508: 'Derived1.M4()': return type must be 'delegate* unmanaged[Stdcall, Thiscall]<void>' to match overridden member 'Base.M4()'
// protected override delegate* unmanaged[Fastcall, Thiscall]<void> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived1.M4()", "Base.M4()", "delegate* unmanaged[Stdcall, Thiscall]<void>").WithLocation(14, 70),
// (20,29): error CS0115: 'Derived2.M3(delegate* unmanaged[Stdcall, Fastcall]<void>)': no suitable method found to override
// protected override void M3(delegate* unmanaged[Stdcall, Fastcall]<void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived2.M3(delegate* unmanaged[Stdcall, Fastcall]<void>)").WithLocation(20, 29),
// (21,69): error CS0508: 'Derived2.M4()': return type must be 'delegate* unmanaged[Stdcall, Thiscall]<void>' to match overridden member 'Base.M4()'
// protected override delegate* unmanaged[Stdcall, Fastcall]<void> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived2.M4()", "Base.M4()", "delegate* unmanaged[Stdcall, Thiscall]<void>").WithLocation(21, 69)
);
}
[Fact]
public void Override_ConventionOrderingDoesNotMatter()
{
var source1 = @"
using System;
public unsafe class Base
{
public virtual void M1(delegate* unmanaged[Thiscall, Stdcall]<void> param) => Console.WriteLine(""Base Thiscall, Stdcall param"");
public virtual delegate* unmanaged[Thiscall, Stdcall]<void> M2() { Console.WriteLine(""Base Thiscall, Stdcall return""); return null; }
public virtual void M3(delegate* unmanaged[Thiscall, Stdcall]<ref string> param) => Console.WriteLine(""Base Thiscall, Stdcall ref param"");
public virtual delegate* unmanaged[Thiscall, Stdcall]<ref string> M4() { Console.WriteLine(""Base Thiscall, Stdcall ref return""); return null; }
}
";
var source2 = @"
using System;
unsafe class Derived1 : Base
{
public override void M1(delegate* unmanaged[Stdcall, Thiscall]<void> param) => Console.WriteLine(""Derived1 Stdcall, Thiscall param"");
public override delegate* unmanaged[Stdcall, Thiscall]<void> M2() { Console.WriteLine(""Derived1 Stdcall, Thiscall return""); return null; }
public override void M3(delegate* unmanaged[Stdcall, Thiscall]<ref string> param) => Console.WriteLine(""Derived1 Stdcall, Thiscall ref param"");
public override delegate* unmanaged[Stdcall, Thiscall]<ref string> M4() { Console.WriteLine(""Derived1 Stdcall, Thiscall ref return""); return null; }
}
unsafe class Derived2 : Base
{
public override void M1(delegate* unmanaged[Stdcall, Stdcall, Thiscall]<void> param) => Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall param"");
public override delegate* unmanaged[Stdcall, Stdcall, Thiscall]<void> M2() { Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall return""); return null; }
public override void M3(delegate* unmanaged[Stdcall, Stdcall, Thiscall]<ref string> param) => Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall ref param"");
public override delegate* unmanaged[Stdcall, Stdcall, Thiscall]<ref string> M4() { Console.WriteLine(""Derived2 Stdcall, Stdcall, Thiscall ref return""); return null; }
}
";
var executableCode = @"
using System;
unsafe
{
delegate* unmanaged[Stdcall, Thiscall]<void> ptr1 = null;
delegate* unmanaged[Stdcall, Thiscall]<ref string> ptr3 = null;
Base b1 = new Base();
b1.M1(ptr1);
b1.M2();
b1.M3(ptr3);
b1.M4();
Base d1 = new Derived1();
d1.M1(ptr1);
d1.M2();
d1.M3(ptr3);
d1.M4();
Base d2 = new Derived2();
d2.M1(ptr1);
d2.M2();
d2.M3(ptr3);
d2.M4();
}
";
var expectedOutput = @"
Base Thiscall, Stdcall param
Base Thiscall, Stdcall return
Base Thiscall, Stdcall ref param
Base Thiscall, Stdcall ref return
Derived1 Stdcall, Thiscall param
Derived1 Stdcall, Thiscall return
Derived1 Stdcall, Thiscall ref param
Derived1 Stdcall, Thiscall ref return
Derived2 Stdcall, Stdcall, Thiscall param
Derived2 Stdcall, Stdcall, Thiscall return
Derived2 Stdcall, Stdcall, Thiscall ref param
Derived2 Stdcall, Stdcall, Thiscall ref return
";
var allSourceComp = CreateCompilationWithFunctionPointers(new[] { executableCode, source1, source2 }, options: TestOptions.UnsafeReleaseExe);
CompileAndVerify(
allSourceComp,
expectedOutput: RuntimeUtilities.IsCoreClrRuntime ? expectedOutput : null,
symbolValidator: getSymbolValidator(separateAssembly: false),
verify: Verification.Skipped);
var baseComp = CreateCompilationWithFunctionPointers(source1);
var metadataRef = baseComp.EmitToImageReference();
var derivedComp = CreateCompilationWithFunctionPointers(new[] { executableCode, source2 }, references: new[] { metadataRef }, options: TestOptions.UnsafeReleaseExe);
CompileAndVerify(
derivedComp,
expectedOutput: RuntimeUtilities.IsCoreClrRuntime ? expectedOutput : null,
symbolValidator: getSymbolValidator(separateAssembly: true),
verify: Verification.Skipped);
static Action<ModuleSymbol> getSymbolValidator(bool separateAssembly)
{
return module =>
{
var @base = (separateAssembly ? module.ReferencedAssemblySymbols[1].GlobalNamespace : module.GlobalNamespace).GetTypeMember("Base");
var baseM1 = @base.GetMethod("M1");
var baseM2 = @base.GetMethod("M2");
var baseM3 = @base.GetMethod("M3");
var baseM4 = @base.GetMethod("M4");
for (int derivedI = 1; derivedI <= 2; derivedI++)
{
var derived = module.GlobalNamespace.GetTypeMember($"Derived{derivedI}");
var derivedM1 = derived.GetMethod("M1");
var derivedM2 = derived.GetMethod("M2");
var derivedM3 = derived.GetMethod("M3");
var derivedM4 = derived.GetMethod("M4");
Assert.True(baseM1.Parameters.Single().Type.Equals(derivedM1.Parameters.Single().Type, TypeCompareKind.ConsiderEverything));
Assert.True(baseM2.ReturnType.Equals(derivedM2.ReturnType, TypeCompareKind.ConsiderEverything));
Assert.True(baseM3.Parameters.Single().Type.Equals(derivedM3.Parameters.Single().Type, TypeCompareKind.ConsiderEverything));
Assert.True(baseM4.ReturnType.Equals(derivedM4.ReturnType, TypeCompareKind.ConsiderEverything));
}
};
}
}
[Theory]
[InlineData("", "ref ")]
[InlineData("", "out ")]
[InlineData("", "in ")]
[InlineData("ref ", "")]
[InlineData("ref ", "out ")]
[InlineData("ref ", "in ")]
[InlineData("out ", "")]
[InlineData("out ", "ref ")]
[InlineData("out ", "in ")]
[InlineData("in ", "")]
[InlineData("in ", "ref ")]
[InlineData("in ", "out ")]
public void Override_RefnessMustMatch_Parameters(string refKind1, string refKind2)
{
var comp = CreateCompilationWithFunctionPointers(@$"
unsafe class Base
{{
protected virtual void M1(delegate*<{refKind1}string, void> ptr) {{}}
protected virtual delegate*<{refKind1}string, void> M2() => throw null;
}}
unsafe class Derived : Base
{{
protected override void M1(delegate*<{refKind2}string, void> ptr) {{}}
protected override delegate*<{refKind2}string, void> M2() => throw null;
}}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<{refKind2} string, void>)': no suitable method found to override
// protected override void M1(delegate*<{refKind2} string, void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments($"Derived.M1(delegate*<{refKind2}string, void>)").WithLocation(9, 29),
// (10,49): error CS0508: 'Derived.M2()': return type must be 'delegate*<{refKind1} string, void>' to match overridden member 'Base.M2()'
// protected override delegate*<{refKind2} string, void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", $"delegate*<{refKind1}string, void>").WithLocation(10, 48 + refKind2.Length)
);
}
[Theory]
[InlineData(" ", "ref ")]
[InlineData(" ", "ref readonly ")]
[InlineData("ref ", " ")]
[InlineData("ref ", "ref readonly ")]
[InlineData("ref readonly ", " ")]
[InlineData("ref readonly ", "ref ")]
public void Override_RefnessMustMatch_Returns(string refKind1, string refKind2)
{
var comp = CreateCompilationWithFunctionPointers(@$"
unsafe class Base
{{
protected virtual void M1(delegate*<{refKind1}string> ptr) {{}}
protected virtual delegate*<{refKind1}string> M2() => throw null;
}}
unsafe class Derived : Base
{{
protected override void M1(delegate*<{refKind2}string> ptr) {{}}
protected override delegate*<{refKind2}string> M2() => throw null;
}}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<{refKind2} string>)': no suitable method found to override
// protected override void M1(delegate*<{refKind2} string> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments($"Derived.M1(delegate*<{(string.IsNullOrWhiteSpace(refKind2) ? "" : refKind2)}string>)").WithLocation(9, 29),
// (10,49): error CS0508: 'Derived.M2()': return type must be 'delegate*<{refKind1} string>' to match overridden member 'Base.M2()'
// protected override delegate*<{refKind2} string> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", $"delegate*<{(string.IsNullOrWhiteSpace(refKind1) ? "" : refKind1)}string>").WithLocation(10, 42 + refKind2.Length)
);
}
[Fact]
public void Override_ParameterTypesMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<object, void> ptr) {{}}
protected virtual delegate*<object, void> M2() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<string, void> ptr) {{}}
protected override delegate*<string, void> M2() => throw null;
}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<string, void>)': no suitable method found to override
// protected override void M1(delegate*<string, void> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<string, void>)").WithLocation(9, 29),
// (10,48): error CS0508: 'Derived.M2()': return type must be 'delegate*<object, void>' to match overridden member 'Base.M2()'
// protected override delegate*<string, void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<object, void>").WithLocation(10, 48)
);
}
[Fact]
public void Override_ReturnTypesMustMatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<object> ptr) {{}}
protected virtual delegate*<object> M2() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<string> ptr) {{}}
protected override delegate*<string> M2() => throw null;
}");
comp.VerifyDiagnostics(
// (9,29): error CS0115: 'Derived.M1(delegate*<string>)': no suitable method found to override
// protected override void M1(delegate*<string> ptr) {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<string>)").WithLocation(9, 29),
// (10,42): error CS0508: 'Derived.M2()': return type must be 'delegate*<object>' to match overridden member 'Base.M2()'
// protected override delegate*<string> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<object>").WithLocation(10, 42)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44358")]
public void Override_NintIntPtrDifferences()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<nint> ptr) {}
protected virtual delegate*<nint> M2() => throw null;
protected virtual void M3(delegate*<nint, void> ptr) {}
protected virtual delegate*<nint, void> M4() => throw null;
protected virtual void M5(delegate*<System.IntPtr> ptr) {}
protected virtual delegate*<System.IntPtr> M6() => throw null;
protected virtual void M7(delegate*<System.IntPtr, void> ptr) {}
protected virtual delegate*<System.IntPtr, void> M8() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<System.IntPtr> ptr) {}
protected override delegate*<System.IntPtr> M2() => throw null;
protected override void M3(delegate*<System.IntPtr, void> ptr) {}
protected override delegate*<System.IntPtr, void> M4() => throw null;
protected override void M5(delegate*<nint> ptr) {}
protected override delegate*<nint> M6() => throw null;
protected override void M7(delegate*<nint, void> ptr) {}
protected override delegate*<nint, void> M8() => throw null;
}");
comp.VerifyDiagnostics(
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<System.IntPtr> ptr)");
assertMethod(derived, "M2", "delegate*<System.IntPtr> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<System.IntPtr, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<System.IntPtr, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<nint> ptr)");
assertMethod(derived, "M6", "delegate*<nint> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<nint, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<nint, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_ObjectDynamicDifferences()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<dynamic> ptr) {}
protected virtual delegate*<dynamic> M2() => throw null;
protected virtual void M3(delegate*<dynamic, void> ptr) {}
protected virtual delegate*<dynamic, void> M4() => throw null;
protected virtual void M5(delegate*<object> ptr) {}
protected virtual delegate*<object> M6() => throw null;
protected virtual void M7(delegate*<object, void> ptr) {}
protected virtual delegate*<object, void> M8() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<object> ptr) {}
protected override delegate*<object> M2() => throw null;
protected override void M3(delegate*<object, void> ptr) {}
protected override delegate*<object, void> M4() => throw null;
protected override void M5(delegate*<dynamic> ptr) {}
protected override delegate*<dynamic> M6() => throw null;
protected override void M7(delegate*<dynamic, void> ptr) {}
protected override delegate*<dynamic, void> M8() => throw null;
}");
comp.VerifyDiagnostics(
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<System.Object> ptr)");
assertMethod(derived, "M2", "delegate*<System.Object> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<System.Object, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<System.Object, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<dynamic> ptr)");
assertMethod(derived, "M6", "delegate*<dynamic> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<dynamic, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<dynamic, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_TupleNameChanges()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Base
{
protected virtual void M1(delegate*<(int, string)> ptr) {}
protected virtual delegate*<(int, string)> M2() => throw null;
protected virtual void M3(delegate*<(int, string), void> ptr) {}
protected virtual delegate*<(int, string), void> M4() => throw null;
protected virtual void M5(delegate*<(int i, string s)> ptr) {}
protected virtual delegate*<(int i, string s)> M6() => throw null;
protected virtual void M7(delegate*<(int i, string s), void> ptr) {}
protected virtual delegate*<(int i, string s), void> M8() => throw null;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<(int i, string s)> ptr) {}
protected override delegate*<(int i, string s)> M2() => throw null;
protected override void M3(delegate*<(int i, string s), void> ptr) {}
protected override delegate*<(int i, string s), void> M4() => throw null;
protected override void M5(delegate*<(int, string)> ptr) {}
protected override delegate*<(int, string)> M6() => throw null;
protected override void M7(delegate*<(int, string), void> ptr) {}
protected override delegate*<(int, string), void> M8() => throw null;
}");
comp.VerifyDiagnostics(
// (15,29): error CS8139: 'Derived.M1(delegate*<(int i, string s)>)': cannot change tuple element names when overriding inherited member 'Base.M1(delegate*<(int, string)>)'
// protected override void M1(delegate*<(int i, string s)> ptr) {}
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M1").WithArguments("Derived.M1(delegate*<(int i, string s)>)", "Base.M1(delegate*<(int, string)>)").WithLocation(15, 29),
// (16,53): error CS8139: 'Derived.M2()': cannot change tuple element names when overriding inherited member 'Base.M2()'
// protected override delegate*<(int i, string s)> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()").WithLocation(16, 53),
// (17,29): error CS8139: 'Derived.M3(delegate*<(int i, string s), void>)': cannot change tuple element names when overriding inherited member 'Base.M3(delegate*<(int, string), void>)'
// protected override void M3(delegate*<(int i, string s), void> ptr) {}
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M3").WithArguments("Derived.M3(delegate*<(int i, string s), void>)", "Base.M3(delegate*<(int, string), void>)").WithLocation(17, 29),
// (18,59): error CS8139: 'Derived.M4()': cannot change tuple element names when overriding inherited member 'Base.M4()'
// protected override delegate*<(int i, string s), void> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeTupleNamesOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()").WithLocation(18, 59)
);
assertMethod("M1", "void Derived.M1(delegate*<(System.Int32 i, System.String s)> ptr)");
assertMethod("M2", "delegate*<(System.Int32 i, System.String s)> Derived.M2()");
assertMethod("M3", "void Derived.M3(delegate*<(System.Int32 i, System.String s), System.Void> ptr)");
assertMethod("M4", "delegate*<(System.Int32 i, System.String s), System.Void> Derived.M4()");
assertMethod("M5", "void Derived.M5(delegate*<(System.Int32, System.String)> ptr)");
assertMethod("M6", "delegate*<(System.Int32, System.String)> Derived.M6()");
assertMethod("M7", "void Derived.M7(delegate*<(System.Int32, System.String), System.Void> ptr)");
assertMethod("M8", "delegate*<(System.Int32, System.String), System.Void> Derived.M8()");
void assertMethod(string methodName, string expectedSignature)
{
var m = comp.GetMember<MethodSymbol>($"Derived.{methodName}");
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString());
}
}
[Fact]
public void Override_NullabilityChanges_NoRefs()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe class Base
{
protected virtual void M1(delegate*<string?> ptr) {}
protected virtual delegate*<string?> M2() => throw null!;
protected virtual void M3(delegate*<string?, void> ptr) {}
protected virtual delegate*<string?, void> M4() => throw null!;
protected virtual void M5(delegate*<string> ptr) {}
protected virtual delegate*<string> M6() => throw null!;
protected virtual void M7(delegate*<string, void> ptr) {}
protected virtual delegate*<string, void> M8() => throw null!;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<string> ptr) {}
protected override delegate*<string> M2() => throw null!;
protected override void M3(delegate*<string, void> ptr) {}
protected override delegate*<string, void> M4() => throw null!;
protected override void M5(delegate*<string?> ptr) {}
protected override delegate*<string?> M6() => throw null!;
protected override void M7(delegate*<string?, void> ptr) {}
protected override delegate*<string?, void> M8() => throw null!;
}");
comp.VerifyDiagnostics(
// (16,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M1(delegate*<string> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 29),
// (19,48): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<string, void> M4() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 48),
// (21,43): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<string?> M6() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 43),
// (22,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M7(delegate*<string?, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 29)
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<System.String!> ptr)");
assertMethod(derived, "M2", "delegate*<System.String!> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<System.String!, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<System.String!, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<System.String?> ptr)");
assertMethod(derived, "M6", "delegate*<System.String?> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<System.String?, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<System.String?, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_NullabilityChanges_RefsInParameterReturnTypes()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe class Base
{
protected virtual void M1(delegate*<ref string?> ptr) {}
protected virtual delegate*<ref string?> M2() => throw null!;
protected virtual void M3(delegate*<ref string?, void> ptr) {}
protected virtual delegate*<ref string?, void> M4() => throw null!;
protected virtual void M5(delegate*<ref string> ptr) {}
protected virtual delegate*<ref string> M6() => throw null!;
protected virtual void M7(delegate*<ref string, void> ptr) {}
protected virtual delegate*<ref string, void> M8() => throw null!;
}
unsafe class Derived : Base
{
protected override void M1(delegate*<ref string> ptr) {}
protected override delegate*<ref string> M2() => throw null!;
protected override void M3(delegate*<ref string, void> ptr) {}
protected override delegate*<ref string, void> M4() => throw null!;
protected override void M5(delegate*<ref string?> ptr) {}
protected override delegate*<ref string?> M6() => throw null!;
protected override void M7(delegate*<ref string?, void> ptr) {}
protected override delegate*<ref string?, void> M8() => throw null!;
}");
comp.VerifyDiagnostics(
// (16,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M1(delegate*<ref string> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 29),
// (17,46): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string> M2() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(17, 46),
// (18,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M3(delegate*<ref string, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("ptr").WithLocation(18, 29),
// (19,52): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string, void> M4() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 52),
// (20,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M5(delegate*<ref string?> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("ptr").WithLocation(20, 29),
// (21,47): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string?> M6() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 47),
// (22,29): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// protected override void M7(delegate*<ref string?, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 29),
// (23,53): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// protected override delegate*<ref string?, void> M8() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M8").WithLocation(23, 53)
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(delegate*<ref System.String!> ptr)");
assertMethod(derived, "M2", "delegate*<ref System.String!> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(delegate*<ref System.String!, System.Void> ptr)");
assertMethod(derived, "M4", "delegate*<ref System.String!, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(delegate*<ref System.String?> ptr)");
assertMethod(derived, "M6", "delegate*<ref System.String?> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(delegate*<ref System.String?, System.Void> ptr)");
assertMethod(derived, "M8", "delegate*<ref System.String?, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_NullabilityChanges_PointerByRef()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
public unsafe class Base
{
public virtual void M1(ref delegate*<string?> ptr) {}
public virtual ref delegate*<string?> M2() => throw null!;
public virtual void M3(ref delegate*<string?, void> ptr) {}
public virtual ref delegate*<string?, void> M4() => throw null!;
public virtual void M5(ref delegate*<string> ptr) {}
public virtual ref delegate*<string> M6() => throw null!;
public virtual void M7(ref delegate*<string, void> ptr) {}
public virtual ref delegate*<string, void> M8() => throw null!;
}
public unsafe class Derived : Base
{
public override void M1(ref delegate*<string> ptr) {}
public override ref delegate*<string> M2() => throw null!;
public override void M3(ref delegate*<string, void> ptr) {}
public override ref delegate*<string, void> M4() => throw null!;
public override void M5(ref delegate*<string?> ptr) {}
public override ref delegate*<string?> M6() => throw null!;
public override void M7(ref delegate*<string?, void> ptr) {}
public override ref delegate*<string?, void> M8() => throw null!;
}");
comp.VerifyDiagnostics(
// (16,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M1(ref delegate*<string> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M1").WithArguments("ptr").WithLocation(16, 26),
// (17,43): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string> M2() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(17, 43),
// (18,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M3(ref delegate*<string, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("ptr").WithLocation(18, 26),
// (19,49): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string, void> M4() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(19, 49),
// (20,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M5(ref delegate*<string?> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("ptr").WithLocation(20, 26),
// (21,44): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string?> M6() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M6").WithLocation(21, 44),
// (22,26): warning CS8610: Nullability of reference types in type of parameter 'ptr' doesn't match overridden member.
// public override void M7(ref delegate*<string?, void> ptr) {}
Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M7").WithArguments("ptr").WithLocation(22, 26),
// (23,50): warning CS8609: Nullability of reference types in return type doesn't match overridden member.
// public override ref delegate*<string?, void> M8() => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M8").WithLocation(23, 50)
);
assertMethods(comp.SourceModule);
CompileAndVerify(comp, symbolValidator: assertMethods, verify: Verification.Skipped);
static void assertMethods(ModuleSymbol module)
{
var derived = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
assertMethod(derived, "M1", "void Derived.M1(ref delegate*<System.String!> ptr)");
assertMethod(derived, "M2", "ref delegate*<System.String!> Derived.M2()");
assertMethod(derived, "M3", "void Derived.M3(ref delegate*<System.String!, System.Void> ptr)");
assertMethod(derived, "M4", "ref delegate*<System.String!, System.Void> Derived.M4()");
assertMethod(derived, "M5", "void Derived.M5(ref delegate*<System.String?> ptr)");
assertMethod(derived, "M6", "ref delegate*<System.String?> Derived.M6()");
assertMethod(derived, "M7", "void Derived.M7(ref delegate*<System.String?, System.Void> ptr)");
assertMethod(derived, "M8", "ref delegate*<System.String?, System.Void> Derived.M8()");
}
static void assertMethod(NamedTypeSymbol derived, string methodName, string expectedSignature)
{
var m = derived.GetMember<MethodSymbol>(methodName);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, m.ToTestDisplayString(includeNonNullable: true));
}
}
[Fact]
public void Override_SingleDimensionArraySizesInMetadata()
{
var il = @"
.class public auto ansi abstract beforefieldinit Base
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig newslot abstract virtual
void M1 (method void *(int32[0...]) param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method void *(int32[0...]) M2 () cil managed
{
}
.method public hidebysig newslot abstract virtual
void M3 (method int32[0...] *() param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method int32[0...] *() M4 () cil managed
{
}
.method family hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}";
var source = @"
unsafe class Derived : Base
{
public override void M1(delegate*<int[], void> param) => throw null;
public override delegate*<int[], void> M2() => throw null;
public override void M3(delegate*<int[]> param) => throw null;
public override delegate*<int[]> M4() => throw null;
}";
var comp = CreateCompilationWithFunctionPointersAndIl(source, il);
comp.VerifyDiagnostics(
// (2,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.M1(delegate*<int[*], void>)'
// unsafe class Derived : Base
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.M1(delegate*<int[*], void>)").WithLocation(2, 14),
// (2,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.M3(delegate*<int[*]>)'
// unsafe class Derived : Base
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.M3(delegate*<int[*]>)").WithLocation(2, 14),
// (4,26): error CS0115: 'Derived.M1(delegate*<int[], void>)': no suitable method found to override
// public override void M1(delegate*<int[], void> param) => throw null;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("Derived.M1(delegate*<int[], void>)").WithLocation(4, 26),
// (5,44): error CS0508: 'Derived.M2()': return type must be 'delegate*<int[*], void>' to match overridden member 'Base.M2()'
// public override delegate*<int[], void> M2() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("Derived.M2()", "Base.M2()", "delegate*<int[*], void>").WithLocation(5, 44),
// (6,26): error CS0115: 'Derived.M3(delegate*<int[]>)': no suitable method found to override
// public override void M3(delegate*<int[]> param) => throw null;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("Derived.M3(delegate*<int[]>)").WithLocation(6, 26),
// (7,38): error CS0508: 'Derived.M4()': return type must be 'delegate*<int[*]>' to match overridden member 'Base.M4()'
// public override delegate*<int[]> M4() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("Derived.M4()", "Base.M4()", "delegate*<int[*]>").WithLocation(7, 38)
);
}
[Fact]
public void Override_ArraySizesInMetadata()
{
var il = @"
.class public auto ansi abstract beforefieldinit Base
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig newslot abstract virtual
void M1 (method void *(int32[5...5,2...4]) param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method void *(int32[5...5,2...4]) M2 () cil managed
{
}
.method public hidebysig newslot abstract virtual
void M3 (method int32[5...5,2...4] *() param) cil managed
{
}
.method public hidebysig newslot abstract virtual
method int32[5...5,2...4] *() M4 () cil managed
{
}
.method family hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}";
var source = @"
using System;
unsafe class Derived : Base
{
private static void MultiDimensionParamFunc(int[,] param) { }
private static int[,] MultiDimensionReturnFunc() => null;
public override void M1(delegate*<int[,], void> param)
{
Console.WriteLine(""Multi-dimension array param as param"");
param(null);
}
public override delegate*<int[,], void> M2()
{
Console.WriteLine(""Multi-dimension array param as return"");
return &MultiDimensionParamFunc;
}
public override void M3(delegate*<int[,]> param)
{
Console.WriteLine(""Multi-dimension array return as param"");
_ = param();
}
public override delegate*<int[,]> M4()
{
Console.WriteLine(""Multi-dimension array return as return"");
return &MultiDimensionReturnFunc;
}
public static void Main()
{
var d = new Derived();
d.M1(&MultiDimensionParamFunc);
var ptr1 = d.M2();
ptr1(null);
d.M3(&MultiDimensionReturnFunc);
var ptr2 = d.M4();
_ = ptr2();
}
}";
var verifier = CompileAndVerifyFunctionPointersWithIl(source, il, expectedOutput: @"
Multi-dimension array param as param
Multi-dimension array param as return
Multi-dimension array return as param
Multi-dimension array return as return
");
verifier.VerifyIL("Derived.M1", expectedIL: @"
{
// Code size 20 (0x14)
.maxstack 2
.locals init (delegate*<int[,], void> V_0)
IL_0000: ldstr ""Multi-dimension array param as param""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldarg.1
IL_000b: stloc.0
IL_000c: ldnull
IL_000d: ldloc.0
IL_000e: calli ""delegate*<int[,], void>""
IL_0013: ret
}
");
verifier.VerifyIL("Derived.M2", expectedIL: @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldstr ""Multi-dimension array param as return""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldftn ""void Derived.MultiDimensionParamFunc(int[,])""
IL_0010: ret
}
");
verifier.VerifyIL("Derived.M3", expectedIL: @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldstr ""Multi-dimension array return as param""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldarg.1
IL_000b: calli ""delegate*<int[,]>""
IL_0010: pop
IL_0011: ret
}
");
verifier.VerifyIL("Derived.M4", expectedIL: @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldstr ""Multi-dimension array return as return""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ldftn ""int[,] Derived.MultiDimensionReturnFunc()""
IL_0010: ret
}
");
verifier.VerifyIL("Derived.Main", expectedIL: @"
{
// Code size 55 (0x37)
.maxstack 3
.locals init (delegate*<int[,], void> V_0)
IL_0000: newobj ""Derived..ctor()""
IL_0005: dup
IL_0006: ldftn ""void Derived.MultiDimensionParamFunc(int[,])""
IL_000c: callvirt ""void Base.M1(delegate*<int[,], void>)""
IL_0011: dup
IL_0012: callvirt ""delegate*<int[,], void> Base.M2()""
IL_0017: stloc.0
IL_0018: ldnull
IL_0019: ldloc.0
IL_001a: calli ""delegate*<int[,], void>""
IL_001f: dup
IL_0020: ldftn ""int[,] Derived.MultiDimensionReturnFunc()""
IL_0026: callvirt ""void Base.M3(delegate*<int[,]>)""
IL_002b: callvirt ""delegate*<int[,]> Base.M4()""
IL_0030: calli ""delegate*<int[,]>""
IL_0035: pop
IL_0036: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var m1 = comp.GetMember<MethodSymbol>("Derived.M1");
var m2 = comp.GetMember<MethodSymbol>("Derived.M2");
var m3 = comp.GetMember<MethodSymbol>("Derived.M3");
var m4 = comp.GetMember<MethodSymbol>("Derived.M4");
var funcPtr = (FunctionPointerTypeSymbol)m1.Parameters.Single().Type;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.Parameters.Single().Type);
funcPtr = (FunctionPointerTypeSymbol)m2.ReturnType;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.Parameters.Single().Type);
funcPtr = (FunctionPointerTypeSymbol)m3.Parameters.Single().Type;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.ReturnType);
funcPtr = (FunctionPointerTypeSymbol)m4.ReturnType;
CommonVerifyFunctionPointer(funcPtr);
verifyArray(funcPtr.Signature.ReturnType);
static void verifyArray(TypeSymbol type)
{
var array = (ArrayTypeSymbol)type;
Assert.False(array.IsSZArray);
Assert.Equal(2, array.Rank);
Assert.Equal(5, array.LowerBounds[0]);
Assert.Equal(1, array.Sizes[0]);
Assert.Equal(2, array.LowerBounds[1]);
Assert.Equal(3, array.Sizes[1]);
}
}
[Fact]
public void NullableUsageWarnings()
{
var comp = CreateCompilationWithFunctionPointers(@"
#nullable enable
unsafe public class C
{
static void M1(delegate*<string, string?, string?> ptr1)
{
_ = ptr1(null, null);
_ = ptr1("""", null).ToString();
delegate*<string?, string?, string?> ptr2 = ptr1;
delegate*<string, string?, string> ptr3 = ptr1;
}
static void M2(delegate*<ref string, ref string> ptr1)
{
string? str1 = null;
ptr1(ref str1);
string str2 = """";
ref string? str3 = ref ptr1(ref str2);
delegate*<ref string?, ref string> ptr2 = ptr1;
delegate*<ref string, ref string?> ptr3 = ptr1;
}
}
");
comp.VerifyDiagnostics(
// (7,18): warning CS8625: Cannot convert null literal to non-nullable reference type.
// _ = ptr1(null, null);
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 18),
// (8,13): warning CS8602: Dereference of a possibly null reference.
// _ = ptr1("", null).ToString();
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"ptr1("""", null)").WithLocation(8, 13),
// (9,53): warning CS8619: Nullability of reference types in value of type 'delegate*<string, string?, string?>' doesn't match target type 'delegate*<string?, string?, string?>'.
// delegate*<string?, string?, string?> ptr2 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<string, string?, string?>", "delegate*<string?, string?, string?>").WithLocation(9, 53),
// (10,51): warning CS8619: Nullability of reference types in value of type 'delegate*<string, string?, string?>' doesn't match target type 'delegate*<string, string?, string>'.
// delegate*<string, string?, string> ptr3 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<string, string?, string?>", "delegate*<string, string?, string>").WithLocation(10, 51),
// (16,18): warning CS8601: Possible null reference assignment.
// ptr1(ref str1);
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "str1").WithLocation(16, 18),
// (18,32): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'.
// ref string? str3 = ref ptr1(ref str2);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1(ref str2)").WithArguments("string", "string?").WithLocation(18, 32),
// (19,51): warning CS8619: Nullability of reference types in value of type 'delegate*<ref string, ref string>' doesn't match target type 'delegate*<ref string?, ref string>'.
// delegate*<ref string?, ref string> ptr2 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<ref string, ref string>", "delegate*<ref string?, ref string>").WithLocation(19, 51),
// (20,51): warning CS8619: Nullability of reference types in value of type 'delegate*<ref string, ref string>' doesn't match target type 'delegate*<ref string, ref string?>'.
// delegate*<ref string, ref string?> ptr3 = ptr1;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ptr1").WithArguments("delegate*<ref string, ref string>", "delegate*<ref string, ref string?>").WithLocation(20, 51)
);
}
[ConditionalFact(typeof(CoreClrOnly))]
public void SpanInArgumentAndReturn()
{
var comp = CompileAndVerifyFunctionPointers(@"
using System;
public class C
{
static char[] chars = new[] { '1', '2', '3', '4' };
static Span<char> ChopSpan(Span<char> span) => span[..^1];
public static unsafe void Main()
{
delegate*<Span<char>, Span<char>> ptr = &ChopSpan;
Console.Write(new string(ptr(chars)));
}
}
", targetFramework: TargetFramework.NetCoreApp, expectedOutput: "123");
comp.VerifyIL("C.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (delegate*<System.Span<char>, System.Span<char>> V_0)
IL_0000: ldftn ""System.Span<char> C.ChopSpan(System.Span<char>)""
IL_0006: stloc.0
IL_0007: ldsfld ""char[] C.chars""
IL_000c: call ""System.Span<char> System.Span<char>.op_Implicit(char[])""
IL_0011: ldloc.0
IL_0012: calli ""delegate*<System.Span<char>, System.Span<char>>""
IL_0017: call ""System.ReadOnlySpan<char> System.Span<char>.op_Implicit(System.Span<char>)""
IL_001c: newobj ""string..ctor(System.ReadOnlySpan<char>)""
IL_0021: call ""void System.Console.Write(string)""
IL_0026: ret
}
");
}
[Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
public void LocalFunction_ValidStatic()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class FunctionPointer
{
public static void Main()
{
delegate*<void> a = &local;
a();
static void local() => System.Console.Write(""local"");
}
}
", expectedOutput: "local");
verifier.VerifyIL("FunctionPointer.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void FunctionPointer.<Main>g__local|0_0()""
IL_0006: calli ""delegate*<void>""
IL_000b: ret
}
");
}
[Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
public void LocalFunction_ValidStatic_NestedInLocalFunction()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class FunctionPointer
{
public static void Main()
{
local(true);
static void local(bool invoke)
{
if (invoke)
{
delegate*<bool, void> ptr = &local;
ptr(false);
}
else
{
System.Console.Write(""local"");
}
}
}
}
", expectedOutput: "local");
verifier.VerifyIL("FunctionPointer.<Main>g__local|0_0(bool)", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (delegate*<bool, void> V_0)
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0012
IL_0003: ldftn ""void FunctionPointer.<Main>g__local|0_0(bool)""
IL_0009: stloc.0
IL_000a: ldc.i4.0
IL_000b: ldloc.0
IL_000c: calli ""delegate*<bool, void>""
IL_0011: ret
IL_0012: ldstr ""local""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: ret
}
");
}
[Fact]
public void LocalFunction_ValidStatic_NestedInLambda()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe class C
{
public static void Main()
{
int capture = 1;
System.Action _ = () =>
{
System.Console.Write(capture); // Just to ensure that this is emitted as a capture
delegate*<void> ptr = &local;
ptr();
static void local() => System.Console.Write(""local"");
};
_();
}
}
", expectedOutput: "1local");
verifier.VerifyIL("C.<>c__DisplayClass0_0.<Main>b__0()", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.capture""
IL_0006: call ""void System.Console.Write(int)""
IL_000b: ldftn ""void C.<Main>g__local|0_1()""
IL_0011: calli ""delegate*<void>""
IL_0016: ret
}
");
}
[Fact, WorkItem(45447, "https://github.com/dotnet/roslyn/issues/45447")]
public void LocalFunction_InvalidNonStatic()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class FunctionPointer
{
public static void M()
{
int local = 1;
delegate*<void> first = &noCaptures;
delegate*<void> second = &capturesLocal;
void noCaptures() { }
void capturesLocal() { local++; }
}
}");
comp.VerifyDiagnostics(
// (8,34): error CS8759: Cannot create a function pointer for 'noCaptures()' because it is not a static method
// delegate*<void> first = &noCaptures;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "noCaptures").WithArguments("noCaptures()").WithLocation(8, 34),
// (9,35): error CS8759: Cannot create a function pointer for 'capturesLocal()' because it is not a static method
// delegate*<void> second = &capturesLocal;
Diagnostic(ErrorCode.ERR_FuncPtrMethMustBeStatic, "capturesLocal").WithArguments("capturesLocal()").WithLocation(9, 35)
);
}
[Fact, WorkItem(45418, "https://github.com/dotnet/roslyn/issues/45418")]
public void RefMismatchInCall()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Test
{
void M1(delegate*<ref string, void> param1)
{
param1(out var l);
string s = null;
param1(s);
param1(in s);
}
void M2(delegate*<in string, void> param2)
{
param2(out var l);
string s = null;
param2(s);
param2(ref s);
}
void M3(delegate*<out string, void> param3)
{
string s = null;
param3(s);
param3(ref s);
param3(in s);
}
void M4(delegate*<string, void> param4)
{
param4(out var l);
string s = null;
param4(ref s);
param4(in s);
}
}");
comp.VerifyDiagnostics(
// (6,20): error CS1620: Argument 1 must be passed with the 'ref' keyword
// param1(out var l);
Diagnostic(ErrorCode.ERR_BadArgRef, "var l").WithArguments("1", "ref").WithLocation(6, 20),
// (8,16): error CS1620: Argument 1 must be passed with the 'ref' keyword
// param1(s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "ref").WithLocation(8, 16),
// (9,19): error CS1620: Argument 1 must be passed with the 'ref' keyword
// param1(in s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "ref").WithLocation(9, 19),
// (14,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// param2(out var l);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var l").WithArguments("1", "out").WithLocation(14, 20),
// (17,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword
// param2(ref s);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "ref").WithLocation(17, 20),
// (23,16): error CS1620: Argument 1 must be passed with the 'out' keyword
// param3(s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(23, 16),
// (24,20): error CS1620: Argument 1 must be passed with the 'out' keyword
// param3(ref s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(24, 20),
// (25,19): error CS1620: Argument 1 must be passed with the 'out' keyword
// param3(in s);
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(25, 19),
// (30,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// param4(out var l);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var l").WithArguments("1", "out").WithLocation(30, 20),
// (32,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword
// param4(ref s);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "ref").WithLocation(32, 20),
// (33,19): error CS1615: Argument 1 may not be passed with the 'in' keyword
// param4(in s);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "s").WithArguments("1", "in").WithLocation(33, 19)
);
}
[Fact]
public void MismatchedInferredLambdaReturn()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class C
{
public void M(delegate*<System.Func<string>, void> param)
{
param(a => a);
}
}");
comp.VerifyDiagnostics(
// (6,15): error CS1593: Delegate 'Func<string>' does not take 1 arguments
// param(a => a);
Diagnostic(ErrorCode.ERR_BadDelArgCount, "a => a").WithArguments("System.Func<string>", "1").WithLocation(6, 15)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
Assert.Equal("a => a", lambda.ToString());
var info = model.GetSymbolInfo(lambda);
var lambdaSymbol = (IMethodSymbol)info.Symbol!;
Assert.NotNull(lambdaSymbol);
Assert.Equal("System.String", lambdaSymbol.ReturnType.ToTestDisplayString(includeNonNullable: false));
Assert.True(lambdaSymbol.Parameters.Single().Type.IsErrorType());
}
[Fact, WorkItem(45418, "https://github.com/dotnet/roslyn/issues/45418")]
public void OutDeconstructionMismatch()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe class Test
{
void M1(delegate*<string, void> param1, object o)
{
param1(o is var (a, b));
param1(o is (var c, var d));
}
}", targetFramework: TargetFramework.Standard);
comp.VerifyDiagnostics(
// (6,25): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// param1(o is var (a, b));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a, b)").WithArguments("object", "Deconstruct").WithLocation(6, 25),
// (6,25): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// param1(o is var (a, b));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a, b)").WithArguments("object", "2").WithLocation(6, 25),
// (7,21): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// param1(o is (var c, var d));
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(var c, var d)").WithArguments("object", "Deconstruct").WithLocation(7, 21),
// (7,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// param1(o is (var c, var d));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(var c, var d)").WithArguments("object", "2").WithLocation(7, 21)
);
}
[Fact]
public void UnusedLoadNotLeftOnStack()
{
string source = @"
unsafe class FunctionPointer
{
public static void Main()
{
delegate*<void> ptr = &Main;
}
}
";
var verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "", options: TestOptions.UnsafeReleaseExe);
verifier.VerifyIL(@"FunctionPointer.Main", expectedIL: @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
");
verifier = CompileAndVerifyFunctionPointers(source, expectedOutput: "", options: TestOptions.UnsafeDebugExe);
verifier.VerifyIL("FunctionPointer.Main", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (delegate*<void> V_0) //ptr
IL_0000: nop
IL_0001: ldftn ""void FunctionPointer.Main()""
IL_0007: stloc.0
IL_0008: ret
}
");
}
[Fact]
public void UnmanagedOnUnsupportedRuntime()
{
var comp = CreateCompilationWithFunctionPointers(@"
#pragma warning disable CS0168 // Unused variable
class C
{
unsafe void M()
{
delegate* unmanaged<void> ptr1;
delegate* unmanaged[Stdcall, Thiscall]<void> ptr2;
}
}", targetFramework: TargetFramework.NetStandard20);
comp.VerifyDiagnostics(
// (7,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
// delegate* unmanaged<void> ptr1;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(7, 19),
// (8,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
// delegate* unmanaged[Stdcall, Thiscall]<void> ptr2;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(8, 19)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var functionPointerSyntaxes = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().ToArray();
Assert.Equal(2, functionPointerSyntaxes.Length);
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntaxes[0],
expectedSyntax: "delegate* unmanaged<void>",
expectedType: "delegate* unmanaged<System.Void>",
expectedSymbol: "delegate* unmanaged<System.Void>");
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntaxes[1],
expectedSyntax: "delegate* unmanaged[Stdcall, Thiscall]<void>",
expectedType: "delegate* unmanaged[Stdcall, Thiscall]<System.Void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvThiscall)>",
expectedSymbol: "delegate* unmanaged[Stdcall, Thiscall]<System.Void modopt(System.Runtime.CompilerServices.CallConvStdcall) modopt(System.Runtime.CompilerServices.CallConvThiscall)>");
}
[Fact]
public void NonPublicCallingConventionType()
{
string source1 = @"
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public class String { }
namespace Runtime.CompilerServices
{
internal class CallConvTest {}
public static class RuntimeFeature
{
public const string UnmanagedSignatureCallingConvention = nameof(UnmanagedSignatureCallingConvention);
}
}
}
";
string source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
void M()
{
delegate* unmanaged[Test]<void> ptr = null;
}
}
";
var allInCoreLib = CreateEmptyCompilation(source1 + source2, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
allInCoreLib.VerifyDiagnostics(
// (23,29): error CS8891: Type 'CallConvTest' must be public to be used as a calling convention.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeMustBePublic, "Test").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(23, 29)
);
var tree = allInCoreLib.SyntaxTrees[0];
var model = allInCoreLib.GetSemanticModel(tree);
var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>");
var coreLib = CreateEmptyCompilation(source1);
coreLib.VerifyDiagnostics();
var comp1 = CreateEmptyCompilation(source2, references: new[] { coreLib.EmitToImageReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
comp1.VerifyDiagnostics(
// (7,29): error CS8891: Type 'CallConvTest' must be public to be used as a calling convention.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeMustBePublic, "Test").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(7, 29)
);
tree = comp1.SyntaxTrees[0];
model = comp1.GetSemanticModel(tree);
functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest)>");
}
[Fact]
public void GenericCallingConventionType()
{
string source1 = @"
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public class String { }
namespace Runtime.CompilerServices
{
public class CallConvTest<T> {}
public static class RuntimeFeature
{
public const string UnmanagedSignatureCallingConvention = nameof(UnmanagedSignatureCallingConvention);
}
}
}
";
string source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
void M()
{
delegate* unmanaged[Test]<void> ptr = null;
}
}
";
var allInCoreLib = CreateEmptyCompilation(source1 + source2, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
allInCoreLib.VerifyDiagnostics(
// (23,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(23, 29)
);
var tree = allInCoreLib.SyntaxTrees[0];
var model = allInCoreLib.GetSemanticModel(tree);
var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var coreLib = CreateEmptyCompilation(source1);
coreLib.VerifyDiagnostics();
var comp1 = CreateEmptyCompilation(source2, references: new[] { coreLib.EmitToImageReference() }, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
comp1.VerifyDiagnostics(
// (7,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr = null;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(7, 29)
);
tree = comp1.SyntaxTrees[0];
model = comp1.GetSemanticModel(tree);
functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var @string = comp1.GetSpecialType(SpecialType.System_String);
var testMod = CSharpCustomModifier.CreateOptional(comp1.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvTest`1"));
var funcPtr = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp1);
var funcPtrRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
parameterRefCustomModifiers: default, returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
compilation: comp1);
var funcPtrWithTestOnReturn = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string, customModifiers: ImmutableArray.Create(testMod)), refCustomModifiers: default,
parameterRefCustomModifiers: default, returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
compilation: comp1);
var funcPtrWithTestOnRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: ImmutableArray.Create(testMod),
parameterRefCustomModifiers: default, returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
compilation: comp1);
Assert.Empty(funcPtrWithTestOnReturn.Signature.GetCallingConventionModifiers());
Assert.Empty(funcPtrWithTestOnRef.Signature.GetCallingConventionModifiers());
Assert.True(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.ConsiderEverything));
Assert.True(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.ConsiderEverything));
}
[Fact]
public void ConventionDefinedInWrongAssembly()
{
var source1 = @"
namespace System.Runtime.CompilerServices
{
public class CallConvTest { }
}
";
var source2 = @"
#pragma warning disable CS0168 // Unused local
unsafe class C
{
static void M()
{
delegate* unmanaged[Test]<void> ptr;
}
}
";
var comp1 = CreateCompilationWithFunctionPointers(source1 + source2);
comp1.VerifyDiagnostics(
// (12,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(12, 29)
);
var tree = comp1.SyntaxTrees[0];
var model = comp1.GetSemanticModel(tree);
var functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var reference = CreateCompilation(source1);
var comp2 = CreateCompilationWithFunctionPointers(source2, new[] { reference.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (7,29): error CS8890: Type 'CallConvTest' is not defined.
// delegate* unmanaged[Test]<void> ptr;
Diagnostic(ErrorCode.ERR_TypeNotFound, "Test").WithArguments("CallConvTest").WithLocation(7, 29)
);
tree = comp2.SyntaxTrees[0];
model = comp2.GetSemanticModel(tree);
functionPointerSyntax = tree.GetRoot().DescendantNodes().OfType<FunctionPointerTypeSyntax>().Single();
VerifyFunctionPointerSemanticInfo(model, functionPointerSyntax,
expectedSyntax: "delegate* unmanaged[Test]<void>",
expectedType: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>",
expectedSymbol: "delegate* unmanaged[Test]<System.Void modopt(System.Runtime.CompilerServices.CallConvTest[missing])>");
var @string = comp2.GetSpecialType(SpecialType.System_String);
var testMod = CSharpCustomModifier.CreateOptional(comp2.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvTest"));
var funcPtr = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
var funcPtrRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: default,
returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
var funcPtrWithTestOnReturn = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string, customModifiers: ImmutableArray.Create(testMod)), refCustomModifiers: default,
returnRefKind: RefKind.None, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
var funcPtrWithTestOnRef = FunctionPointerTypeSymbol.CreateFromPartsForTests(
CallingConvention.Unmanaged, TypeWithAnnotations.Create(@string), refCustomModifiers: ImmutableArray.Create(testMod),
returnRefKind: RefKind.Ref, parameterTypes: ImmutableArray<TypeWithAnnotations>.Empty, parameterRefKinds: ImmutableArray<RefKind>.Empty,
parameterRefCustomModifiers: default, compilation: comp2);
Assert.Empty(funcPtrWithTestOnReturn.Signature.GetCallingConventionModifiers());
Assert.Empty(funcPtrWithTestOnRef.Signature.GetCallingConventionModifiers());
Assert.True(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtr.Equals(funcPtrWithTestOnReturn, TypeCompareKind.ConsiderEverything));
Assert.True(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds));
Assert.False(funcPtrRef.Equals(funcPtrWithTestOnRef, TypeCompareKind.ConsiderEverything));
}
private const string UnmanagedCallersOnlyAttribute = @"
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public Type[] CallConvs;
public string EntryPoint;
}
}
";
private const string UnmanagedCallersOnlyAttributeIl = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute
extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
}
}
";
[Fact]
public void UnmanagedCallersOnlyRequiresStatic()
{
var comp = CreateCompilation(new[] { @"
#pragma warning disable 8321 // Unreferenced local function
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
void M1() {}
public void M2()
{
[UnmanagedCallersOnly]
void local() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6),
// (11,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(11, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyAllowedOnStatics()
{
var comp = CreateCompilation(new[] { @"
#pragma warning disable 8321 // Unreferenced local function
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
static void M1() {}
public void M2()
{
[UnmanagedCallersOnly]
static void local() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustComeFromCorrectNamespace()
{
var comp = CreateEmptyCompilation(new[] { @"
using System.Runtime.InteropServices;
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public abstract partial class Enum : ValueType {}
public class String { }
public struct Boolean { }
public struct Int32 { }
public class Type { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) {}
public bool Inherited { get; set; }
}
public enum AttributeTargets { Method = 0x0040, }
}
class CallConvTest
{
}
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (26,6): error CS8893: 'CallConvTest' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })").WithArguments("CallConvTest").WithLocation(26, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustNotBeNestedType()
{
var comp = CreateEmptyCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public abstract partial class Enum : ValueType {}
public class String { }
public struct Boolean { }
public struct Int32 { }
public class Type { }
public class Attribute { }
public class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn) {}
public bool Inherited { get; set; }
}
public enum AttributeTargets { Method = 0x0040, }
namespace Runtime.CompilerServices
{
public class CallConvTestA
{
public class CallConvTestB { }
}
}
}
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (31,6): error CS8893: 'CallConvTestA.CallConvTestB' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTestA.CallConvTestB) })").WithArguments("System.Runtime.CompilerServices.CallConvTestA.CallConvTestB").WithLocation(31, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustComeFromCorelib()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices
{
class CallConvTest
{
}
}
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,6): error CS8893: 'CallConvTest' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvTest) })").WithArguments("System.Runtime.CompilerServices.CallConvTest").WithLocation(12, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsMustStartWithCallConv()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(ExtensionAttribute) })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,6): error CS8893: 'ExtensionAttribute' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.ExtensionAttribute) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(ExtensionAttribute) })").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(6, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvNull_InSource()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new System.Type[] { null })]
static void M() {}
unsafe static void M1()
{
delegate* unmanaged<void> ptr = &M;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'null' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new System.Type[] { null })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new System.Type[] { null })").WithArguments("null").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvNull_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static void M () cil managed
{
// [UnmanagedCallersOnly(CallConvs = new Type[] { null })]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 01 00 53 1d 50 09 43 61 6c 6c 43 6f 6e 76
73 01 00 00 00 ff
)
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
class D
{
unsafe static void M1()
{
C.M();
delegate* unmanaged<void> ptr = &C.M;
}
}
", il);
comp.VerifyDiagnostics(
// (6,9): error CS8901: 'C.M()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// C.M();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M()").WithArguments("C.M()").WithLocation(6, 9)
);
var c = comp.GetTypeByMetadataName("C");
var m1 = c.GetMethod("M");
var unmanagedData = m1.GetUnmanagedCallersOnlyAttributeData(forceComplete: true);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.Uninitialized);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound);
Assert.Empty(unmanagedData!.CallingConventionTypes);
}
[Fact]
public void UnmanagedCallersOnlyCallConvDefault()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new System.Type[] { default })]
static void M() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'null' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new System.Type[] { default })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new System.Type[] { default })").WithArguments("null").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_Errors()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
static string M1() => throw null;
[UnmanagedCallersOnly]
static void M2(object o) {}
[UnmanagedCallersOnly]
static T M3<T>() => throw null;
[UnmanagedCallersOnly]
static void M4<T>(T t) {}
[UnmanagedCallersOnly]
static T M5<T>() where T : struct => throw null;
[UnmanagedCallersOnly]
static void M6<T>(T t) where T : struct {}
[UnmanagedCallersOnly]
static T M7<T>() where T : unmanaged => throw null;
[UnmanagedCallersOnly]
static void M8<T>(T t) where T : unmanaged {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,12): error CS8894: Cannot use 'string' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static string M1() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "string").WithArguments("string", "return").WithLocation(6, 12),
// (9,20): error CS8894: Cannot use 'object' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M2(object o) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "object o").WithArguments("object", "parameter").WithLocation(9, 20),
// (11,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(11, 6),
// (12,12): error CS8894: Cannot use 'T' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static T M3<T>() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T").WithArguments("T", "return").WithLocation(12, 12),
// (14,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(14, 6),
// (15,23): error CS8894: Cannot use 'T' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M4<T>(T t) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T t").WithArguments("T", "parameter").WithLocation(15, 23),
// (17,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(17, 6),
// (18,12): error CS8894: Cannot use 'T' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static T M5<T>() where T : struct => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T").WithArguments("T", "return").WithLocation(18, 12),
// (20,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(20, 6),
// (21,23): error CS8894: Cannot use 'T' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M6<T>(T t) where T : struct {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "T t").WithArguments("T", "parameter").WithLocation(21, 23),
// (23,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 6),
// (26,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(26, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_Valid()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
#pragma warning disable CS0169 // unused private field
struct S
{
private int _field;
}
class C
{
[UnmanagedCallersOnly]
static int M1() => throw null;
[UnmanagedCallersOnly]
static void M2(int o) {}
[UnmanagedCallersOnly]
static S M3() => throw null;
[UnmanagedCallersOnly]
public static void M4(S s) {}
[UnmanagedCallersOnly]
static int? M5() => throw null;
[UnmanagedCallersOnly]
static void M6(int? o) {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_MethodWithGenericParameter()
{
var comp = CreateCompilation(new[] { @"
#pragma warning disable CS8321 // Unused local function
using System.Runtime.InteropServices;
public struct S<T> where T : unmanaged
{
public T t;
}
class C
{
[UnmanagedCallersOnly] // 1
static S<T> M1<T>() where T : unmanaged => throw null;
[UnmanagedCallersOnly] // 2
static void M2<T>(S<T> o) where T : unmanaged {}
static void M3<T>()
{
[UnmanagedCallersOnly] // 3
static void local1() {}
static void local2()
{
[UnmanagedCallersOnly] // 4
static void local3() { }
}
System.Action a = () =>
{
[UnmanagedCallersOnly] // 5
static void local4() { }
};
}
static void M4()
{
[UnmanagedCallersOnly] // 6
static void local2<T>() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 1
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(10, 6),
// (13,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 2
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(13, 6),
// (18,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 3
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(18, 10),
// (23,14): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 4
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 14),
// (29,14): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 5
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(29, 14),
// (36,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 6
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(36, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiredUnmanagedTypes_MethodWithGenericParameter_InIl()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C extends [mscorlib]System.Object
{
.method public hidebysig static void M<T> () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
unsafe
{
delegate* unmanaged<void> ptr = C.M<int>;
}", il, options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (4,37): error CS0570: 'C.M<T>()' is not supported by the language
// delegate* unmanaged<void> ptr = C.M<int>;
Diagnostic(ErrorCode.ERR_BindToBogus, "C.M<int>").WithArguments("C.M<T>()").WithLocation(4, 37)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeWithGenericParameter()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T> where T : unmanaged
{
public T t;
}
class C<T> where T : unmanaged
{
[UnmanagedCallersOnly] // 1
static S<T> M1() => throw null;
[UnmanagedCallersOnly] // 2
static void M2(S<T> o) {}
[UnmanagedCallersOnly] // 3
static S<int> M3() => throw null;
[UnmanagedCallersOnly] // 4
static void M4(S<int> o) {}
class C2
{
[UnmanagedCallersOnly] // 5
static void M5() {}
}
struct S2
{
[UnmanagedCallersOnly] // 6
static void M6() {}
}
#pragma warning disable CS8321 // Unused local function
static void M7()
{
[UnmanagedCallersOnly] // 7
static void local1() { }
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (9,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 1
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(9, 6),
// (12,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 2
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(12, 6),
// (15,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 3
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(15, 6),
// (18,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 4
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(18, 6),
// (23,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 5
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(23, 10),
// (29,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 6
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(29, 10),
// (36,10): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly] // 7
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(36, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeWithGenericParameter_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Object
{
// Nested Types
.class nested public auto ansi beforefieldinit NestedClass<T> extends [mscorlib]System.Object
{
.method public hidebysig static void M2 () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
.class nested public sequential ansi sealed beforefieldinit NestedStruct<T> extends [mscorlib]System.ValueType
{
.pack 0
.size 1
// Methods
.method public hidebysig static void M3 () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
.method public hidebysig static void M1 () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
unsafe
{
delegate* unmanaged<void> ptr1 = &C<int>.M1;
delegate* unmanaged<void> ptr2 = &C<int>.NestedClass.M2;
delegate* unmanaged<void> ptr3 = &C<int>.NestedStruct.M3;
}
", il, options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (4,39): error CS0570: 'C<T>.M1()' is not supported by the language
// delegate* unmanaged<void> ptr1 = &C<int>.M1;
Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.M1").WithArguments("C<T>.M1()").WithLocation(4, 39),
// (5,39): error CS0570: 'C<T>.NestedClass.M2()' is not supported by the language
// delegate* unmanaged<void> ptr2 = &C<int>.NestedClass.M2;
Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.NestedClass.M2").WithArguments("C<T>.NestedClass.M2()").WithLocation(5, 39),
// (6,39): error CS0570: 'C<T>.NestedStruct.M3()' is not supported by the language
// delegate* unmanaged<void> ptr3 = &C<int>.NestedStruct.M3;
Diagnostic(ErrorCode.ERR_BindToBogus, "C<int>.NestedStruct.M3").WithArguments("C<T>.NestedStruct.M3()").WithLocation(6, 39)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_TypeAndMethodWithGenericParameter()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C<T1>
{
[UnmanagedCallersOnly]
static void M<T2>() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8895: Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric, "UnmanagedCallersOnly").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_StructWithGenericParameters_1()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T>
{
public T t;
}
class C
{
[UnmanagedCallersOnly]
static S<int> M1() => throw null;
[UnmanagedCallersOnly]
static void M2(S<int> o) {}
[UnmanagedCallersOnly]
static S<S<int>> M2() => throw null;
[UnmanagedCallersOnly]
static void M3(S<S<int>> o) {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyRequiresUnmanagedTypes_StructWithGenericParameters_2()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S<T>
{
public T t;
}
class C
{
[UnmanagedCallersOnly]
static S<object> M1() => throw null;
[UnmanagedCallersOnly]
static void M2(S<object> o) {}
[UnmanagedCallersOnly]
static S<S<object>> M2() => throw null;
[UnmanagedCallersOnly]
static void M3(S<S<object>> o) {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,12): error CS8894: Cannot use 'S<object>' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static S<object> M1() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<object>").WithArguments("S<object>", "return").WithLocation(10, 12),
// (13,20): error CS8894: Cannot use 'S<object>' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M2(S<object> o) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<object> o").WithArguments("S<object>", "parameter").WithLocation(13, 20),
// (16,12): error CS8894: Cannot use 'S<S<object>>' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// static S<S<object>> M2() => throw null;
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<S<object>>").WithArguments("S<S<object>>", "return").WithLocation(16, 12),
// (19,20): error CS8894: Cannot use 'S<S<object>>' as a parameter type on a method attributed with 'UnmanagedCallersOnly'.
// static void M3(S<S<object>> o) {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "S<S<object>> o").WithArguments("S<S<object>>", "parameter").WithLocation(19, 20)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCallMethodDirectly()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M1() { }
public static unsafe void M2()
{
M1();
delegate*<void> p1 = &M1;
delegate* unmanaged<void> p2 = &M1;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "M1()", isSuppressed: false).WithArguments("C.M1()").WithLocation(10, 9),
// (11,31): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("C.M1()", "Default").WithLocation(11, 31)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCallMethodDirectlyWithAlias()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
using E = D;
public class C
{
public static unsafe void M2()
{
E.M1();
delegate*<void> p1 = &E.M1;
delegate* unmanaged<void> p2 = &E.M1;
}
}
public class D
{
[UnmanagedCallersOnly]
public static void M1() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'D.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// E.M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "E.M1()", isSuppressed: false).WithArguments("D.M1()").WithLocation(8, 9),
// (9,31): error CS8786: Calling convention of 'D.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &E.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "E.M1", isSuppressed: false).WithArguments("D.M1()", "Default").WithLocation(9, 31)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCallMethodDirectlyWithUsingStatic()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
using static D;
public class C
{
public static unsafe void M2()
{
M1();
delegate*<void> p1 = &M1;
delegate* unmanaged<void> p2 = &M1;
}
}
public class D
{
[UnmanagedCallersOnly]
public static void M1() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'D.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "M1()", isSuppressed: false).WithArguments("D.M1()").WithLocation(8, 9),
// (9,31): error CS8786: Calling convention of 'D.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("D.M1()", "Default").WithLocation(9, 31)
);
}
[Fact]
public void UnmanagedCallersOnlyReferencedFromMetadata()
{
var comp0 = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M1() { }
}
", UnmanagedCallersOnlyAttribute });
validate(comp0.ToMetadataReference());
validate(comp0.EmitToImageReference());
static void validate(MetadataReference reference)
{
var comp1 = CreateCompilationWithFunctionPointers(@"
class D
{
public static unsafe void M2()
{
C.M1();
delegate*<void> p1 = &C.M1;
delegate* unmanaged<void> p2 = &C.M1;
}
}
", references: new[] { reference }, targetFramework: TargetFramework.Standard);
comp1.VerifyDiagnostics(
// (6,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// C.M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M1()").WithArguments("C.M1()").WithLocation(6, 9),
// (7,31): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Default'.
// delegate*<void> p1 = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1", isSuppressed: false).WithArguments("C.M1()", "Default").WithLocation(7, 31),
// (8,19): error CS8889: The target runtime doesn't support extensible or runtime-environment default calling conventions.
// delegate* unmanaged<void> p2 = &C.M1;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv, "unmanaged").WithLocation(8, 19)
);
}
}
[Fact]
public void UnmanagedCallersOnlyReferencedFromMetadata_BadTypeInList()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static
void M1 () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 01 00 53 1d 50 09 43 61 6c 6c 43 6f 6e 76
73 01 00 00 00 68 53 79 73 74 65 6d 2e 4f 62 6a
65 63 74 2c 20 53 79 73 74 65 6d 2e 50 72 69 76
61 74 65 2e 43 6f 72 65 4c 69 62 2c 20 56 65 72
73 69 6f 6e 3d 34 2e 30 2e 30 2e 30 2c 20 43 75
6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50
75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 37 63
65 63 38 35 64 37 62 65 61 37 37 39 38 65
)
ret
}
}";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
class D
{
public unsafe static void M2()
{
C.M1();
delegate* unmanaged<void> ptr = &C.M1;
}
}
", il);
comp.VerifyDiagnostics(
// (6,9): error CS8901: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// C.M1();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "C.M1()").WithArguments("C.M1()").WithLocation(6, 9)
);
var c = comp.GetTypeByMetadataName("C");
var m1 = c.GetMethod("M1");
var unmanagedData = m1.GetUnmanagedCallersOnlyAttributeData(forceComplete: true);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.Uninitialized);
Assert.NotSame(unmanagedData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound);
Assert.Empty(unmanagedData!.CallingConventionTypes);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnInstanceMethod()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig
instance void M1 () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ret
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
c.M1();
}
}
", il);
comp.VerifyDiagnostics(
// (6,11): error CS0570: 'C.M1()' is not supported by the language
// c.M1();
Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("C.M1()").WithLocation(6, 11)
);
}
[Fact]
[WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")]
public void UnmanagedCallersOnlyDefinedOnConversion()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname static
int32 op_Implicit (
class C i
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
IL_0000: ldc.i4.0
IL_0001: ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
}
}
";
var comp = CreateCompilationWithIL(@"
class Test
{
void M(C x)
{
_ = (int)x;
}
}
", il);
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnProperty_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
static int Prop
{
[UnmanagedCallersOnly] get => throw null;
[UnmanagedCallersOnly] set => throw null;
}
static void M()
{
Prop = 1;
_ = Prop;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] get => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10),
// (8,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] set => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnProperty_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig specialname static
int32 get_Prop () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.method public hidebysig specialname static
void set_Prop (
int32 'value'
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.property int32 Prop()
{
.get int32 C::get_Prop()
.set void C::set_Prop(int32)
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2()
{
C.Prop = 1;
_ = C.Prop;
}
}
", il);
comp.VerifyDiagnostics(
// (6,11): error CS0570: 'C.Prop.set' is not supported by the language
// C.Prop = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.set").WithLocation(6, 11),
// (7,15): error CS0570: 'C.Prop.get' is not supported by the language
// _ = C.Prop;
Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.get").WithLocation(7, 15)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnPropertyRefReadonlyGetterAsLvalue_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
static ref int Prop { [UnmanagedCallersOnly] get => throw null; }
static void M()
{
Prop = 1;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,28): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// static int Prop { [UnmanagedCallersOnly] get {} }
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 28)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnPropertyRefReadonlyGetterAsLvalue_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig specialname static
int32& get_Prop () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
} // end of method C::get_Prop
// Properties
.property int32& Prop()
{
.get int32& C::get_Prop()
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2()
{
C.Prop = 1;
}
}
", il);
comp.VerifyDiagnostics(
// (6,11): error CS0570: 'C.Prop.get' is not supported by the language
// C.Prop = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "Prop").WithArguments("C.Prop.get").WithLocation(6, 11)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnIndexer_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
01 00 04 49 74 65 6d 00 00
)
// Methods
.method public hidebysig specialname
instance void set_Item (
int32 i,
int32 'value'
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
nop
ret
} // end of method C::set_Item
.method public hidebysig specialname
instance int32 get_Item (
int32 i
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
} // end of method C::get_Item
// Properties
.property instance int32 Item(
int32 i
)
{
.get instance int32 C::get_Item(int32)
.set instance void C::set_Item(int32, int32)
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
c[1] = 1;
_ = c[0];
}
}
", il);
comp.VerifyDiagnostics(
// (6,10): error CS0570: 'C.this[int].set' is not supported by the language
// c[1] = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "[1]").WithArguments("C.this[int].set").WithLocation(6, 10),
// (7,14): error CS0570: 'C.this[int].get' is not supported by the language
// _ = c[0];
Diagnostic(ErrorCode.ERR_BindToBogus, "[0]").WithArguments("C.this[int].get").WithLocation(7, 14)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnIndexer_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
public int this[int i]
{
[UnmanagedCallersOnly] set => throw null;
[UnmanagedCallersOnly] get => throw null;
}
static void M(C c)
{
c[1] = 1;
_ = c[0];
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] set => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10),
// (8,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly] get => throw null;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnIndexerRefReturnAsLvalue_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
01 00 04 49 74 65 6d 00 00
)
// Methods
.method public hidebysig specialname
instance int32& get_Item (
int32 i
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
} // end of method C::get_Item
// Properties
.property instance int32& Item(
int32 i
)
{
.get instance int32& C::get_Item(int32)
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
c[1] = 1;
_ = c[0];
}
}
", il);
comp.VerifyDiagnostics(
// (6,10): error CS0570: 'C.this[int].get' is not supported by the language
// c[1] = 1;
Diagnostic(ErrorCode.ERR_BindToBogus, "[1]").WithArguments("C.this[int].get").WithLocation(6, 10),
// (7,14): error CS0570: 'C.this[int].get' is not supported by the language
// _ = c[0];
Diagnostic(ErrorCode.ERR_BindToBogus, "[0]").WithArguments("C.this[int].get").WithLocation(7, 14)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnBinaryOperator_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static C operator +(C c1, C c2) => null;
static void M(C c1, C c2)
{
_ = c1 + c2;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnBinaryOperator_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname static
class C op_Addition (
class C c1,
class C c2
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
ret
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c1, C c2)
{
_ = c1 + c2;
}
}
", il);
comp.VerifyDiagnostics(
// (6,13): error CS0570: 'C.operator +(C, C)' is not supported by the language
// _ = c1 + c2;
Diagnostic(ErrorCode.ERR_BindToBogus, "c1 + c2").WithArguments("C.operator +(C, C)").WithLocation(6, 13)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnUnaryOperator_InSource()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static C operator +(C c) => null;
static void M(C c)
{
_ = +c;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyDefinedOnUnaryOperator_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname static
class C op_UnaryPlus (
class C c1
) cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
ret
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c1, C c2)
{
_ = +c1;
}
}
", il);
comp.VerifyDiagnostics(
// (6,13): error CS0570: 'C.operator +(C)' is not supported by the language
// _ = +c1;
Diagnostic(ErrorCode.ERR_BindToBogus, "+c1").WithArguments("C.operator +(C)").WithLocation(6, 13)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnGetEnumerator_InMetadata()
{
var il = UnmanagedCallersOnlyAttributeIl + @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> GetEnumerator () cil managed
{
// [System.Runtime.InteropServices.UnmanagedCallersOnly]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(@"
class D
{
public static void M2(C c)
{
foreach (var i in c) {}
}
}
", il);
comp.VerifyDiagnostics(
// (6,27): error CS1579: foreach statement cannot operate on variables of type 'C' because 'C' does not contain a public instance or extension definition for 'GetEnumerator'
// foreach (var i in c) {}
Diagnostic(ErrorCode.ERR_ForEachMissingMember, "c").WithArguments("C", "GetEnumerator").WithLocation(6, 27)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnGetEnumeratorExtension()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
public static void M2(S s)
{
foreach (var i in s) {}
}
}
public struct SEnumerator
{
public bool MoveNext() => throw null;
public int Current => throw null;
}
public static class CExt
{
[UnmanagedCallersOnly]
public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,9): error CS8901: 'CExt.GetEnumerator(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// foreach (var i in s) {}
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "foreach").WithArguments("CExt.GetEnumerator(S)").WithLocation(7, 9)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnMoveNext()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
public static void M2(S s)
{
foreach (var i in s) {}
}
}
public struct SEnumerator
{
[UnmanagedCallersOnly]
public bool MoveNext() => throw null;
public int Current => throw null;
}
public static class CExt
{
public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(12, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyDeclaredOnPatternDispose()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public struct S
{
public static void M2(S s)
{
foreach (var i in s) {}
}
}
public ref struct SEnumerator
{
public bool MoveNext() => throw null;
public int Current => throw null;
[UnmanagedCallersOnly]
public void Dispose() => throw null;
}
public static class CExt
{
public static SEnumerator GetEnumerator(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCaptureToDelegate()
{
var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M1() { }
public static void M2()
{
Action a = M1;
a = local;
a = new Action(M1);
a = new Action(local);
[UnmanagedCallersOnly]
static void local() {}
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (11,20): error CS8902: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// Action a = M1;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M1").WithArguments("C.M1()").WithLocation(11, 20),
// (12,13): error CS8902: 'local()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// a = local;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "local").WithArguments("local()").WithLocation(12, 13),
// (13,24): error CS8902: 'C.M1()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// a = new Action(M1);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M1").WithArguments("C.M1()").WithLocation(13, 24),
// (14,24): error CS8902: 'local()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// a = new Action(local);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "local").WithArguments("local()").WithLocation(14, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyCannotCaptureToDelegate_OverloadStillPicked()
{
var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly]
public static void M(int s) { }
public static void M(object o) { }
void N()
{
Action<int> a = M;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (13,25): error CS8902: 'C.M(int)' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.
// Action<int> a = M;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "M").WithArguments("C.M(int)").WithLocation(13, 25)
);
}
[Fact]
public void UnmanagedCallersOnlyOnExtensionsCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
struct S
{
static void M(S s)
{
s.Extension();
CExt.Extension(s);
}
}
static class CExt
{
[UnmanagedCallersOnly]
public static void Extension(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'CExt.Extension(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// s.Extension();
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s.Extension()").WithArguments("CExt.Extension(S)").WithLocation(8, 9),
// (9,9): error CS8901: 'CExt.Extension(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// CExt.Extension(s);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "CExt.Extension(s)").WithArguments("CExt.Extension(S)").WithLocation(9, 9)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionDeconstructCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Collections.Generic;
using System.Runtime.InteropServices;
struct S
{
static void M(S s, List<S> ls)
{
var (i1, i2) = s;
(i1, i2) = s;
foreach (var (_, _) in ls) { }
_ = s is (int _, int _);
}
}
static class CExt
{
[UnmanagedCallersOnly]
public static void Deconstruct(this S s, out int i1, out int i2) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (9,24): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// var (i1, i2) = s;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(9, 24),
// (10,20): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// (i1, i2) = s;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(10, 20),
// (11,32): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// foreach (var (_, _) in ls) { }
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "ls").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(11, 32),
// (12,18): error CS8901: 'CExt.Deconstruct(S, out int, out int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = s is (int _, int _);
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "(int _, int _)").WithArguments("CExt.Deconstruct(S, out int, out int)").WithLocation(12, 18)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionAddCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
struct S : IEnumerable
{
static void M(S s, List<S> ls)
{
_ = new S() { 1, 2, 3 };
}
public IEnumerator GetEnumerator() => throw null;
}
static class CExt
{
[UnmanagedCallersOnly]
public static void Add(this S s, int i) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (10,23): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = new S() { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "1").WithArguments("CExt.Add(S, int)").WithLocation(10, 23),
// (10,26): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = new S() { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "2").WithArguments("CExt.Add(S, int)").WithLocation(10, 26),
// (10,29): error CS8901: 'CExt.Add(S, int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// _ = new S() { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "3").WithArguments("CExt.Add(S, int)").WithLocation(10, 29)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionGetAwaiterCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
struct S
{
static async void M(S s)
{
await s;
}
}
public struct Result : System.Runtime.CompilerServices.INotifyCompletion
{
public int GetResult() => throw null;
public void OnCompleted(System.Action continuation) => throw null;
public bool IsCompleted => throw null;
}
static class CExt
{
[UnmanagedCallersOnly]
public static Result GetAwaiter(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (8,9): error CS8901: 'CExt.GetAwaiter(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// await s;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "await s").WithArguments("CExt.GetAwaiter(S)").WithLocation(8, 9)
);
}
[Fact]
public void UnmanagedCallersOnlyExtensionGetPinnableReferenceCannotBeUsedDirectly()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
struct S
{
static void M(S s)
{
unsafe
{
fixed (int* i = s)
{
}
}
}
}
static class CExt
{
[UnmanagedCallersOnly]
public static ref int GetPinnableReference(this S s) => throw null;
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (10,29): error CS8901: 'CExt.GetPinnableReference(S)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// fixed (int* i = s)
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "s").WithArguments("CExt.GetPinnableReference(S)").WithLocation(10, 29)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_1()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (6,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static void Main() {}
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(6, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_2()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
public static void Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (5,24): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
// public static void Main() {}
Diagnostic(ErrorCode.ERR_MultipleEntryPoints, "Main").WithLocation(5, 24),
// (10,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static void Main() {}
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(10, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_3()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
public static void Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static void Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyOnMain_4()
{
var comp = CreateCompilation(new[] { @"
using System.Threading.Tasks;
using System.Runtime.InteropServices;
class C
{
public static async Task Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static async Task Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (6,30): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_MultipleEntryPoints, "Main").WithLocation(6, 30),
// (6,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(6, 30),
// (11,25): error CS8894: Cannot use 'Task' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "Task").WithArguments("System.Threading.Tasks.Task", "return").WithLocation(11, 25),
// (11,30): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main").WithLocation(11, 30),
// (11,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(11, 30)
);
}
[Fact]
public void UnmanagedCallersOnlyOnMain_5()
{
var comp = CreateCompilation(new[] { @"
using System.Threading.Tasks;
using System.Runtime.InteropServices;
class C
{
public static void Main() {}
}
class D
{
[UnmanagedCallersOnly]
public static async Task Main() {}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (11,25): error CS8894: Cannot use 'Task' as a return type on a method attributed with 'UnmanagedCallersOnly'.
// public static async Task Main() {}
Diagnostic(ErrorCode.ERR_CannotUseManagedTypeInUnmanagedCallersOnly, "Task").WithArguments("System.Threading.Tasks.Task", "return").WithLocation(11, 25),
// (11,30): warning CS8892: Method 'D.Main()' will not be used as an entry point because a synchronous entry point 'C.Main()' was found.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("D.Main()", "C.Main()").WithLocation(11, 30),
// (11,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// public static async Task Main() {}
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(11, 30)
);
}
[Fact, WorkItem(47858, "https://github.com/dotnet/roslyn/issues/47858")]
public void UnmanagedCallersOnlyOnMain_GetEntryPoint()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly]
public static void Main()
{
}
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.ReleaseExe);
var method = comp.GetEntryPoint(System.Threading.CancellationToken.None);
Assert.Equal("void C.Main()", method.ToTestDisplayString());
comp.VerifyDiagnostics(
// (6,24): error CS8899: Application entry points cannot be attributed with 'UnmanagedCallersOnly'.
// public static void Main()
Diagnostic(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, "Main", isSuppressed: false).WithLocation(6, 24)
);
}
[Fact]
public void UnmanagedCallersOnlyOnModuleInitializer()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } }
public class C
{
[UnmanagedCallersOnly, ModuleInitializer]
public static void M1() {}
[ModuleInitializer, UnmanagedCallersOnly]
public static void M2() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (9,28): error CS8900: Module initializer cannot be attributed with 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly, ModuleInitializer]
Diagnostic(ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly, "ModuleInitializer").WithLocation(9, 28),
// (12,6): error CS8900: Module initializer cannot be attributed with 'UnmanagedCallersOnly'.
// [ModuleInitializer, UnmanagedCallersOnly]
Diagnostic(ErrorCode.ERR_ModuleInitializerCannotBeUnmanagedCallersOnly, "ModuleInitializer").WithLocation(12, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyMultipleApplications()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })]
[UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
public static void M1() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'string' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(string) })").WithArguments("string").WithLocation(5, 6),
// (6,6): error CS0579: Duplicate 'UnmanagedCallersOnly' attribute
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(object) })]
Diagnostic(ErrorCode.ERR_DuplicateAttribute, "UnmanagedCallersOnly").WithArguments("UnmanagedCallersOnly").WithLocation(6, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInDefinition_1()
{
var comp = CreateCompilation(@"
#nullable enable
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public Type[]? CallConvs;
public string? EntryPoint;
[UnmanagedCallersOnly]
static void M() {}
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInDefinition_2()
{
var comp = CreateCompilation(@"
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
public UnmanagedCallersOnlyAttribute() { }
public Type[] CallConvs;
}
}
");
comp.VerifyDiagnostics(
// (7,10): error CS8893: 'UnmanagedCallersOnlyAttribute' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })").WithArguments("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute").WithLocation(7, 10),
// (7,10): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(UnmanagedCallersOnlyAttribute) })]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 10)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_1()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })]
public static void Func() {}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,6): error CS8893: 'C' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(C) })").WithArguments("C").WithLocation(5, 6)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_2()
{
var comp = CreateCompilation(new[] { @"
using System.Runtime.InteropServices;
class A
{
struct B { }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })]
static void F() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,6): error CS8893: 'A.B' is not a valid calling convention type for 'UnmanagedCallersOnly'.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })]
Diagnostic(ErrorCode.ERR_InvalidUnmanagedCallersOnlyCallConv, "UnmanagedCallersOnly(CallConvs = new[] { typeof(B) })").WithArguments("A.B").WithLocation(6, 6)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/47125")]
public void UnmanagedCallersOnlyWithLoopInUsage_3()
{
// Remove UnmanagedCallersOnlyWithLoopInUsage_3_Release when
// this is unskipped.
var comp = CreateCompilation(new[] { @"
#nullable enable
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = F())]
static Type[] F() { }
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(IsRelease))]
public void UnmanagedCallersOnlyWithLoopInUsage_3_Release()
{
// The bug in UnmanagedCallersOnlyWithLoopInUsage_3 is only
// triggered by the nullablewalker, which is unconditionally
// run in debug mode. We also want to verify the use-site
// diagnostic for unmanagedcallersonly does not cause a loop,
// so we have a separate version that does not have nullable
// enabled and only runs in release to verify. When
// https://github.com/dotnet/roslyn/issues/47125 is fixed, this
// test can be removed
var comp = CreateCompilation(new[] { @"
using System;
using System.Runtime.InteropServices;
class C
{
[UnmanagedCallersOnly(CallConvs = F())]
static Type[] F() => null;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (6,39): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// [UnmanagedCallersOnly(CallConvs = F())]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()").WithArguments("C.F()").WithLocation(6, 39),
// (6,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [UnmanagedCallersOnly(CallConvs = F())]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()").WithLocation(6, 39)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_4()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
unsafe class Attr : Attribute
{
public Attr(delegate*<void> d) {}
}
unsafe class C
{
[UnmanagedCallersOnly]
[Attr(&M1)]
static void M1()
{
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,6): error CS0181: Attribute constructor parameter 'd' has type 'delegate*<void>', which is not a valid attribute parameter type
// [Attr(&M1)]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr", isSuppressed: false).WithArguments("d", "delegate*<void>").WithLocation(12, 6)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/47125")]
public void UnmanagedCallersOnlyWithLoopInUsage_5()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class Attr : Attribute
{
public Attr(int i) {}
}
unsafe class C
{
[UnmanagedCallersOnly]
[Attr(F())]
static int F()
{
return 0;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,11): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// [Attr(F())]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F()").WithLocation(12, 11),
// (12,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Attr(F())]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()", isSuppressed: false).WithLocation(12, 11)
);
}
[ConditionalFact(typeof(IsRelease))]
public void UnmanagedCallersOnlyWithLoopInUsage_5_Release()
{
// The bug in UnmanagedCallersOnlyWithLoopInUsage_5 is only
// triggered by the nullablewalker, which is unconditionally
// run in debug mode. We also want to verify the use-site
// diagnostic for unmanagedcallersonly does not cause a loop,
// so we have a separate version that does not have nullable
// enabled and only runs in release to verify. When
// https://github.com/dotnet/roslyn/issues/47125 is fixed, this
// test can be removed
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class Attr : Attribute
{
public Attr(int i) {}
}
unsafe class C
{
[UnmanagedCallersOnly]
[Attr(F())]
static int F()
{
return 0;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (12,11): error CS8901: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// [Attr(F())]
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F()").WithLocation(12, 11),
// (12,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Attr(F())]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F()", isSuppressed: false).WithLocation(12, 11)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_6()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvFastcall) })]
static void F(int i = G(&F)) { }
static int G(delegate*unmanaged[Fastcall]<int, void> d) => 0;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,27): error CS1736: Default parameter value for 'i' must be a compile-time constant
// static void F(int i = G(&F)) { }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "G(&F)", isSuppressed: false).WithArguments("i").WithLocation(7, 27)
);
}
[Fact]
public void UnmanagedCallersOnlyWithLoopInUsage_7()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvFastcall) })]
static int F(int i = F()) => 0;
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (7,26): error CS8901: 'C.F(int)' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.
// static int F(int i = F()) => 0;
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, "F()", isSuppressed: false).WithArguments("C.F(int)").WithLocation(7, 26),
// (7,26): error CS1736: Default parameter value for 'i' must be a compile-time constant
// static int F(int i = F()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()", isSuppressed: false).WithArguments("i").WithLocation(7, 26)
);
}
[Fact]
public void UnmanagedCallersOnlyUnrecognizedConstructor()
{
var comp = CreateCompilation(@"
using System.Runtime.InteropServices;
public class C
{
// Invalid typeof for the regular constructor, non-static method
[UnmanagedCallersOnly(CallConvs: new[] { typeof(string) })]
public void M() {}
}
#nullable enable
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute(Type[]? CallConvs)
{
}
public string? EntryPoint;
}
}
");
comp.VerifyDiagnostics();
}
[Fact]
public void UnmanagedCallersOnlyCallConvsWithADifferentType()
{
var definition = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
public static void M1() {}
}
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public string EntryPoint;
public object CallConvs;
}
}
";
var usage = @"
class D
{
unsafe void M2()
{
delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
}
}
";
var allInOne = CreateCompilationWithFunctionPointers(definition + usage);
allInOne.VerifyDiagnostics(
// (27,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(27, 51)
);
var definitionComp = CreateCompilation(definition);
var usageComp = CreateCompilationWithFunctionPointers(usage, new[] { definitionComp.EmitToImageReference() });
usageComp.VerifyDiagnostics(
// (6,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(6, 51)
);
}
[Fact]
public void UnmanagedCallersOnlyCallConvsWithADifferentType_2()
{
var definition = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
public static void M1() {}
}
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public string EntryPoint;
public object[] CallConvs;
}
}
";
var usage = @"
class D
{
unsafe void M2()
{
delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
}
}
";
var allInOne = CreateCompilationWithFunctionPointers(definition + usage);
allInOne.VerifyDiagnostics(
// (27,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(27, 51)
);
var definitionComp = CreateCompilation(definition);
var usageComp = CreateCompilationWithFunctionPointers(usage, new[] { definitionComp.EmitToImageReference() });
usageComp.VerifyDiagnostics(
// (6,51): error CS8786: Calling convention of 'C.M1()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr = &C.M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M1").WithArguments("C.M1()", "Standard").WithLocation(6, 51)
);
}
[Fact]
public void UnmanagedCallersOnly_CallConvsAsProperty()
{
string source1 = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute()
{
}
public Type[] CallConvs { get; set; }
public string EntryPoint;
}
}
public class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
public static void M() {}
}";
string source2 = @"
class D
{
unsafe void M2()
{
delegate* unmanaged<void> ptr1 = &C.M;
delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
}
}";
var sameComp = CreateCompilationWithFunctionPointers(source1 + source2);
sameComp.VerifyDiagnostics(
// (28,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(28, 50)
);
verifyUnmanagedData(sameComp);
var refComp = CreateCompilation(source1);
var differentComp = CreateCompilationWithFunctionPointers(source2, new[] { refComp.EmitToImageReference() });
differentComp.VerifyDiagnostics(
// (7,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(7, 50)
);
verifyUnmanagedData(differentComp);
static void verifyUnmanagedData(CSharpCompilation compilation)
{
var c = compilation.GetTypeByMetadataName("C");
var m = c.GetMethod("M");
Assert.Empty(m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true)!.CallingConventionTypes);
}
}
[Fact]
public void UnmanagedCallersOnly_UnrecognizedSignature()
{
string source1 = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices
{
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class UnmanagedCallersOnlyAttribute : Attribute
{
public UnmanagedCallersOnlyAttribute(Type[] CallConvs)
{
}
public string EntryPoint;
}
}
public class C
{
[UnmanagedCallersOnly(CallConvs: new[] { typeof(CallConvCdecl) })]
public static void M() {}
}";
string source2 = @"
class D
{
unsafe void M2()
{
delegate* unmanaged<void> ptr1 = &C.M;
delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
delegate*<void> ptr3 = &C.M;
}
}";
var sameComp = CreateCompilationWithFunctionPointers(source1 + source2);
sameComp.VerifyDiagnostics(
// (26,43): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// delegate* unmanaged<void> ptr1 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Unmanaged").WithLocation(26, 43),
// (27,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(27, 50)
);
verifyUnmanagedData(sameComp);
var refComp = CreateCompilation(source1);
var differentComp = CreateCompilationWithFunctionPointers(source2, new[] { refComp.EmitToImageReference() });
differentComp.VerifyDiagnostics(
// (6,43): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// delegate* unmanaged<void> ptr1 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Unmanaged").WithLocation(6, 43),
// (7,50): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptr2 = &C.M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "CDecl").WithLocation(7, 50)
);
verifyUnmanagedData(differentComp);
static void verifyUnmanagedData(CSharpCompilation compilation)
{
var c = compilation.GetTypeByMetadataName("C");
var m = c.GetMethod("M");
Assert.Null(m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true));
}
}
[Fact]
public void UnmanagedCallersOnly_PropertyAndFieldNamedCallConvs()
{
var il = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute
extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
// Fields
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
// Methods
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
} // end of method UnmanagedCallersOnlyAttribute::.ctor
.method public hidebysig specialname instance class [mscorlib]System.Type[] get_CallConvs () cil managed
{
ldnull
ret
} // end of method UnmanagedCallersOnlyAttribute::get_CallConvs
.method public hidebysig specialname instance void set_CallConvs (
class [mscorlib]System.Type[] 'value'
) cil managed
{
ret
} // end of method UnmanagedCallersOnlyAttribute::set_CallConvs
// Properties
.property instance class [mscorlib]System.Type[] CallConvs()
{
.get instance class [mscorlib]System.Type[] System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::get_CallConvs()
.set instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::set_CallConvs(class [mscorlib]System.Type[])
}
}
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig static void M () cil managed
{
// As separate field/property assignments. Property is first.
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) }, CallConvs = new[] { typeof(CallConvCdecl) })]
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 02 00 54 1d 50 09 43 61 6c 6c 43 6f 6e 76
73 01 00 00 00 7c 53 79 73 74 65 6d 2e 52 75 6e
74 69 6d 65 2e 43 6f 6d 70 69 6c 65 72 53 65 72
76 69 63 65 73 2e 43 61 6c 6c 43 6f 6e 76 53 74
64 63 61 6c 6c 2c 20 6d 73 63 6f 72 6c 69 62 2c
20 56 65 72 73 69 6f 6e 3d 34 2e 30 2e 30 2e 30
2c 20 43 75 6c 74 75 72 65 3d 6e 65 75 74 72 61
6c 2c 20 50 75 62 6c 69 63 4b 65 79 54 6f 6b 65
6e 3d 62 37 37 61 35 63 35 36 31 39 33 34 65 30
38 39 53 1d 50 09 43 61 6c 6c 43 6f 6e 76 73 01
00 00 00 7a 53 79 73 74 65 6d 2e 52 75 6e 74 69
6d 65 2e 43 6f 6d 70 69 6c 65 72 53 65 72 76 69
63 65 73 2e 43 61 6c 6c 43 6f 6e 76 43 64 65 63
6c 2c 20 6d 73 63 6f 72 6c 69 62 2c 20 56 65 72
73 69 6f 6e 3d 34 2e 30 2e 30 2e 30 2c 20 43 75
6c 74 75 72 65 3d 6e 65 75 74 72 61 6c 2c 20 50
75 62 6c 69 63 4b 65 79 54 6f 6b 65 6e 3d 62 37
37 61 35 63 35 36 31 39 33 34 65 30 38 39
)
ret
} // end of method C::M
}
";
var comp = CreateCompilationWithFunctionPointersAndIl(@"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
unsafe class D
{
static void M1()
{
delegate* unmanaged[Cdecl]<void> ptr1 = &C.M;
delegate* unmanaged[Stdcall]<void> ptr2 = &C.M; // Error
M2();
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
static void M2() {}
}
", il);
comp.VerifyDiagnostics(
// (9,52): error CS8786: Calling convention of 'C.M()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptr2 = &C.M; // Error
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "C.M").WithArguments("C.M()", "Standard").WithLocation(9, 52),
// (13,27): error CS0229: Ambiguity between 'UnmanagedCallersOnlyAttribute.CallConvs' and 'UnmanagedCallersOnlyAttribute.CallConvs'
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
Diagnostic(ErrorCode.ERR_AmbigMember, "CallConvs").WithArguments("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute.CallConvs", "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute.CallConvs").WithLocation(13, 27)
);
var c = comp.GetTypeByMetadataName("C");
var m = c.GetMethod("M");
var callConvCdecl = comp.GetTypeByMetadataName("System.Runtime.CompilerServices.CallConvCdecl");
Assert.True(callConvCdecl!.Equals((NamedTypeSymbol)m.GetUnmanagedCallersOnlyAttributeData(forceComplete: true)!.CallingConventionTypes.Single(), TypeCompareKind.ConsiderEverything));
}
[Fact]
public void UnmanagedCallersOnly_BadExpressionInArguments()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System.Runtime.InteropServices;
class A
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
static unsafe void F()
{
delegate*<void> ptr1 = &F;
delegate* unmanaged<void> ptr2 = &F;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (5,54): error CS0246: The type or namespace name 'Bad' could not be found (are you missing a using directive or an assembly reference?)
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Bad", isSuppressed: false).WithArguments("Bad").WithLocation(5, 54),
// (5,57): error CS1026: ) expected
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_CloseParenExpected, ",", isSuppressed: false).WithLocation(5, 57),
// (5,59): error CS0103: The name 'Expression' does not exist in the current context
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_NameNotInContext, "Expression", isSuppressed: false).WithArguments("Expression").WithLocation(5, 59),
// (5,69): error CS1003: Syntax error, ',' expected
// [UnmanagedCallersOnly(CallConvs = new[] { typeof(Bad, Expression) })]
Diagnostic(ErrorCode.ERR_SyntaxError, ")", isSuppressed: false).WithArguments(",", ")").WithLocation(5, 69),
// (9,43): error CS8786: Calling convention of 'A.F()' is not compatible with 'Unmanaged'.
// delegate* unmanaged<void> ptr2 = &F;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "F", isSuppressed: false).WithArguments("A.F()", "Unmanaged").WithLocation(9, 43)
);
}
[Theory]
[InlineData("", 1)]
[InlineData("CallConvs = null", 1)]
[InlineData("CallConvs = new System.Type[0]", 1)]
[InlineData("CallConvs = new[] { typeof(CallConvCdecl) }", 2)]
[InlineData("CallConvs = new[] { typeof(CallConvCdecl), typeof(CallConvCdecl) }", 2)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall) }", 3)]
[InlineData("CallConvs = new[] { typeof(CallConvStdcall) }", 4)]
[InlineData("CallConvs = new[] { typeof(CallConvFastcall) }", 5)]
[InlineData("CallConvs = new[] { typeof(CallConvCdecl), typeof(CallConvThiscall) }", 6)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl) }", 6)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl), typeof(CallConvCdecl) }", 6)]
[InlineData("CallConvs = new[] { typeof(CallConvFastcall), typeof(CallConvCdecl) }", -1)]
[InlineData("CallConvs = new[] { typeof(CallConvThiscall), typeof(CallConvCdecl), typeof(CallConvStdcall) }", -1)]
public void UnmanagedCallersOnlyAttribute_ConversionsToPointerType(string unmanagedCallersOnlyConventions, int diagnosticToSkip)
{
var comp = CreateCompilationWithFunctionPointers(new[] { $@"
#pragma warning disable CS8019 // Unused using
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{{
[UnmanagedCallersOnly({unmanagedCallersOnlyConventions})]
public static void M()
{{
delegate*<void> ptrManaged = &M;
delegate* unmanaged<void> ptrUnmanaged = &M;
delegate* unmanaged[Cdecl]<void> ptrCdecl = &M;
delegate* unmanaged[Thiscall]<void> ptrThiscall = &M;
delegate* unmanaged[Stdcall]<void> ptrStdcall = &M;
delegate* unmanaged[Fastcall]<void> ptrFastcall = &M;
delegate* unmanaged[Cdecl, Thiscall]<void> ptrCdeclThiscall = &M;
}}
}}
", UnmanagedCallersOnlyAttribute });
List<DiagnosticDescription> diagnostics = new()
{
// (10,39): error CS8786: Calling convention of 'C.M()' is not compatible with 'Default'.
// delegate*<void> ptrManaged = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Default").WithLocation(10, 39)
};
if (diagnosticToSkip != 1)
{
diagnostics.Add(
// (11,25): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// ptrUnmanaged = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Unmanaged").WithLocation(11, 51)
);
}
if (diagnosticToSkip != 2)
{
diagnostics.Add(
// (12,54): error CS8786: Calling convention of 'C.M()' is not compatible with 'CDecl'.
// delegate* unmanaged[Cdecl]<void> ptrCdecl = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "CDecl").WithLocation(12, 54)
);
}
if (diagnosticToSkip != 3)
{
diagnostics.Add(
// (13,60): error CS8786: Calling convention of 'C.M()' is not compatible with 'ThisCall'.
// delegate* unmanaged[Thiscall]<void> ptrThiscall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "ThisCall").WithLocation(13, 60)
);
}
if (diagnosticToSkip != 4)
{
diagnostics.Add(
// (14,58): error CS8786: Calling convention of 'C.M()' is not compatible with 'Standard'.
// delegate* unmanaged[Stdcall]<void> ptrStdcall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Standard").WithLocation(14, 58)
);
}
if (diagnosticToSkip != 5)
{
diagnostics.Add(
// (15,60): error CS8786: Calling convention of 'C.M()' is not compatible with 'FastCall'.
// delegate* unmanaged[Fastcall]<void> ptrFastcall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "FastCall").WithLocation(15, 60)
);
}
if (diagnosticToSkip != 6)
{
diagnostics.Add(
// (16,72): error CS8786: Calling convention of 'C.M()' is not compatible with 'Unmanaged'.
// delegate* unmanaged[Cdecl, Thiscall]<void> ptrCdeclThiscall = &M;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M", isSuppressed: false).WithArguments("C.M()", "Unmanaged").WithLocation(16, 72)
);
}
comp.VerifyDiagnostics(diagnostics.ToArray());
}
[Fact]
public void UnmanagedCallersOnlyAttribute_AddressOfUsedInAttributeArgument()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
unsafe class Attr : Attribute
{
public Attr() {}
public delegate* unmanaged<void> PropUnmanaged { get; set; }
public delegate*<void> PropManaged { get; set; }
public delegate* unmanaged[Cdecl]<void> PropCdecl { get; set; }
}
unsafe class C
{
[UnmanagedCallersOnly]
static void M1()
{
}
[Attr(PropUnmanaged = &M1)]
[Attr(PropManaged = &M1)]
[Attr(PropCdecl = &M1)]
static unsafe void M2()
{
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (20,11): error CS0655: 'PropUnmanaged' is not a valid named attribute argument because it is not a valid attribute parameter type
// [Attr(PropUnmanaged = &M1)]
Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropUnmanaged", isSuppressed: false).WithArguments("PropUnmanaged").WithLocation(20, 11),
// (21,11): error CS0655: 'PropManaged' is not a valid named attribute argument because it is not a valid attribute parameter type
// [Attr(PropManaged = &M1)]
Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropManaged", isSuppressed: false).WithArguments("PropManaged").WithLocation(21, 11),
// (22,11): error CS0655: 'PropCdecl' is not a valid named attribute argument because it is not a valid attribute parameter type
// [Attr(PropCdecl = &M1)]
Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "PropCdecl", isSuppressed: false).WithArguments("PropCdecl").WithLocation(22, 11)
);
}
[ConditionalFact(typeof(CoreClrOnly))]
public void UnmanagedCallersOnly_Il()
{
var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
unsafe
{
delegate* unmanaged<void> ptr = &M;
ptr();
}
[UnmanagedCallersOnly]
static void M()
{
Console.WriteLine(1);
}
", UnmanagedCallersOnlyAttribute }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp);
// TODO: Remove the manual unmanagedcallersonlyattribute definition and override and verify the
// output of running this code when we move to p8
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIL: @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void Program.<<Main>$>g__M|0_0()""
IL_0006: calli ""delegate* unmanaged<void>""
IL_000b: ret
}
");
}
[Fact]
public void UnmanagedCallersOnly_AddressOfAsInvocationArgument()
{
var verifier = CompileAndVerifyFunctionPointers(new[] { @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
public static void M1(int i) { }
public static void M2(delegate* unmanaged[Cdecl]<int, void> param)
{
M2(&M1);
}
}
", UnmanagedCallersOnlyAttribute });
verifier.VerifyIL(@"C.M2", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""void C.M1(int)""
IL_0006: call ""void C.M2(delegate* unmanaged[Cdecl]<int, void>)""
IL_000b: ret
}
");
}
[Fact]
public void UnmanagedCallersOnly_LambdaInference()
{
var comp = CreateCompilationWithFunctionPointers(new[] { @"
using System;
using System.Runtime.InteropServices;
public unsafe class C
{
[UnmanagedCallersOnly]
public static void M1(int i) { }
public static void M2()
{
Func<delegate*<int, void>> a1 = () => &M1;
Func<delegate* unmanaged<int, void>> a2 = () => &M1;
}
}
", UnmanagedCallersOnlyAttribute });
comp.VerifyDiagnostics(
// (11,14): error CS0306: The type 'delegate*<int, void>' may not be used as a type argument
// Func<delegate*<int, void>> a1 = () => &M1;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, void>", isSuppressed: false).WithArguments("delegate*<int, void>").WithLocation(11, 14),
// (11,47): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<delegate*<int, void>> a1 = () => &M1;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "&M1", isSuppressed: false).WithArguments("lambda expression").WithLocation(11, 47),
// (11,48): error CS8786: Calling convention of 'C.M1(int)' is not compatible with 'Default'.
// Func<delegate*<int, void>> a1 = () => &M1;
Diagnostic(ErrorCode.ERR_WrongFuncPtrCallingConvention, "M1", isSuppressed: false).WithArguments("C.M1(int)", "Default").WithLocation(11, 48),
// (12,14): error CS0306: The type 'delegate* unmanaged<int, void>' may not be used as a type argument
// Func<delegate* unmanaged<int, void>> a2 = () => &M1;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate* unmanaged<int, void>", isSuppressed: false).WithArguments("delegate* unmanaged<int, void>").WithLocation(12, 14)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambdas = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToArray();
Assert.Equal(2, lambdas.Length);
var typeInfo = model.GetTypeInfo(lambdas[0]);
var conversion = model.GetConversion(lambdas[0]);
AssertEx.Equal("System.Func<delegate*<System.Int32, System.Void>>",
typeInfo.Type.ToTestDisplayString(includeNonNullable: false));
AssertEx.Equal("System.Func<delegate*<System.Int32, System.Void>>",
typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false));
Assert.Equal(Conversion.NoConversion, conversion);
typeInfo = model.GetTypeInfo(lambdas[1]);
conversion = model.GetConversion(lambdas[1]);
Assert.Null(typeInfo.Type);
AssertEx.Equal("System.Func<delegate* unmanaged<System.Int32, System.Void>>",
typeInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false));
Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind);
}
[Fact, WorkItem(47487, "https://github.com/dotnet/roslyn/issues/47487")]
public void InAndRefParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
delegate*<in int, ref char, void> F = &Test;
char c = 'a';
F(int.MaxValue, ref c);
}
static void Test(in int b, ref char c)
{
Console.WriteLine($""b = {b}, c = {c}"");
}
", expectedOutput: "b = 2147483647, c = a");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 27 (0x1b)
.maxstack 3
.locals init (char V_0, //c
delegate*<in int, ref char, void> V_1,
int V_2)
IL_0000: ldftn ""void Program.<<Main>$>g__Test|0_0(in int, ref char)""
IL_0006: ldc.i4.s 97
IL_0008: stloc.0
IL_0009: stloc.1
IL_000a: ldc.i4 0x7fffffff
IL_000f: stloc.2
IL_0010: ldloca.s V_2
IL_0012: ldloca.s V_0
IL_0014: ldloc.1
IL_0015: calli ""delegate*<in int, ref char, void>""
IL_001a: ret
}
");
}
[Fact, WorkItem(47487, "https://github.com/dotnet/roslyn/issues/47487")]
public void OutDiscard()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
delegate*<out int, out int, void> F = &Test;
F(out var i1, out _);
F(out _, out var i2);
Console.Write(i1);
Console.Write(i2);
}
static void Test(out int i1, out int i2)
{
i1 = 1;
i2 = 2;
}
", expectedOutput: "12");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
int V_2,
delegate*<out int, out int, void> V_3)
IL_0000: ldftn ""void Program.<<Main>$>g__Test|0_0(out int, out int)""
IL_0006: dup
IL_0007: stloc.3
IL_0008: ldloca.s V_0
IL_000a: ldloca.s V_2
IL_000c: ldloc.3
IL_000d: calli ""delegate*<out int, out int, void>""
IL_0012: stloc.3
IL_0013: ldloca.s V_2
IL_0015: ldloca.s V_1
IL_0017: ldloc.3
IL_0018: calli ""delegate*<out int, out int, void>""
IL_001d: ldloc.0
IL_001e: call ""void System.Console.Write(int)""
IL_0023: ldloc.1
IL_0024: call ""void System.Console.Write(int)""
IL_0029: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
iRef = 2;
System.Console.WriteLine(i);
static ref int ReturnPtrByRef(delegate*<ref int, ref int> ptr, ref int i)
=> ref ptr(ref i);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref int, ref int>, ref int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref int, ref int>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_FunctionPointerDoesNotReturnByRefError()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe
{
int i = 1;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
static ref int ReturnPtrByRef(delegate*<ref int, int> ptr, ref int i)
=> ref ptr(ref i);
static int ReturnByRef(ref int i) => i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (8,16): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// => ref ptr(ref i);
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "ptr(ref i)").WithLocation(8, 16)
);
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_NotSafeToEscape()
{
var comp = CreateCompilationWithSpan(@"
using System;
unsafe
{
ref Span<int> spanRef = ref ReturnPtrByRef(&ReturnByRef);
static ref Span<int> ReturnPtrByRef(delegate*<ref Span<int>, ref Span<int>> ptr)
{
Span<int> span = stackalloc int[1];
return ref ptr(ref span);
}
static ref Span<int> ReturnByRef(ref Span<int> i) => ref i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (10,20): error CS8347: Cannot use a result of 'delegate*<ref Span<int>, ref Span<int>>' in this context because it may expose variables referenced by parameter '0' outside of their declaration scope
// return ref ptr(ref span);
Diagnostic(ErrorCode.ERR_EscapeCall, "ptr(ref span)").WithArguments("delegate*<ref System.Span<int>, ref System.Span<int>>", "0").WithLocation(10, 20),
// (10,28): error CS8168: Cannot return local 'span' by reference because it is not a ref local
// return ref ptr(ref span);
Diagnostic(ErrorCode.ERR_RefReturnLocal, "span").WithArguments("span").WithLocation(10, 28)
);
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_SafeToEscape()
{
var comp = CreateCompilationWithSpan(@"
using System;
unsafe
{
Span<int> s = stackalloc int[1];
s[0] = 1;
ref Span<int> sRef = ref ReturnPtrByRef(&ReturnByRef, ref s);
sRef[0] = 2;
Console.WriteLine(s[0]);
static ref Span<int> ReturnPtrByRef(delegate*<ref Span<int>, ref Span<int>> ptr, ref Span<int> s)
=> ref ptr(ref s);
static ref Span<int> ReturnByRef(ref Span<int> i) => ref i;
}", options: TestOptions.UnsafeReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref System.Span<int>, ref System.Span<int>>, ref System.Span<int>)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref System.Span<int>, ref System.Span<int>> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref System.Span<int>, ref System.Span<int>>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_RefReadonlyToRefError()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe
{
int i = 1;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
static ref int ReturnPtrByRef(delegate*<ref int, ref readonly int> ptr, ref int i)
=> ref ptr(ref i);
static ref readonly int ReturnByRef(ref int i) => ref i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (8,16): error CS8333: Cannot return method 'delegate*<ref int, ref readonly int>' by writable reference because it is a readonly variable
// => ref ptr(ref i);
Diagnostic(ErrorCode.ERR_RefReturnReadonlyNotField, "ptr(ref i)").WithArguments("method", "delegate*<ref int, ref readonly int>").WithLocation(8, 16)
);
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void ReturnByRefFromRefReturningMethod_RefToRefReadonly()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
ref readonly int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i);
i = 2;
System.Console.WriteLine(iRef);
static ref readonly int ReturnPtrByRef(delegate*<ref int, ref int> ptr, ref int i)
=> ref ptr(ref i);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref int, ref int>, ref int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref int, ref int>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void RefAssignment()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
delegate*<ref int, ref int> ptr = &ReturnByRef;
ref readonly int iRef = ref ptr(ref i);
i = 2;
System.Console.WriteLine(iRef);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldftn ""ref int Program.<<Main>$>g__ReturnByRef|0_0(ref int)""
IL_0008: stloc.1
IL_0009: ldloca.s V_0
IL_000b: ldloc.1
IL_000c: calli ""delegate*<ref int, ref int>""
IL_0011: ldc.i4.2
IL_0012: stloc.0
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void RefAssignmentThroughTernary()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
int i2 = 3;
delegate*<ref int, ref int> ptr = &ReturnByRef;
ref readonly int iRef = ref false ? ref i2 : ref ptr(ref i);
i = 2;
System.Console.WriteLine(iRef);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldftn ""ref int Program.<<Main>$>g__ReturnByRef|0_0(ref int)""
IL_0008: stloc.1
IL_0009: ldloca.s V_0
IL_000b: ldloc.1
IL_000c: calli ""delegate*<ref int, ref int>""
IL_0011: ldc.i4.2
IL_0012: stloc.0
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void RefReturnThroughTernary()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
int i2 = 3;
ref int iRef = ref ReturnPtrByRef(&ReturnByRef, ref i, ref i2);
iRef = 2;
System.Console.WriteLine(i);
static ref int ReturnPtrByRef(delegate*<ref int, ref int> ptr, ref int i, ref int i2)
=> ref false ? ref i2 : ref ptr(ref i);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("Program.<<Main>$>g__ReturnPtrByRef|0_0(delegate*<ref int, ref int>, ref int, ref int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: ldloc.0
IL_0004: calli ""delegate*<ref int, ref int>""
IL_0009: ret
}
");
}
[Fact, WorkItem(49315, "https://github.com/dotnet/roslyn/issues/49315")]
public void PassedAsByRefParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
int i = 1;
delegate*<ref int, ref int> ptr = &ReturnByRef;
ref readonly int iRef = ref ptr(ref ptr(ref i));
i = 2;
System.Console.WriteLine(iRef);
static ref int ReturnByRef(ref int i) => ref i;
}", expectedOutput: "2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1,
delegate*<ref int, ref int> V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldftn ""ref int Program.<<Main>$>g__ReturnByRef|0_0(ref int)""
IL_0008: dup
IL_0009: stloc.1
IL_000a: stloc.2
IL_000b: ldloca.s V_0
IL_000d: ldloc.2
IL_000e: calli ""delegate*<ref int, ref int>""
IL_0013: ldloc.1
IL_0014: calli ""delegate*<ref int, ref int>""
IL_0019: ldc.i4.2
IL_001a: stloc.0
IL_001b: ldind.i4
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: ret
}
");
}
[Fact, WorkItem(49760, "https://github.com/dotnet/roslyn/issues/49760")]
public void ReturnRefStructByValue_CanEscape()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
Console.WriteLine(ptrTest().field);
static BorrowedReference ptrTest()
{
delegate*<BorrowedReference> ptr = &test;
return ptr();
}
static BorrowedReference test() => new BorrowedReference() { field = 1 };
}
ref struct BorrowedReference {
public int field;
}
", expectedOutput: "1");
verifier.VerifyIL("Program.<<Main>$>g__ptrTest|0_0()", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldftn ""BorrowedReference Program.<<Main>$>g__test|0_1()""
IL_0006: calli ""delegate*<BorrowedReference>""
IL_000b: ret
}
");
}
[Fact, WorkItem(49760, "https://github.com/dotnet/roslyn/issues/49760")]
public void ReturnRefStructByValue_CannotEscape()
{
var comp = CreateCompilationWithSpan(@"
#pragma warning disable CS8321 // Unused local function ptrTest
using System;
unsafe
{
static Span<int> ptrTest()
{
Span<int> s = stackalloc int[1];
delegate*<Span<int>, Span<int>> ptr = &test;
return ptr(s);
}
static Span<int> ptrTest2(Span<int> s)
{
delegate*<Span<int>, Span<int>> ptr = &test;
return ptr(s);
}
static Span<int> test(Span<int> s) => s;
}
", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (10,16): error CS8347: Cannot use a result of 'delegate*<Span<int>, Span<int>>' in this context because it may expose variables referenced by parameter '0' outside of their declaration scope
// return ptr(s);
Diagnostic(ErrorCode.ERR_EscapeCall, "ptr(s)").WithArguments("delegate*<System.Span<int>, System.Span<int>>", "0").WithLocation(10, 16),
// (10,20): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// return ptr(s);
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(10, 20)
);
}
[Fact]
public void RefEscapeNestedArrayAccess()
{
var verifier = CompileAndVerifyFunctionPointers(@"
System.Console.WriteLine(M());
static ref int M()
{
var arr = new int[1]{40};
unsafe ref int N()
{
static ref int NN(ref int arg) => ref arg;
delegate*<ref int, ref int> ptr = &NN;
ref var r = ref ptr(ref arr[0]);
r += 2;
return ref r;
}
return ref N();
}
", expectedOutput: "42");
verifier.VerifyIL("Program.<<Main>$>g__N|0_1(ref Program.<>c__DisplayClass0_0)", @"
{
// Code size 32 (0x20)
.maxstack 4
.locals init (delegate*<ref int, ref int> V_0)
IL_0000: ldftn ""ref int Program.<<Main>$>g__NN|0_2(ref int)""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldfld ""int[] Program.<>c__DisplayClass0_0.arr""
IL_000d: ldc.i4.0
IL_000e: ldelema ""int""
IL_0013: ldloc.0
IL_0014: calli ""delegate*<ref int, ref int>""
IL_0019: dup
IL_001a: dup
IL_001b: ldind.i4
IL_001c: ldc.i4.2
IL_001d: add
IL_001e: stind.i4
IL_001f: ret
}
");
}
[Fact]
public void RefReturnInCompoundAssignment()
{
var verifier = CompileAndVerifyFunctionPointers(@"
unsafe
{
delegate*<ref int, ref int> ptr = &RefReturn;
int i = 0;
ptr(ref i) += 1;
System.Console.WriteLine(i);
static ref int RefReturn(ref int i) => ref i;
}", expectedOutput: "1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (int V_0, //i
delegate*<ref int, ref int> V_1)
IL_0000: ldftn ""ref int Program.<<Main>$>g__RefReturn|0_0(ref int)""
IL_0006: ldc.i4.0
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloca.s V_0
IL_000b: ldloc.1
IL_000c: calli ""delegate*<ref int, ref int>""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: stind.i4
IL_0016: ldloc.0
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: ret
}
");
}
[Fact]
public void InvalidReturnInCompoundAssignment()
{
var comp = CreateCompilationWithFunctionPointers(@"
unsafe
{
delegate*<int, int> ptr = &RefReturn;
int i = 0;
ptr(i) += 1;
static int RefReturn(int i) => i;
}", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (6,5): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// ptr(i) += 1;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "ptr(i)").WithLocation(6, 5)
);
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithNestedUnconstrainedTypeParameter()
{
var verifier = CompileAndVerifyFunctionPointers(@"
using System;
unsafe
{
test<int>(null);
test<int>(&intTest);
static void test<T>(delegate*<T, void> f)
{
Console.WriteLine(f == null);
Console.WriteLine(f is null);
}
static void intTest(int i) {}
}
", expectedOutput: @"
True
True
False
False");
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(delegate*<T, void>)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Fact, WorkItem(48765, "https://github.com/dotnet/roslyn/issues/48765")]
public void TypeOfFunctionPointerInAttribute()
{
var comp = CreateCompilationWithFunctionPointers(@"
using System;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
[Attr(typeof(delegate*<void>))]
[Attr(typeof(delegate*<void>[]))]
[Attr(typeof(C<delegate*<void>[]>))]
unsafe class Attr : System.Attribute
{
public Attr(System.Type type) {}
}
class C<T> {}
");
// https://github.com/dotnet/roslyn/issues/48765 tracks enabling support for this scenario. Currently, we don't know how to
// encode these in metadata, and may need to work with the runtime team to define a new format.
comp.VerifyDiagnostics(
// (4,7): error CS8911: Using a function pointer type in a 'typeof' in an attribute is not supported.
// [Attr(typeof(delegate*<void>))]
Diagnostic(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, "typeof(delegate*<void>)").WithLocation(4, 7),
// (5,7): error CS8911: Using a function pointer type in a 'typeof' in an attribute is not supported.
// [Attr(typeof(delegate*<void>[]))]
Diagnostic(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, "typeof(delegate*<void>[])").WithLocation(5, 7),
// (6,7): error CS8911: Using a function pointer type in a 'typeof' in an attribute is not supported.
// [Attr(typeof(C<delegate*<void>[]>))]
Diagnostic(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, "typeof(C<delegate*<void>[]>)").WithLocation(6, 7)
);
}
private static readonly Guid s_guid = new Guid("97F4DBD4-F6D1-4FAD-91B3-1001F92068E5");
private static readonly BlobContentId s_contentId = new BlobContentId(s_guid, 0x04030201);
private static void DefineInvalidSignatureAttributeIL(MetadataBuilder metadata, BlobBuilder ilBuilder, SignatureHeader headerToUseForM)
{
metadata.AddModule(
0,
metadata.GetOrAddString("ConsoleApplication.exe"),
metadata.GetOrAddGuid(s_guid),
default(GuidHandle),
default(GuidHandle));
metadata.AddAssembly(
metadata.GetOrAddString("ConsoleApplication"),
version: new Version(1, 0, 0, 0),
culture: default(StringHandle),
publicKey: metadata.GetOrAddBlob(new byte[0]),
flags: default(AssemblyFlags),
hashAlgorithm: AssemblyHashAlgorithm.Sha1);
var mscorlibAssemblyRef = metadata.AddAssemblyReference(
name: metadata.GetOrAddString("mscorlib"),
version: new Version(4, 0, 0, 0),
culture: default(StringHandle),
publicKeyOrToken: metadata.GetOrAddBlob(ImmutableArray.Create<byte>(0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89)),
flags: default(AssemblyFlags),
hashValue: default(BlobHandle));
var systemObjectTypeRef = metadata.AddTypeReference(
mscorlibAssemblyRef,
metadata.GetOrAddString("System"),
metadata.GetOrAddString("Object"));
var systemConsoleTypeRefHandle = metadata.AddTypeReference(
mscorlibAssemblyRef,
metadata.GetOrAddString("System"),
metadata.GetOrAddString("Console"));
var consoleWriteLineSignature = new BlobBuilder();
new BlobEncoder(consoleWriteLineSignature).
MethodSignature().
Parameters(1,
returnType => returnType.Void(),
parameters => parameters.AddParameter().Type().String());
var consoleWriteLineMemberRef = metadata.AddMemberReference(
systemConsoleTypeRefHandle,
metadata.GetOrAddString("WriteLine"),
metadata.GetOrAddBlob(consoleWriteLineSignature));
var parameterlessCtorSignature = new BlobBuilder();
new BlobEncoder(parameterlessCtorSignature).
MethodSignature(isInstanceMethod: true).
Parameters(0, returnType => returnType.Void(), parameters => { });
var parameterlessCtorBlobIndex = metadata.GetOrAddBlob(parameterlessCtorSignature);
var objectCtorMemberRef = metadata.AddMemberReference(
systemObjectTypeRef,
metadata.GetOrAddString(".ctor"),
parameterlessCtorBlobIndex);
// Signature for M() with an _invalid_ SignatureAttribute
var mSignature = new BlobBuilder();
var mBlobBuilder = new BlobEncoder(mSignature);
mBlobBuilder.Builder.WriteByte(headerToUseForM.RawValue);
var mParameterEncoder = new MethodSignatureEncoder(mBlobBuilder.Builder, hasVarArgs: false);
mParameterEncoder.Parameters(parameterCount: 0, returnType => returnType.Void(), parameters => { });
var methodBodyStream = new MethodBodyStreamEncoder(ilBuilder);
var codeBuilder = new BlobBuilder();
InstructionEncoder il;
//
// Program::.ctor
//
il = new InstructionEncoder(codeBuilder);
// ldarg.0
il.LoadArgument(0);
// call instance void [mscorlib]System.Object::.ctor()
il.Call(objectCtorMemberRef);
// ret
il.OpCode(ILOpCode.Ret);
int ctorBodyOffset = methodBodyStream.AddMethodBody(il);
codeBuilder.Clear();
//
// Program::M
//
il = new InstructionEncoder(codeBuilder);
// ldstr "M"
il.LoadString(metadata.GetOrAddUserString("M"));
// call void [mscorlib]System.Console::WriteLine(string)
il.Call(consoleWriteLineMemberRef);
// ret
il.OpCode(ILOpCode.Ret);
int mBodyOffset = methodBodyStream.AddMethodBody(il);
codeBuilder.Clear();
var mMethodDef = metadata.AddMethodDefinition(
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig,
MethodImplAttributes.IL | MethodImplAttributes.Managed,
metadata.GetOrAddString("M"),
metadata.GetOrAddBlob(mSignature),
mBodyOffset,
parameterList: default(ParameterHandle));
var ctorDef = metadata.AddMethodDefinition(
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
MethodImplAttributes.IL | MethodImplAttributes.Managed,
metadata.GetOrAddString(".ctor"),
parameterlessCtorBlobIndex,
ctorBodyOffset,
parameterList: default(ParameterHandle));
metadata.AddTypeDefinition(
default(TypeAttributes),
default(StringHandle),
metadata.GetOrAddString("<Module>"),
baseType: default(EntityHandle),
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: mMethodDef);
metadata.AddTypeDefinition(
TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.BeforeFieldInit,
metadata.GetOrAddString("ConsoleApplication"),
metadata.GetOrAddString("Program"),
systemObjectTypeRef,
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: mMethodDef);
}
private static void WritePEImage(
Stream peStream,
MetadataBuilder metadataBuilder,
BlobBuilder ilBuilder)
{
var peHeaderBuilder = new PEHeaderBuilder(imageCharacteristics: Characteristics.Dll);
var peBuilder = new ManagedPEBuilder(
peHeaderBuilder,
new MetadataRootBuilder(metadataBuilder),
ilBuilder,
flags: CorFlags.ILOnly,
deterministicIdProvider: content => s_contentId);
var peBlob = new BlobBuilder();
var contentId = peBuilder.Serialize(peBlob);
peBlob.WriteContentTo(peStream);
}
private static ModuleSymbol GetSourceModule(CompilationVerifier verifier)
{
return ((CSharpCompilation)verifier.Compilation).SourceModule;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/VisualBasicTest/Structure/CompilationUnitStructureTests.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 CompilationUnitStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of CompilationUnitSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New CompilationUnitStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestImports() As Task
Const code = "
{|span:$$Imports System
Imports System.Linq|}
Class C1
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Imports ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestImportsAliases() As Task
Const code = "
{|span:$$Imports System
Imports linq = System.Linq|}
Class C1
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Imports ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestComments() As Task
Const code = "
{|span1:$$'Top
'Of
'File|}
Class C
End Class
{|span2:'Bottom
'Of
'File|}
"
Await VerifyBlockSpansAsync(code,
Region("span1", "' Top ...", autoCollapse:=True),
Region("span2", "' Bottom ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestImportsAndComments() As Task
Const code = "
{|span1:$$'Top
'Of
'File|}
{|span2:Imports System
Imports System.Linq|}
{|span3:'Bottom
'Of
'File|}
"
Await VerifyBlockSpansAsync(code,
Region("span1", "' Top ...", autoCollapse:=True),
Region("span2", "Imports ...", autoCollapse:=True),
Region("span3", "' Bottom ...", autoCollapse:=True))
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class CompilationUnitStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of CompilationUnitSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New CompilationUnitStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestImports() As Task
Const code = "
{|span:$$Imports System
Imports System.Linq|}
Class C1
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Imports ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestImportsAliases() As Task
Const code = "
{|span:$$Imports System
Imports linq = System.Linq|}
Class C1
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Imports ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestComments() As Task
Const code = "
{|span1:$$'Top
'Of
'File|}
Class C
End Class
{|span2:'Bottom
'Of
'File|}
"
Await VerifyBlockSpansAsync(code,
Region("span1", "' Top ...", autoCollapse:=True),
Region("span2", "' Bottom ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestImportsAndComments() As Task
Const code = "
{|span1:$$'Top
'Of
'File|}
{|span2:Imports System
Imports System.Linq|}
{|span3:'Bottom
'Of
'File|}
"
Await VerifyBlockSpansAsync(code,
Region("span1", "' Top ...", autoCollapse:=True),
Region("span2", "Imports ...", autoCollapse:=True),
Region("span3", "' Bottom ...", autoCollapse:=True))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Test/Resources/Core/SymbolsTests/TypeForwarders/TypeForwarder3.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(Base))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(GenericBase<>))]
public class Derived : Base
{
};
public class GenericDerived<S> : GenericBase<S>
{
};
public class GenericDerived1<S1, S2> : GenericBase<S1>.NestedGenericBase<S2>
{
};
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(Base))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(GenericBase<>))]
public class Derived : Base
{
};
public class GenericDerived<S> : GenericBase<S>
{
};
public class GenericDerived1<S1, S2> : GenericBase<S1>.NestedGenericBase<S2>
{
};
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core/Shared/Tagging/Tags/PreviewWarningTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal class PreviewWarningTag : TextMarkerTag
{
public const string TagId = "RoslynPreviewWarningTag";
public static readonly PreviewWarningTag Instance = new();
private PreviewWarningTag()
: base(TagId)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal class PreviewWarningTag : TextMarkerTag
{
public const string TagId = "RoslynPreviewWarningTag";
public static readonly PreviewWarningTag Instance = new();
private PreviewWarningTag()
: base(TagId)
{
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxLastTokenReplacer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal class SyntaxLastTokenReplacer : CSharpSyntaxRewriter
{
private readonly SyntaxToken _oldToken;
private readonly SyntaxToken _newToken;
private int _count = 1;
private bool _found;
private SyntaxLastTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken)
{
_oldToken = oldToken;
_newToken = newToken;
}
internal static TRoot Replace<TRoot>(TRoot root, SyntaxToken newToken)
where TRoot : CSharpSyntaxNode
{
var oldToken = root.GetLastToken();
var replacer = new SyntaxLastTokenReplacer(oldToken, newToken);
var newRoot = (TRoot)replacer.Visit(root);
Debug.Assert(replacer._found);
return newRoot;
}
private static int CountNonNullSlots(CSharpSyntaxNode node)
{
return node.ChildNodesAndTokens().Count;
}
public override CSharpSyntaxNode Visit(CSharpSyntaxNode node)
{
if (node != null && !_found)
{
_count--;
if (_count == 0)
{
var token = node as SyntaxToken;
if (token != null)
{
Debug.Assert(token == _oldToken);
_found = true;
return _newToken;
}
_count += CountNonNullSlots(node);
return base.Visit(node);
}
}
return node;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal class SyntaxLastTokenReplacer : CSharpSyntaxRewriter
{
private readonly SyntaxToken _oldToken;
private readonly SyntaxToken _newToken;
private int _count = 1;
private bool _found;
private SyntaxLastTokenReplacer(SyntaxToken oldToken, SyntaxToken newToken)
{
_oldToken = oldToken;
_newToken = newToken;
}
internal static TRoot Replace<TRoot>(TRoot root, SyntaxToken newToken)
where TRoot : CSharpSyntaxNode
{
var oldToken = root.GetLastToken();
var replacer = new SyntaxLastTokenReplacer(oldToken, newToken);
var newRoot = (TRoot)replacer.Visit(root);
Debug.Assert(replacer._found);
return newRoot;
}
private static int CountNonNullSlots(CSharpSyntaxNode node)
{
return node.ChildNodesAndTokens().Count;
}
public override CSharpSyntaxNode Visit(CSharpSyntaxNode node)
{
if (node != null && !_found)
{
_count--;
if (_count == 0)
{
var token = node as SyntaxToken;
if (token != null)
{
Debug.Assert(token == _oldToken);
_found = true;
return _newToken;
}
_count += CountNonNullSlots(node);
return base.Visit(node);
}
}
return node;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/AbstractNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class AbstractNode : TreeType
{
public readonly List<Field> Fields = new List<Field>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class AbstractNode : TreeType
{
public readonly List<Field> Fields = new List<Field>();
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/TestUtilities2/Utilities/TestNotificationService.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.Notification
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Friend Class TestNotificationService
Implements INotificationService
Public MessageText As String
Public MessageTitle As String
Public MessageSeverity As NotificationSeverity
Public ConfirmBoxText As String
Public ConfirmBoxTitle As String
Public ConfirmBoxSeverity As NotificationSeverity
Public DesiredConfirmBoxResult As Boolean
Public Sub SendNotification(message As String, Optional title As String = Nothing, Optional severity As NotificationSeverity = NotificationSeverity.Warning) Implements INotificationService.SendNotification
MessageText = message
MessageTitle = title
MessageSeverity = severity
End Sub
Public Function ConfirmMessageBox(message As String, Optional title As String = Nothing, Optional severity As NotificationSeverity = NotificationSeverity.Warning) As Boolean Implements INotificationService.ConfirmMessageBox
ConfirmBoxText = message
ConfirmBoxTitle = title
ConfirmBoxSeverity = severity
Return DesiredConfirmBoxResult
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.Notification
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Friend Class TestNotificationService
Implements INotificationService
Public MessageText As String
Public MessageTitle As String
Public MessageSeverity As NotificationSeverity
Public ConfirmBoxText As String
Public ConfirmBoxTitle As String
Public ConfirmBoxSeverity As NotificationSeverity
Public DesiredConfirmBoxResult As Boolean
Public Sub SendNotification(message As String, Optional title As String = Nothing, Optional severity As NotificationSeverity = NotificationSeverity.Warning) Implements INotificationService.SendNotification
MessageText = message
MessageTitle = title
MessageSeverity = severity
End Sub
Public Function ConfirmMessageBox(message As String, Optional title As String = Nothing, Optional severity As NotificationSeverity = NotificationSeverity.Warning) As Boolean Implements INotificationService.ConfirmMessageBox
ConfirmBoxText = message
ConfirmBoxTitle = title
ConfirmBoxSeverity = severity
Return DesiredConfirmBoxResult
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/MethodTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MethodTests
Inherits BasicTestBase
<Fact>
Public Sub Methods1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1()
End Sub
Protected MustOverride Function m2$()
Friend NotOverridable Overloads Function m3() As D
End Function
Protected Friend Overridable Shadows Sub m4()
End Sub
Protected Overrides Sub m5()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Shared Function m6()
End Function
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(8, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim ctor = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, ctor.ContainingSymbol)
Assert.Same(classC, ctor.ContainingType)
Assert.Equal(".ctor", ctor.Name)
Assert.Equal(MethodKind.Constructor, ctor.MethodKind)
Assert.Equal(Accessibility.Public, ctor.DeclaredAccessibility)
Assert.Equal(0, ctor.TypeParameters.Length)
Assert.Equal(0, ctor.TypeArguments.Length)
Assert.False(ctor.IsGenericMethod)
Assert.False(ctor.IsMustOverride)
Assert.False(ctor.IsNotOverridable)
Assert.False(ctor.IsOverridable)
Assert.False(ctor.IsOverrides)
Assert.False(ctor.IsShared)
Assert.False(ctor.IsOverloads)
Assert.True(ctor.IsSub)
Assert.Equal("System.Void", ctor.ReturnType.ToTestDisplayString())
Assert.Equal(0, ctor.Parameters.Length)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.False(m1.IsRuntimeImplemented()) ' test for default implementation
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.True(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsSub)
Assert.False(m2.IsOverloads)
Assert.Equal("System.String", m2.ReturnType.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(Accessibility.Friend, m3.DeclaredAccessibility)
Assert.False(m3.IsMustOverride)
Assert.True(m3.IsNotOverridable)
Assert.False(m3.IsOverridable)
Assert.False(m3.IsOverrides)
Assert.False(m3.IsShared)
Assert.True(m3.IsOverloads)
Assert.False(m3.IsSub)
Assert.Equal("C.D", m3.ReturnType.ToTestDisplayString())
Dim m4 = DirectCast(membersOfC(5), MethodSymbol)
Assert.Equal(Accessibility.ProtectedOrFriend, m4.DeclaredAccessibility)
Assert.False(m4.IsMustOverride)
Assert.False(m4.IsNotOverridable)
Assert.True(m4.IsOverridable)
Assert.False(m4.IsOverrides)
Assert.False(m4.IsShared)
Assert.False(m4.IsOverloads)
Assert.True(m4.IsSub)
Dim m5 = DirectCast(membersOfC(6), MethodSymbol)
Assert.Equal(Accessibility.Protected, m5.DeclaredAccessibility)
Assert.False(m5.IsMustOverride)
Assert.False(m5.IsNotOverridable)
Assert.False(m5.IsOverridable)
Assert.True(m5.IsOverrides)
Assert.False(m5.IsShared)
Assert.True(m5.IsOverloads)
Assert.True(m5.IsSub)
Dim m6 = DirectCast(membersOfC(7), MethodSymbol)
Assert.Equal(Accessibility.Friend, m6.DeclaredAccessibility)
Assert.False(m6.IsMustOverride)
Assert.False(m6.IsNotOverridable)
Assert.False(m6.IsOverridable)
Assert.False(m6.IsOverrides)
Assert.True(m6.IsShared)
Assert.False(m6.IsSub)
Assert.Equal("System.Object", m6.ReturnType.ToTestDisplayString())
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<expected>
BC31411: 'C' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Public Partial Class C
~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Friend NotOverridable Overloads Function m3() As D
~~
BC30508: 'm3' cannot expose type 'C.D' in namespace '<Default>' through class 'C'.
Friend NotOverridable Overloads Function m3() As D
~
BC30284: sub 'm5' cannot be declared 'Overrides' because it does not override a sub in a base class.
Protected Overrides Sub m5()
~~
</expected>)
End Sub
<Fact>
Public Sub Methods2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Module M
Sub m1()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim moduleM = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim m1 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m1.ContainingSymbol)
Assert.Same(moduleM, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared) ' methods in a module are implicitly Shared
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub Constructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Public Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Sub New(x as string, y as integer)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(2, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim m2 = DirectCast(membersOfC(1), MethodSymbol)
Assert.Same(classC, m2.ContainingSymbol)
Assert.Same(classC, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Friend, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(2, m2.Parameters.Length)
Assert.Equal("x", m2.Parameters(0).Name)
Assert.Equal("System.String", m2.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("y", m2.Parameters(1).Name)
Assert.Equal("System.Int32", m2.Parameters(1).Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub SharedConstructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Shared Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Module M
Sub New()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim moduleM = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".cctor", m1.Name)
Assert.Equal(MethodKind.SharedConstructor, m1.MethodKind)
Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m2 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m2.ContainingSymbol)
Assert.Same(moduleM, m2.ContainingType)
Assert.Equal(".cctor", m2.Name)
Assert.Equal(MethodKind.SharedConstructor, m2.MethodKind)
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.True(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub DefaultConstructors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Class C
End Class
Public MustInherit Class D
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Structure S
End Structure
Public Module M
End Module
Public Interface I
End Interface
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Assert.Equal("C", classC.Name)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim classD = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Dim membersOfD = classD.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfD.Length)
Dim m2 = DirectCast(membersOfD(0), MethodSymbol)
Assert.Same(classD, m2.ContainingSymbol)
Assert.Same(classD, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
Dim interfaceI = DirectCast(globalNSmembers(2), NamedTypeSymbol)
Assert.Equal("I", interfaceI.Name)
Assert.Equal(0, interfaceI.GetMembers().Length())
Dim moduleM = DirectCast(globalNSmembers(3), NamedTypeSymbol)
Assert.Equal("M", moduleM.Name)
Assert.Equal(0, moduleM.GetMembers().Length())
Dim structureS = DirectCast(globalNSmembers(4), NamedTypeSymbol)
Assert.Equal("S", structureS.Name)
Assert.Equal(1, structureS.GetMembers().Length()) ' Implicit parameterless constructor
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1(x as D, ByRef y As Integer)
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Sub m2(a(), z, byref q, ParamArray w())
End Sub
Sub m3(x)
End Sub
Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Equal("m1", m1.Name)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.Same(classD, m1p1.Type)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Int32", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Int32", m1p2.ToTestDisplayString())
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(4, m2.Parameters.Length)
Dim m2p1 = m2.Parameters(0)
Assert.Equal("a", m2p1.Name)
Assert.Same(m2, m2p1.ContainingSymbol)
Assert.False(m2p1.HasExplicitDefaultValue)
Assert.False(m2p1.IsOptional)
Assert.False(m2p1.IsParamArray)
Assert.False(m2p1.IsByRef)
Assert.Equal("System.Object()", m2p1.Type.ToTestDisplayString())
Dim m2p2 = m2.Parameters(1)
Assert.Equal("z", m2p2.Name)
Assert.Same(m2, m2p2.ContainingSymbol)
Assert.False(m2p2.HasExplicitDefaultValue)
Assert.False(m2p2.IsOptional)
Assert.False(m2p2.IsParamArray)
Assert.Equal("System.Object", m2p2.Type.ToTestDisplayString())
Dim m2p3 = m2.Parameters(2)
Assert.Equal("q", m2p3.Name)
Assert.Same(m2, m2p3.ContainingSymbol)
Assert.False(m2p3.HasExplicitDefaultValue)
Assert.False(m2p3.IsOptional)
Assert.False(m2p3.IsParamArray)
Assert.True(m2p3.IsByRef)
Assert.Equal("System.Object", m2p3.Type.ToTestDisplayString())
Assert.Equal("ByRef q As System.Object", m2p3.ToTestDisplayString())
Dim m2p4 = m2.Parameters(3)
Assert.Equal("w", m2p4.Name)
Assert.Same(m2, m2p4.ContainingSymbol)
Assert.False(m2p4.HasExplicitDefaultValue)
Assert.False(m2p4.IsOptional)
Assert.True(m2p4.IsParamArray)
Assert.Equal(TypeKind.Array, m2p4.Type.TypeKind)
Assert.Equal("System.Object", DirectCast(m2p4.Type, ArrayTypeSymbol).ElementType.ToTestDisplayString())
Assert.Equal("System.Object()", m2p4.Type.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(1, m3.Parameters.Length)
Dim m3p1 = m3.Parameters(0)
Assert.Equal("x", m3p1.Name)
Assert.Same(m3, m3p1.ContainingSymbol)
Assert.False(m3p1.HasExplicitDefaultValue)
Assert.False(m3p1.IsOptional)
Assert.False(m3p1.IsParamArray)
Assert.Equal("System.Object", m3p1.Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodByRefParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Structure S
Function M(Byref x as Object, ByRef y As Byte) As Long
Return 0
End Function
End Structure
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim typeS = DirectCast(globalNS.GetTypeMembers("S").Single(), NamedTypeSymbol)
Dim m1 = DirectCast(typeS.GetMembers("M").Single(), MethodSymbol)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.True(m1p1.IsByRef)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Byte", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Byte", m1p2.ToTestDisplayString())
Assert.Equal("ValueType", m1p2.Type.BaseType.Name)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodTypeParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Partial Class C
Function m1(Of T, U)(x1 As T) As IEnumerable(Of U)
End Function
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(3, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.True(m1.IsGenericMethod)
Assert.Equal(2, m1.TypeParameters.Length)
Dim tpT = m1.TypeParameters(0)
Assert.Equal("T", tpT.Name)
Assert.Same(m1, tpT.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpT.Variance)
Dim tpU = m1.TypeParameters(1)
Assert.Equal("U", tpU.Name)
Assert.Same(m1, tpU.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpU.Variance)
Dim paramX1 = m1.Parameters(0)
Assert.Same(tpT, paramX1.Type)
Assert.Equal("T", paramX1.Type.ToTestDisplayString())
Assert.Same(tpU, DirectCast(m1.ReturnType, NamedTypeSymbol).TypeArguments(0))
Assert.Equal("System.Collections.Generic.IEnumerable(Of U)", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub ConstructGenericMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Class C(Of W)
Function m1(Of T, U)(p1 As T, p2 as W) As KeyValuePair(Of W, U))
End Function
Sub m2()
End Sub
Public Class D(Of X)
Sub m3(Of T)(p1 As T)
End Sub
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim constructedC = classC.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_Int32)}).AsImmutableOrNull())
Dim m1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Dim m2 = DirectCast(constructedC.GetMembers("m2")(0), MethodSymbol)
Assert.True(m1.CanConstruct)
Assert.True(m1.OriginalDefinition.CanConstruct)
Assert.Same(m1, m1.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.NotEqual(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0))
Assert.Same(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0).OriginalDefinition)
Assert.Same(m1, m1.TypeParameters(0).ContainingSymbol)
Assert.Equal(2, m1.Arity)
Assert.Same(m1, m1.Construct(m1.TypeParameters(0), m1.TypeParameters(1)))
Dim m1_1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Assert.Equal(m1, m1_1)
Assert.NotSame(m1, m1_1) ' Checks below need equal, but not identical symbols to test target scenarios!
Assert.Same(m1, m1.Construct(m1_1.TypeParameters(0), m1_1.TypeParameters(1)))
Dim alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(1), m1_1.TypeParameters(0))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(1))
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(0))
alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(0), constructedC)
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(0))
Assert.Same(alphaConstructedM1.TypeArguments(1), constructedC)
alphaConstructedM1 = m1.Construct(constructedC, m1_1.TypeParameters(1))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), constructedC)
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(1))
Assert.False(m2.CanConstruct)
Assert.False(m2.OriginalDefinition.CanConstruct)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.Throws(Of InvalidOperationException)(Sub() m2.OriginalDefinition.Construct(classC))
Assert.Throws(Of InvalidOperationException)(Sub() m2.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.OriginalDefinition.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.Construct(classC))
Dim constructedC_d = constructedC.GetTypeMembers("D").Single()
Dim m3 = DirectCast(constructedC_d.GetMembers("m3").Single(), MethodSymbol)
Assert.Equal(1, m3.Arity)
Assert.False(m3.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() m3.Construct(classC))
Dim d = classC.GetTypeMembers("D").Single()
m3 = DirectCast(d.GetMembers("m3").Single(), MethodSymbol)
Dim alphaConstructedM3 = m3.Construct(m1.TypeParameters(0))
Assert.NotSame(m3, alphaConstructedM3)
Assert.Same(m3, alphaConstructedM3.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), alphaConstructedM3.TypeArguments(0))
Assert.Equal("T", m1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", m1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, U)", m1.ReturnType.ToTestDisplayString())
Assert.Equal("T", m1.TypeParameters(0).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.Equal("U", m1.TypeParameters(1).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(1), m1.TypeArguments(1))
Assert.Same(m1, m1.ConstructedFrom)
Dim constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.Equal("System.String", constructedM1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", constructedM1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ReturnType.ToTestDisplayString())
Assert.Equal("T", constructedM1.TypeParameters(0).ToTestDisplayString())
Assert.Equal("System.String", constructedM1.TypeArguments(0).ToTestDisplayString())
Assert.Equal("U", constructedM1.TypeParameters(1).ToTestDisplayString())
Assert.Equal("System.Boolean", constructedM1.TypeArguments(1).ToTestDisplayString())
Assert.Same(m1, constructedM1.ConstructedFrom)
Assert.Equal("Function C(Of System.Int32).m1(Of System.String, System.Boolean)(p1 As System.String, p2 As System.Int32) As System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ToTestDisplayString())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
' Try wrong arity.
Assert.Throws(Of ArgumentException)(Sub()
Dim constructedM1WrongArity = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String)}).AsImmutableOrNull())
End Sub)
' Try identity substitution.
Dim identityM1 = m1.Construct(m1.OriginalDefinition.TypeParameters.As(Of TypeSymbol)())
Assert.NotEqual(m1, identityM1)
Assert.Same(m1, identityM1.ConstructedFrom)
m1 = DirectCast(classC.GetMembers("m1").Single(), MethodSymbol)
identityM1 = m1.Construct(m1.TypeParameters.As(Of TypeSymbol)())
Assert.Same(m1, identityM1)
constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
Dim constructedM1_2 = m1.Construct(compilation.GetSpecialType(SpecialType.System_Byte), compilation.GetSpecialType(SpecialType.System_Boolean))
Dim constructedM1_3 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.NotEqual(constructedM1, constructedM1_2)
Assert.Equal(constructedM1, constructedM1_3)
Dim p1 = constructedM1.Parameters(0)
Assert.Equal(0, p1.Ordinal)
Assert.Same(constructedM1, p1.ContainingSymbol)
Assert.Equal(p1, p1)
Assert.Equal(p1, constructedM1_3.Parameters(0))
Assert.Equal(p1.GetHashCode(), constructedM1_3.Parameters(0).GetHashCode())
Assert.NotEqual(m1.Parameters(0), p1)
Assert.NotEqual(constructedM1_2.Parameters(0), p1)
Dim constructedM3 = m3.Construct(compilation.GetSpecialType(SpecialType.System_String))
Assert.NotEqual(constructedM3.Parameters(0), p1)
End Sub
<Fact>
Public Sub InterfaceImplements01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Namespace NS
Public Class Abc
End Class
Public Interface IGoo(Of T)
Sub I1Sub1(ByRef p As T)
End Interface
Public Interface I1
Sub I1Sub1(ByRef p As String)
Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2 As Object()) As Integer
End Interface
Public Interface I2
Inherits I1
Sub I2Sub1()
Function I2Func1(ByRef p1 As aBC) As AbC
End Interface
End Namespace
</file>
<file name="b.vb">
Imports System.Collections.Generic
Namespace NS.NS1
Class Impl
Implements I2, IGoo(Of String)
Public Sub Sub1(ByRef p As String) Implements I1.I1Sub1, IGoo(Of String).I1Sub1
End Sub
Public Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2() As Object) As Integer Implements I1.I1Func1
Return p1
End Function
Public Function I2Func1(ByRef p1 As ABc) As ABC Implements I2.I2Func1
Return Nothing
End Function
Public Sub I2Sub1() Implements I2.I2Sub1
End Sub
End Class
Structure StructImpl(Of T)
Implements IGoo(Of T)
Public Sub Sub1(ByRef p As T) Implements IGoo(Of T).I1Sub1
End Sub
End Structure
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").AsEnumerable().SingleOrDefault(), NamespaceSymbol)
Dim ns1 = DirectCast(ns.GetMembers("NS1").Single(), NamespaceSymbol)
Dim classImpl = DirectCast(ns1.GetTypeMembers("impl").Single(), NamedTypeSymbol)
'direct interfaces
Assert.Equal(2, classImpl.Interfaces.Length)
Dim itfc = DirectCast(classImpl.Interfaces(0), NamedTypeSymbol)
Assert.Equal(1, itfc.Interfaces.Length)
itfc = DirectCast(itfc.Interfaces(0), NamedTypeSymbol)
Assert.Equal("I1", itfc.Name)
Dim mem1 = DirectCast(classImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(2, mem1.ExplicitInterfaceImplementation.Count)
mem1 = DirectCast(classImpl.GetMembers("i2Func1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count)
Dim param = DirectCast(mem1.Parameters(0), ParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal("ByRef " & param.Name & " As NS.Abc", param.ToTestDisplayString()) ' use case of declare's name
Dim structImpl = DirectCast(ns1.GetTypeMembers("structimpl").Single(), NamedTypeSymbol)
Assert.Equal(1, structImpl.Interfaces.Length)
Dim mem2 = DirectCast(structImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<WorkItem(537444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537444")>
<Fact>
Public Sub DeclareFunction01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Explicit
Imports System
Imports System.Runtime.InteropServices
Public Structure S1
Public strVar As String
Public x As Integer
End Structure
Namespace NS
Friend Module MyMod
Declare Ansi Function VerifyString2 Lib "AttrUsgOthM010DLL.dll" (ByRef Arg As S1, ByVal Op As Integer) As String
End Module
Class cls1
Overloads Declare Sub Goo Lib "someLib" ()
Overloads Sub goo(ByRef arg As Integer)
' ...
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim nsNS = DirectCast(compilation.Assembly.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim modOfNS = DirectCast(nsNS.GetMembers("MyMod").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(modOfNS.GetMembers().First(), MethodSymbol)
Assert.Equal("VerifyString2", mem1.Name)
' TODO: add more verification when this is working
End Sub
<Fact>
Public Sub CodepageOptionUnicodeMembers01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Module Module2
Sub ÛÊÛÄÁÍäá() ' 1067
Console.WriteLine (CStr(AscW("ÛÊÛÄÁÍäá")))
End Sub
End Module
Class Class1
Public Shared Sub ŒŸõ()
Console.WriteLine(CStr(AscW("ŒŸõ"))) ' 26908
End Sub
Friend Function [Widening](ByVal Ÿü As Short) As à–¾ 'invalid char in Dev10
Return New à–¾(Ÿü)
End Function
End Class
Structure ĵÁiÛE
Const str1 As String = "ĵÁiÛE" ' 1044
Dim i As Integer
End Structure
Public Class [Narrowing] 'êàê èäåíòèôèêàòîð.
Public ñëîâî As [CULng]
End Class
Public Structure [CULng]
Public [UInteger] As Integer
End Structure
</file>
</compilation>)
Dim glbNS = compilation.Assembly.GlobalNamespace
Dim type1 = DirectCast(glbNS.GetMembers("Module2").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(type1.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem1.DeclaredAccessibility)
Assert.True(mem1.IsSub)
Assert.Equal("Sub Module2.ÛÊÛÄÁÍäá()", mem1.ToTestDisplayString())
Dim type2 = DirectCast(glbNS.GetMembers("Class1").Single(), NamedTypeSymbol)
Dim mem2 = DirectCast(type2.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem2.DeclaredAccessibility)
'Assert.Equal("ŒŸõ", mem2.Name) - TODO: Code Page issue
Dim type3 = DirectCast(glbNS.GetTypeMembers("ĵÁiÛE").Single(), NamedTypeSymbol)
Dim mem3 = DirectCast(type3.GetMembers("Str1").Single(), FieldSymbol)
Assert.True(mem3.IsConst)
Assert.Equal("ĵÁiÛE.str1 As System.String", mem3.ToTestDisplayString())
Dim type4 = DirectCast(glbNS.GetTypeMembers("Narrowing").Single(), NamedTypeSymbol)
Dim mem4 = DirectCast(type4.GetMembers("ñëîâî").Single(), FieldSymbol)
Assert.Equal(TypeKind.Structure, mem4.Type.TypeKind)
End Sub
<WorkItem(537466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537466")>
<Fact>
Public Sub DefaultAccessibility01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Interface GI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class GC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Class
Structure GS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Structure
Namespace NS
Interface NI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class NC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Class
Structure NS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Structure
End Namespace
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
' interface - public
Dim typemem = DirectCast(globalNS.GetTypeMembers("GI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
Dim mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Class - field (private), other - public
typemem = DirectCast(globalNS.GetTypeMembers("GC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Struct - public
typemem = DirectCast(globalNS.GetTypeMembers("GS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
Dim nsNS = DirectCast(globalNS.GetMembers("NS").Single(), NamespaceSymbol)
typemem = DirectCast(nsNS.GetTypeMembers("NI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
End Sub
<Fact>
Public Sub OverloadsAndOverrides01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim derive = New NS.C2()
derive.Goo(1) ' call derived Goo
derive.Bar(1) ' call derived Bar
derive.Boo(1) ' call derived Boo
derive.VGoo(1) ' call derived VGoo
derive.VBar(1) ' call derived VBar
derive.VBoo(1) ' call derived VBoo
Console.WriteLine("-------------")
Dim base As NS.C1 = New NS.C2()
base.Goo(1) ' call base Goo
base.Bar(1) ' call base Bar
base.Boo(1) ' call base Boo
base.VGoo(1) ' call base Goo
base.VBar(1) ' call D
base.VBoo(1) ' call D
End Sub
End Module
Namespace NS
Public Class C1
Public Sub Goo(ByVal p As Integer)
Console.WriteLine("Base - Goo")
End Sub
Public Sub Bar(ByVal p As Integer)
Console.WriteLine("Base - Bar")
End Sub
Public Sub Boo(ByVal p As Integer)
Console.WriteLine("Base - Boo")
End Sub
Public Overridable Sub VGoo(ByVal p As Integer)
Console.WriteLine("Base - VGoo")
End Sub
Public Overridable Sub VBar(ByVal p As Integer)
Console.WriteLine("Base - VBar")
End Sub
Public Overridable Sub VBoo(ByVal p As Integer)
Console.WriteLine("Base - VBoo")
End Sub
End Class
Public Class C2
Inherits C1
Public Shadows Sub Goo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows Goo")
End Sub
Public Overloads Sub Bar(Optional ByVal p As Integer = 1)
Console.WriteLine("Derived - Overloads Bar")
End Sub
' warning
Public Sub Boo(Optional ByVal p As Integer = 2)
Console.WriteLine("Derived - Boo")
End Sub
' not virtual
Public Shadows Sub VGoo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows VGoo")
End Sub
' hidebysig and virtual
Public Overloads Overrides Sub VBar(ByVal p As Integer)
Console.WriteLine("Derived - Overloads Overrides VBar")
End Sub
' virtual
Public Overrides Sub VBoo(ByVal p As Integer)
Console.WriteLine("Derived - Overrides VBoo")
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetTypeMembers("C1").Single(), NamedTypeSymbol)
Dim mem = DirectCast(type1.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverridable)
mem = DirectCast(type1.GetMembers("VGoo").Single(), MethodSymbol)
Assert.True(mem.IsOverridable)
Dim type2 = DirectCast(ns.GetTypeMembers("C2").Single(), NamedTypeSymbol)
mem = DirectCast(type2.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Bar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Boo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
' overridable
mem = DirectCast(type2.GetMembers("VGoo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
Assert.False(mem.IsOverrides)
Assert.False(mem.IsOverridable)
mem = DirectCast(type2.GetMembers("VBar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
mem = DirectCast(type2.GetMembers("VBoo").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
End Sub
<Fact>
Public Sub Bug2820()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Class Class1
sub Test(x as T)
End sub
End Class
</file>
</compilation>)
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim test = class1.GetMembers("Test").OfType(Of MethodSymbol)().Single()
Assert.Equal("T", test.Parameters(0).Type.Name)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Sub baNana()
End Sub
Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Sub baNANa(xyz as String)
End Sub
Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' No "Overloads", so all methods should match first overloads in first source file
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNana").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNana" (from first file supplied to compilation).
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
If m.Parameters.Any Then
Assert.NotEqual("baNana", m.Name)
End If
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub baNANa(xyz as String)
End Sub
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overloads" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Overridable Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overrides Sub baNANa(xyz as String, a as integer)
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overrides" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BANANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, so all methods should match methods in base
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BAnANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, but base methods have multiple casing, so don't use it.
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "baNana".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub ProbableExtensionMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C">
<file name="a.vb">
Option Strict On
Class C1
Sub X()
goodext1()
goodext2()
goodext3()
goodext4()
goodext5()
goodext6()
goodext7()
goodext8()
badext1()
badext2()
badext3()
badext4()
badext5()
badext6()
End Sub
End Class
Namespace Blah
Class ExtensionAttribute
Inherits System.Attribute
End Class
End Namespace
</file>
<file name="b.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Runtime.CompilerServices
Imports ExAttribute = System.Runtime.CompilerServices.ExtensionAttribute
Imports Ex2 = System.Runtime.CompilerServices.ExtensionAttribute
Module M1
<[Extension]>
Public Sub goodext1(this As C1)
End Sub
<ExtensionAttribute>
Public Sub goodext2(this As C1)
End Sub
<System.Runtime.CompilerServices.Extension>
Public Sub goodext3(this As C1)
End Sub
<System.Runtime.CompilerServices.ExtensionAttribute>
Public Sub goodext4(this As C1)
End Sub
<[ExAttribute]>
Public Sub goodext5(this As C1)
End Sub
<Ex>
Public Sub goodext6(this As C1)
End Sub
<Ex2>
Public Sub goodext7(this As C1)
End Sub
<AnExt>
Public Sub goodext8(this As C1)
End Sub
<AnExt>
Declare Sub goodext9 Lib "goo" (this As C1)
<Blah.Extension>
Public Sub badext1(this As C1)
End Sub
<Blah.ExtensionAttribute>
Public Sub badext2(this As C1)
End Sub
<Extension>
Public Sub badext3()
End Sub
End Module
]]></file>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System
Imports Blah
Module M2
<Extension>
Public Sub badext4(this As C1)
End Sub
<ExtensionAttribute>
Public Sub badext5(this As C1)
End Sub
<Extension>
Declare Sub badext6 Lib "goo" (this As C1)
End Module
]]></file>
</compilation>, references:={TestMetadata.Net40.SystemCore, TestMetadata.Net40.System}, options:=TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse("AnExt=System.Runtime.CompilerServices.ExtensionAttribute")))
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim modM1 = DirectCast(globalNS.GetMembers("M1").Single(), NamedTypeSymbol)
Dim modM2 = DirectCast(globalNS.GetMembers("M2").Single(), NamedTypeSymbol)
Dim goodext1 = DirectCast(modM1.GetMembers("goodext1").Single(), MethodSymbol)
Assert.True(goodext1.IsExtensionMethod)
Assert.True(goodext1.MayBeReducibleExtensionMethod)
Dim goodext2 = DirectCast(modM1.GetMembers("goodext2").Single(), MethodSymbol)
Assert.True(goodext2.IsExtensionMethod)
Assert.True(goodext2.MayBeReducibleExtensionMethod)
Dim goodext3 = DirectCast(modM1.GetMembers("goodext3").Single(), MethodSymbol)
Assert.True(goodext3.IsExtensionMethod)
Assert.True(goodext3.MayBeReducibleExtensionMethod)
Dim goodext4 = DirectCast(modM1.GetMembers("goodext4").Single(), MethodSymbol)
Assert.True(goodext4.IsExtensionMethod)
Assert.True(goodext4.MayBeReducibleExtensionMethod)
Dim goodext5 = DirectCast(modM1.GetMembers("goodext5").Single(), MethodSymbol)
Assert.True(goodext5.IsExtensionMethod)
Assert.True(goodext5.MayBeReducibleExtensionMethod)
Dim goodext6 = DirectCast(modM1.GetMembers("goodext6").Single(), MethodSymbol)
Assert.True(goodext6.IsExtensionMethod)
Assert.True(goodext6.MayBeReducibleExtensionMethod)
Dim goodext7 = DirectCast(modM1.GetMembers("goodext7").Single(), MethodSymbol)
Assert.True(goodext7.IsExtensionMethod)
Assert.True(goodext7.MayBeReducibleExtensionMethod)
Dim goodext8 = DirectCast(modM1.GetMembers("goodext8").Single(), MethodSymbol)
Assert.True(goodext8.IsExtensionMethod)
Assert.True(goodext8.MayBeReducibleExtensionMethod)
Dim goodext9 = DirectCast(modM1.GetMembers("goodext9").Single(), MethodSymbol)
Assert.True(goodext9.IsExtensionMethod)
Assert.True(goodext9.MayBeReducibleExtensionMethod)
Dim badext1 = DirectCast(modM1.GetMembers("badext1").Single(), MethodSymbol)
Assert.False(badext1.IsExtensionMethod)
Assert.True(badext1.MayBeReducibleExtensionMethod)
Dim badext2 = DirectCast(modM1.GetMembers("badext2").Single(), MethodSymbol)
Assert.False(badext2.IsExtensionMethod)
Assert.True(badext2.MayBeReducibleExtensionMethod)
Dim badext3 = DirectCast(modM1.GetMembers("badext3").Single(), MethodSymbol)
Assert.False(badext3.IsExtensionMethod)
Assert.True(badext3.MayBeReducibleExtensionMethod)
Dim badext4 = DirectCast(modM2.GetMembers("badext4").Single(), MethodSymbol)
Assert.False(badext4.IsExtensionMethod)
Assert.True(badext4.MayBeReducibleExtensionMethod)
Dim badext5 = DirectCast(modM2.GetMembers("badext5").Single(), MethodSymbol)
Assert.False(badext5.IsExtensionMethod)
Assert.True(badext5.MayBeReducibleExtensionMethod)
Dim badext6 = DirectCast(modM2.GetMembers("badext6").Single(), MethodSymbol)
Assert.False(badext6.IsExtensionMethod)
Assert.True(badext6.MayBeReducibleExtensionMethod)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext1(this As C1)'.
badext1()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext2(this As C1)'.
badext2()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext4(this As C1)'.
badext4()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext5(this As C1)'.
badext5()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Declare Ansi Sub badext6 Lib "goo" (this As C1)'.
badext6()
~~~~~~~
BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend.
Public Sub badext3()
~~~~~~~
</expected>)
End Sub
<WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")>
<Fact>
Public Sub UserDefinedOperatorLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(c As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim operatorPos = source.IndexOf("+"c)
Dim parenPos = source.IndexOf("("c)
Dim comp = CreateCompilationWithMscorlib40({Parse(source)})
Dim Symbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single()
Dim span = Symbol.Locations.Single().SourceSpan
Assert.Equal(operatorPos, span.Start)
Assert.Equal(parenPos, span.End)
End Sub
<WorkItem(901815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/901815")>
<Fact>
Public Sub UserDefinedConversionLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(Of T)
Return Nothing
End Operator
End Class
]]>.Value
' Used to raise an exception.
Dim comp = CreateCompilationWithMscorlib40({Parse(source)}, options:=TestOptions.ReleaseDll)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC33016: Operator '+' must have either one or two parameters.
Public Shared Operator +(Of T)
~
BC30198: ')' expected.
Public Shared Operator +(Of T)
~
BC30199: '(' expected.
Public Shared Operator +(Of T)
~
BC32065: Type parameters cannot be specified on this declaration.
Public Shared Operator +(Of T)
~~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnNonPartial()
Dim source = <![CDATA[
Public Class C
Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.False(m.IsPartialDefinition)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnPartialDefinitionOnly()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.Null(m.PartialImplementationPart)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionWithPartialImplementation()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
Private Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.False(m.PartialImplementationPart.IsPartialDefinition)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MethodTests
Inherits BasicTestBase
<Fact>
Public Sub Methods1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1()
End Sub
Protected MustOverride Function m2$()
Friend NotOverridable Overloads Function m3() As D
End Function
Protected Friend Overridable Shadows Sub m4()
End Sub
Protected Overrides Sub m5()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Shared Function m6()
End Function
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(8, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim ctor = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, ctor.ContainingSymbol)
Assert.Same(classC, ctor.ContainingType)
Assert.Equal(".ctor", ctor.Name)
Assert.Equal(MethodKind.Constructor, ctor.MethodKind)
Assert.Equal(Accessibility.Public, ctor.DeclaredAccessibility)
Assert.Equal(0, ctor.TypeParameters.Length)
Assert.Equal(0, ctor.TypeArguments.Length)
Assert.False(ctor.IsGenericMethod)
Assert.False(ctor.IsMustOverride)
Assert.False(ctor.IsNotOverridable)
Assert.False(ctor.IsOverridable)
Assert.False(ctor.IsOverrides)
Assert.False(ctor.IsShared)
Assert.False(ctor.IsOverloads)
Assert.True(ctor.IsSub)
Assert.Equal("System.Void", ctor.ReturnType.ToTestDisplayString())
Assert.Equal(0, ctor.Parameters.Length)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.False(m1.IsRuntimeImplemented()) ' test for default implementation
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.True(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsSub)
Assert.False(m2.IsOverloads)
Assert.Equal("System.String", m2.ReturnType.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(Accessibility.Friend, m3.DeclaredAccessibility)
Assert.False(m3.IsMustOverride)
Assert.True(m3.IsNotOverridable)
Assert.False(m3.IsOverridable)
Assert.False(m3.IsOverrides)
Assert.False(m3.IsShared)
Assert.True(m3.IsOverloads)
Assert.False(m3.IsSub)
Assert.Equal("C.D", m3.ReturnType.ToTestDisplayString())
Dim m4 = DirectCast(membersOfC(5), MethodSymbol)
Assert.Equal(Accessibility.ProtectedOrFriend, m4.DeclaredAccessibility)
Assert.False(m4.IsMustOverride)
Assert.False(m4.IsNotOverridable)
Assert.True(m4.IsOverridable)
Assert.False(m4.IsOverrides)
Assert.False(m4.IsShared)
Assert.False(m4.IsOverloads)
Assert.True(m4.IsSub)
Dim m5 = DirectCast(membersOfC(6), MethodSymbol)
Assert.Equal(Accessibility.Protected, m5.DeclaredAccessibility)
Assert.False(m5.IsMustOverride)
Assert.False(m5.IsNotOverridable)
Assert.False(m5.IsOverridable)
Assert.True(m5.IsOverrides)
Assert.False(m5.IsShared)
Assert.True(m5.IsOverloads)
Assert.True(m5.IsSub)
Dim m6 = DirectCast(membersOfC(7), MethodSymbol)
Assert.Equal(Accessibility.Friend, m6.DeclaredAccessibility)
Assert.False(m6.IsMustOverride)
Assert.False(m6.IsNotOverridable)
Assert.False(m6.IsOverridable)
Assert.False(m6.IsOverrides)
Assert.True(m6.IsShared)
Assert.False(m6.IsSub)
Assert.Equal("System.Object", m6.ReturnType.ToTestDisplayString())
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<expected>
BC31411: 'C' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Public Partial Class C
~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Friend NotOverridable Overloads Function m3() As D
~~
BC30508: 'm3' cannot expose type 'C.D' in namespace '<Default>' through class 'C'.
Friend NotOverridable Overloads Function m3() As D
~
BC30284: sub 'm5' cannot be declared 'Overrides' because it does not override a sub in a base class.
Protected Overrides Sub m5()
~~
</expected>)
End Sub
<Fact>
Public Sub Methods2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Module M
Sub m1()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim moduleM = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim m1 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m1.ContainingSymbol)
Assert.Same(moduleM, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.Equal(MethodKind.Ordinary, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared) ' methods in a module are implicitly Shared
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub Constructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Public Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Friend Sub New(x as string, y as integer)
End Sub
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(2, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim m2 = DirectCast(membersOfC(1), MethodSymbol)
Assert.Same(classC, m2.ContainingSymbol)
Assert.Same(classC, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Friend, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(2, m2.Parameters.Length)
Assert.Equal("x", m2.Parameters(0).Name)
Assert.Equal("System.String", m2.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("y", m2.Parameters(1).Name)
Assert.Equal("System.Int32", m2.Parameters(1).Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub SharedConstructors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Shared Sub New()
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Module M
Sub New()
End Sub
End Module
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim moduleM = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".cctor", m1.Name)
Assert.Equal(MethodKind.SharedConstructor, m1.MethodKind)
Assert.Equal(Accessibility.Private, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.True(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim membersOfM = moduleM.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Dim m2 = DirectCast(membersOfM(0), MethodSymbol)
Assert.Same(moduleM, m2.ContainingSymbol)
Assert.Same(moduleM, m2.ContainingType)
Assert.Equal(".cctor", m2.Name)
Assert.Equal(MethodKind.SharedConstructor, m2.MethodKind)
Assert.Equal(Accessibility.Private, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.True(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub DefaultConstructors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Class C
End Class
Public MustInherit Class D
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Structure S
End Structure
Public Module M
End Module
Public Interface I
End Interface
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Assert.Equal("C", classC.Name)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfC.Length)
Dim m1 = DirectCast(membersOfC(0), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal(".ctor", m1.Name)
Assert.Equal(MethodKind.Constructor, m1.MethodKind)
Assert.Equal(Accessibility.Public, m1.DeclaredAccessibility)
Assert.Equal(0, m1.TypeParameters.Length)
Assert.Equal(0, m1.TypeArguments.Length)
Assert.False(m1.IsGenericMethod)
Assert.False(m1.IsMustOverride)
Assert.False(m1.IsNotOverridable)
Assert.False(m1.IsOverridable)
Assert.False(m1.IsOverrides)
Assert.False(m1.IsShared)
Assert.False(m1.IsOverloads)
Assert.True(m1.IsSub)
Assert.Equal("System.Void", m1.ReturnType.ToTestDisplayString())
Assert.Equal(0, m1.Parameters.Length)
Dim classD = DirectCast(globalNSmembers(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Dim membersOfD = classD.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ThenBy(Function(s) DirectCast(s, MethodSymbol).Parameters.Length).ToArray()
Assert.Equal(1, membersOfD.Length)
Dim m2 = DirectCast(membersOfD(0), MethodSymbol)
Assert.Same(classD, m2.ContainingSymbol)
Assert.Same(classD, m2.ContainingType)
Assert.Equal(".ctor", m2.Name)
Assert.Equal(MethodKind.Constructor, m2.MethodKind)
Assert.Equal(Accessibility.Protected, m2.DeclaredAccessibility)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.False(m2.IsGenericMethod)
Assert.False(m2.IsMustOverride)
Assert.False(m2.IsNotOverridable)
Assert.False(m2.IsOverridable)
Assert.False(m2.IsOverrides)
Assert.False(m2.IsShared)
Assert.False(m2.IsOverloads)
Assert.True(m2.IsSub)
Assert.Equal("System.Void", m2.ReturnType.ToTestDisplayString())
Assert.Equal(0, m2.Parameters.Length)
Dim interfaceI = DirectCast(globalNSmembers(2), NamedTypeSymbol)
Assert.Equal("I", interfaceI.Name)
Assert.Equal(0, interfaceI.GetMembers().Length())
Dim moduleM = DirectCast(globalNSmembers(3), NamedTypeSymbol)
Assert.Equal("M", moduleM.Name)
Assert.Equal(0, moduleM.GetMembers().Length())
Dim structureS = DirectCast(globalNSmembers(4), NamedTypeSymbol)
Assert.Equal("S", structureS.Name)
Assert.Equal(1, structureS.GetMembers().Length()) ' Implicit parameterless constructor
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Partial Class C
Sub m1(x as D, ByRef y As Integer)
End Sub
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Sub m2(a(), z, byref q, ParamArray w())
End Sub
Sub m3(x)
End Sub
Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Equal("m1", m1.Name)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.Same(classD, m1p1.Type)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Int32", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Int32", m1p2.ToTestDisplayString())
Dim m2 = DirectCast(membersOfC(3), MethodSymbol)
Assert.Equal(4, m2.Parameters.Length)
Dim m2p1 = m2.Parameters(0)
Assert.Equal("a", m2p1.Name)
Assert.Same(m2, m2p1.ContainingSymbol)
Assert.False(m2p1.HasExplicitDefaultValue)
Assert.False(m2p1.IsOptional)
Assert.False(m2p1.IsParamArray)
Assert.False(m2p1.IsByRef)
Assert.Equal("System.Object()", m2p1.Type.ToTestDisplayString())
Dim m2p2 = m2.Parameters(1)
Assert.Equal("z", m2p2.Name)
Assert.Same(m2, m2p2.ContainingSymbol)
Assert.False(m2p2.HasExplicitDefaultValue)
Assert.False(m2p2.IsOptional)
Assert.False(m2p2.IsParamArray)
Assert.Equal("System.Object", m2p2.Type.ToTestDisplayString())
Dim m2p3 = m2.Parameters(2)
Assert.Equal("q", m2p3.Name)
Assert.Same(m2, m2p3.ContainingSymbol)
Assert.False(m2p3.HasExplicitDefaultValue)
Assert.False(m2p3.IsOptional)
Assert.False(m2p3.IsParamArray)
Assert.True(m2p3.IsByRef)
Assert.Equal("System.Object", m2p3.Type.ToTestDisplayString())
Assert.Equal("ByRef q As System.Object", m2p3.ToTestDisplayString())
Dim m2p4 = m2.Parameters(3)
Assert.Equal("w", m2p4.Name)
Assert.Same(m2, m2p4.ContainingSymbol)
Assert.False(m2p4.HasExplicitDefaultValue)
Assert.False(m2p4.IsOptional)
Assert.True(m2p4.IsParamArray)
Assert.Equal(TypeKind.Array, m2p4.Type.TypeKind)
Assert.Equal("System.Object", DirectCast(m2p4.Type, ArrayTypeSymbol).ElementType.ToTestDisplayString())
Assert.Equal("System.Object()", m2p4.Type.ToTestDisplayString())
Dim m3 = DirectCast(membersOfC(4), MethodSymbol)
Assert.Equal(1, m3.Parameters.Length)
Dim m3p1 = m3.Parameters(0)
Assert.Equal("x", m3p1.Name)
Assert.Same(m3, m3p1.ContainingSymbol)
Assert.False(m3p1.HasExplicitDefaultValue)
Assert.False(m3p1.IsOptional)
Assert.False(m3p1.IsParamArray)
Assert.Equal("System.Object", m3p1.Type.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodByRefParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Public Structure S
Function M(Byref x as Object, ByRef y As Byte) As Long
Return 0
End Function
End Structure
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim typeS = DirectCast(globalNS.GetTypeMembers("S").Single(), NamedTypeSymbol)
Dim m1 = DirectCast(typeS.GetMembers("M").Single(), MethodSymbol)
Assert.Equal(2, m1.Parameters.Length)
Dim m1p1 = m1.Parameters(0)
Assert.Equal("x", m1p1.Name)
Assert.Same(m1, m1p1.ContainingSymbol)
Assert.False(m1p1.HasExplicitDefaultValue)
Assert.False(m1p1.IsOptional)
Assert.False(m1p1.IsParamArray)
Assert.True(m1p1.IsByRef)
Dim m1p2 = m1.Parameters(1)
Assert.Equal("y", m1p2.Name)
Assert.Same(m1, m1p2.ContainingSymbol)
Assert.False(m1p2.HasExplicitDefaultValue)
Assert.False(m1p2.IsOptional)
Assert.False(m1p2.IsParamArray)
Assert.True(m1p2.IsByRef)
Assert.Equal("System.Byte", m1p2.Type.ToTestDisplayString())
Assert.Equal("ByRef y As System.Byte", m1p2.ToTestDisplayString())
Assert.Equal("ValueType", m1p2.Type.BaseType.Name)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub MethodTypeParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Partial Class C
Function m1(Of T, U)(x1 As T) As IEnumerable(Of U)
End Function
End Class
</file>
<file name="b.vb">
Option Strict Off
Public Partial Class C
Private Class D
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray()
Assert.Equal(3, membersOfC.Length)
Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol)
Assert.Equal("D", classD.Name)
Assert.Equal(TypeKind.Class, classD.TypeKind)
Dim m1 = DirectCast(membersOfC(2), MethodSymbol)
Assert.Same(classC, m1.ContainingSymbol)
Assert.Same(classC, m1.ContainingType)
Assert.Equal("m1", m1.Name)
Assert.True(m1.IsGenericMethod)
Assert.Equal(2, m1.TypeParameters.Length)
Dim tpT = m1.TypeParameters(0)
Assert.Equal("T", tpT.Name)
Assert.Same(m1, tpT.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpT.Variance)
Dim tpU = m1.TypeParameters(1)
Assert.Equal("U", tpU.Name)
Assert.Same(m1, tpU.ContainingSymbol)
Assert.Equal(VarianceKind.None, tpU.Variance)
Dim paramX1 = m1.Parameters(0)
Assert.Same(tpT, paramX1.Type)
Assert.Equal("T", paramX1.Type.ToTestDisplayString())
Assert.Same(tpU, DirectCast(m1.ReturnType, NamedTypeSymbol).TypeArguments(0))
Assert.Equal("System.Collections.Generic.IEnumerable(Of U)", m1.ReturnType.ToTestDisplayString())
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
Public Sub ConstructGenericMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Public Class C(Of W)
Function m1(Of T, U)(p1 As T, p2 as W) As KeyValuePair(Of W, U))
End Function
Sub m2()
End Sub
Public Class D(Of X)
Sub m3(Of T)(p1 As T)
End Sub
End Class
End Class
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim globalNSmembers = globalNS.GetMembers()
Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol)
Dim constructedC = classC.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_Int32)}).AsImmutableOrNull())
Dim m1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Dim m2 = DirectCast(constructedC.GetMembers("m2")(0), MethodSymbol)
Assert.True(m1.CanConstruct)
Assert.True(m1.OriginalDefinition.CanConstruct)
Assert.Same(m1, m1.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.NotEqual(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0))
Assert.Same(m1.OriginalDefinition.TypeParameters(0), m1.TypeParameters(0).OriginalDefinition)
Assert.Same(m1, m1.TypeParameters(0).ContainingSymbol)
Assert.Equal(2, m1.Arity)
Assert.Same(m1, m1.Construct(m1.TypeParameters(0), m1.TypeParameters(1)))
Dim m1_1 = DirectCast(constructedC.GetMembers("m1")(0), MethodSymbol)
Assert.Equal(m1, m1_1)
Assert.NotSame(m1, m1_1) ' Checks below need equal, but not identical symbols to test target scenarios!
Assert.Same(m1, m1.Construct(m1_1.TypeParameters(0), m1_1.TypeParameters(1)))
Dim alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(1), m1_1.TypeParameters(0))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(1))
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(0))
alphaConstructedM1 = m1.Construct(m1_1.TypeParameters(0), constructedC)
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), m1.TypeParameters(0))
Assert.NotSame(alphaConstructedM1.TypeArguments(0), m1_1.TypeParameters(0))
Assert.Same(alphaConstructedM1.TypeArguments(1), constructedC)
alphaConstructedM1 = m1.Construct(constructedC, m1_1.TypeParameters(1))
Assert.Same(m1, alphaConstructedM1.ConstructedFrom)
Assert.Same(alphaConstructedM1.TypeArguments(0), constructedC)
Assert.Same(alphaConstructedM1.TypeArguments(1), m1.TypeParameters(1))
Assert.NotSame(alphaConstructedM1.TypeArguments(1), m1_1.TypeParameters(1))
Assert.False(m2.CanConstruct)
Assert.False(m2.OriginalDefinition.CanConstruct)
Assert.Equal(0, m2.TypeParameters.Length)
Assert.Equal(0, m2.TypeArguments.Length)
Assert.Throws(Of InvalidOperationException)(Sub() m2.OriginalDefinition.Construct(classC))
Assert.Throws(Of InvalidOperationException)(Sub() m2.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.OriginalDefinition.Construct(classC))
Assert.Throws(Of ArgumentException)(Sub() m1.Construct(classC))
Dim constructedC_d = constructedC.GetTypeMembers("D").Single()
Dim m3 = DirectCast(constructedC_d.GetMembers("m3").Single(), MethodSymbol)
Assert.Equal(1, m3.Arity)
Assert.False(m3.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() m3.Construct(classC))
Dim d = classC.GetTypeMembers("D").Single()
m3 = DirectCast(d.GetMembers("m3").Single(), MethodSymbol)
Dim alphaConstructedM3 = m3.Construct(m1.TypeParameters(0))
Assert.NotSame(m3, alphaConstructedM3)
Assert.Same(m3, alphaConstructedM3.ConstructedFrom)
Assert.Same(m1.TypeParameters(0), alphaConstructedM3.TypeArguments(0))
Assert.Equal("T", m1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", m1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, U)", m1.ReturnType.ToTestDisplayString())
Assert.Equal("T", m1.TypeParameters(0).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(0), m1.TypeArguments(0))
Assert.Equal("U", m1.TypeParameters(1).ToTestDisplayString())
Assert.Equal(m1.TypeParameters(1), m1.TypeArguments(1))
Assert.Same(m1, m1.ConstructedFrom)
Dim constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.Equal("System.String", constructedM1.Parameters(0).Type.ToTestDisplayString())
Assert.Equal("System.Int32", constructedM1.Parameters(1).Type.ToTestDisplayString())
Assert.Equal("System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ReturnType.ToTestDisplayString())
Assert.Equal("T", constructedM1.TypeParameters(0).ToTestDisplayString())
Assert.Equal("System.String", constructedM1.TypeArguments(0).ToTestDisplayString())
Assert.Equal("U", constructedM1.TypeParameters(1).ToTestDisplayString())
Assert.Equal("System.Boolean", constructedM1.TypeArguments(1).ToTestDisplayString())
Assert.Same(m1, constructedM1.ConstructedFrom)
Assert.Equal("Function C(Of System.Int32).m1(Of System.String, System.Boolean)(p1 As System.String, p2 As System.Int32) As System.Collections.Generic.KeyValuePair(Of System.Int32, System.Boolean)", constructedM1.ToTestDisplayString())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
' Try wrong arity.
Assert.Throws(Of ArgumentException)(Sub()
Dim constructedM1WrongArity = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String)}).AsImmutableOrNull())
End Sub)
' Try identity substitution.
Dim identityM1 = m1.Construct(m1.OriginalDefinition.TypeParameters.As(Of TypeSymbol)())
Assert.NotEqual(m1, identityM1)
Assert.Same(m1, identityM1.ConstructedFrom)
m1 = DirectCast(classC.GetMembers("m1").Single(), MethodSymbol)
identityM1 = m1.Construct(m1.TypeParameters.As(Of TypeSymbol)())
Assert.Same(m1, identityM1)
constructedM1 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.False(constructedM1.CanConstruct)
Assert.Throws(Of InvalidOperationException)(Sub() constructedM1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull()))
Dim constructedM1_2 = m1.Construct(compilation.GetSpecialType(SpecialType.System_Byte), compilation.GetSpecialType(SpecialType.System_Boolean))
Dim constructedM1_3 = m1.Construct((New TypeSymbol() {compilation.GetSpecialType(SpecialType.System_String), compilation.GetSpecialType(SpecialType.System_Boolean)}).AsImmutableOrNull())
Assert.NotEqual(constructedM1, constructedM1_2)
Assert.Equal(constructedM1, constructedM1_3)
Dim p1 = constructedM1.Parameters(0)
Assert.Equal(0, p1.Ordinal)
Assert.Same(constructedM1, p1.ContainingSymbol)
Assert.Equal(p1, p1)
Assert.Equal(p1, constructedM1_3.Parameters(0))
Assert.Equal(p1.GetHashCode(), constructedM1_3.Parameters(0).GetHashCode())
Assert.NotEqual(m1.Parameters(0), p1)
Assert.NotEqual(constructedM1_2.Parameters(0), p1)
Dim constructedM3 = m3.Construct(compilation.GetSpecialType(SpecialType.System_String))
Assert.NotEqual(constructedM3.Parameters(0), p1)
End Sub
<Fact>
Public Sub InterfaceImplements01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Strict On
Imports System.Collections.Generic
Namespace NS
Public Class Abc
End Class
Public Interface IGoo(Of T)
Sub I1Sub1(ByRef p As T)
End Interface
Public Interface I1
Sub I1Sub1(ByRef p As String)
Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2 As Object()) As Integer
End Interface
Public Interface I2
Inherits I1
Sub I2Sub1()
Function I2Func1(ByRef p1 As aBC) As AbC
End Interface
End Namespace
</file>
<file name="b.vb">
Imports System.Collections.Generic
Namespace NS.NS1
Class Impl
Implements I2, IGoo(Of String)
Public Sub Sub1(ByRef p As String) Implements I1.I1Sub1, IGoo(Of String).I1Sub1
End Sub
Public Function I1Func1(ByVal p1 As Short, ByVal ParamArray p2() As Object) As Integer Implements I1.I1Func1
Return p1
End Function
Public Function I2Func1(ByRef p1 As ABc) As ABC Implements I2.I2Func1
Return Nothing
End Function
Public Sub I2Sub1() Implements I2.I2Sub1
End Sub
End Class
Structure StructImpl(Of T)
Implements IGoo(Of T)
Public Sub Sub1(ByRef p As T) Implements IGoo(Of T).I1Sub1
End Sub
End Structure
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").AsEnumerable().SingleOrDefault(), NamespaceSymbol)
Dim ns1 = DirectCast(ns.GetMembers("NS1").Single(), NamespaceSymbol)
Dim classImpl = DirectCast(ns1.GetTypeMembers("impl").Single(), NamedTypeSymbol)
'direct interfaces
Assert.Equal(2, classImpl.Interfaces.Length)
Dim itfc = DirectCast(classImpl.Interfaces(0), NamedTypeSymbol)
Assert.Equal(1, itfc.Interfaces.Length)
itfc = DirectCast(itfc.Interfaces(0), NamedTypeSymbol)
Assert.Equal("I1", itfc.Name)
Dim mem1 = DirectCast(classImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(2, mem1.ExplicitInterfaceImplementation.Count)
mem1 = DirectCast(classImpl.GetMembers("i2Func1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem1.ExplicitInterfaceImplementation.Count)
Dim param = DirectCast(mem1.Parameters(0), ParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal("ByRef " & param.Name & " As NS.Abc", param.ToTestDisplayString()) ' use case of declare's name
Dim structImpl = DirectCast(ns1.GetTypeMembers("structimpl").Single(), NamedTypeSymbol)
Assert.Equal(1, structImpl.Interfaces.Length)
Dim mem2 = DirectCast(structImpl.GetMembers("sub1").Single(), MethodSymbol)
' not impl
'Assert.Equal(1, mem2.ExplicitInterfaceImplementation.Count)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<WorkItem(537444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537444")>
<Fact>
Public Sub DeclareFunction01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Option Explicit
Imports System
Imports System.Runtime.InteropServices
Public Structure S1
Public strVar As String
Public x As Integer
End Structure
Namespace NS
Friend Module MyMod
Declare Ansi Function VerifyString2 Lib "AttrUsgOthM010DLL.dll" (ByRef Arg As S1, ByVal Op As Integer) As String
End Module
Class cls1
Overloads Declare Sub Goo Lib "someLib" ()
Overloads Sub goo(ByRef arg As Integer)
' ...
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim nsNS = DirectCast(compilation.Assembly.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim modOfNS = DirectCast(nsNS.GetMembers("MyMod").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(modOfNS.GetMembers().First(), MethodSymbol)
Assert.Equal("VerifyString2", mem1.Name)
' TODO: add more verification when this is working
End Sub
<Fact>
Public Sub CodepageOptionUnicodeMembers01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Module Module2
Sub ÛÊÛÄÁÍäá() ' 1067
Console.WriteLine (CStr(AscW("ÛÊÛÄÁÍäá")))
End Sub
End Module
Class Class1
Public Shared Sub ŒŸõ()
Console.WriteLine(CStr(AscW("ŒŸõ"))) ' 26908
End Sub
Friend Function [Widening](ByVal Ÿü As Short) As à–¾ 'invalid char in Dev10
Return New à–¾(Ÿü)
End Function
End Class
Structure ĵÁiÛE
Const str1 As String = "ĵÁiÛE" ' 1044
Dim i As Integer
End Structure
Public Class [Narrowing] 'êàê èäåíòèôèêàòîð.
Public ñëîâî As [CULng]
End Class
Public Structure [CULng]
Public [UInteger] As Integer
End Structure
</file>
</compilation>)
Dim glbNS = compilation.Assembly.GlobalNamespace
Dim type1 = DirectCast(glbNS.GetMembers("Module2").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(type1.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem1.DeclaredAccessibility)
Assert.True(mem1.IsSub)
Assert.Equal("Sub Module2.ÛÊÛÄÁÍäá()", mem1.ToTestDisplayString())
Dim type2 = DirectCast(glbNS.GetMembers("Class1").Single(), NamedTypeSymbol)
Dim mem2 = DirectCast(type2.GetMembers().First(), MethodSymbol)
Assert.Equal(Accessibility.Public, mem2.DeclaredAccessibility)
'Assert.Equal("ŒŸõ", mem2.Name) - TODO: Code Page issue
Dim type3 = DirectCast(glbNS.GetTypeMembers("ĵÁiÛE").Single(), NamedTypeSymbol)
Dim mem3 = DirectCast(type3.GetMembers("Str1").Single(), FieldSymbol)
Assert.True(mem3.IsConst)
Assert.Equal("ĵÁiÛE.str1 As System.String", mem3.ToTestDisplayString())
Dim type4 = DirectCast(glbNS.GetTypeMembers("Narrowing").Single(), NamedTypeSymbol)
Dim mem4 = DirectCast(type4.GetMembers("ñëîâî").Single(), FieldSymbol)
Assert.Equal(TypeKind.Structure, mem4.Type.TypeKind)
End Sub
<WorkItem(537466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537466")>
<Fact>
Public Sub DefaultAccessibility01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Interface GI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class GC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Class
Structure GS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
Property Prop As Integer
Structure InnerStructure
End Structure
Class Innerclass
End Class
Delegate Sub DelegateA()
Event EventA As DelegateA
End Structure
Namespace NS
Interface NI(Of T)
Sub Goo(ByVal t As T)
Function Bar() As T
End Interface
Class NC
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Class
Structure NS
Dim X As Integer
Sub Goo()
End Sub
Function Bar() As String
Return String.Empty
End Function
End Structure
End Namespace
</file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
' interface - public
Dim typemem = DirectCast(globalNS.GetTypeMembers("GI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
Dim mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Class - field (private), other - public
typemem = DirectCast(globalNS.GetTypeMembers("GC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
' Struct - public
typemem = DirectCast(globalNS.GetTypeMembers("GS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Prop").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerStructure").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("InnerClass").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("DelegateA").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
'mem = typemem.GetMembers("EventA").Single()
'Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
Dim nsNS = DirectCast(globalNS.GetMembers("NS").Single(), NamespaceSymbol)
typemem = DirectCast(nsNS.GetTypeMembers("NI").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NC").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Private, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
typemem = DirectCast(nsNS.GetTypeMembers("NS").Single(), NamedTypeSymbol)
Assert.Equal(Accessibility.Friend, typemem.DeclaredAccessibility)
mem = typemem.GetMembers("X").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility) ' private is better but Dev10 is public
mem = typemem.GetMembers("Goo").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
mem = typemem.GetMembers("Bar").Single()
Assert.Equal(Accessibility.Public, mem.DeclaredAccessibility)
End Sub
<Fact>
Public Sub OverloadsAndOverrides01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim derive = New NS.C2()
derive.Goo(1) ' call derived Goo
derive.Bar(1) ' call derived Bar
derive.Boo(1) ' call derived Boo
derive.VGoo(1) ' call derived VGoo
derive.VBar(1) ' call derived VBar
derive.VBoo(1) ' call derived VBoo
Console.WriteLine("-------------")
Dim base As NS.C1 = New NS.C2()
base.Goo(1) ' call base Goo
base.Bar(1) ' call base Bar
base.Boo(1) ' call base Boo
base.VGoo(1) ' call base Goo
base.VBar(1) ' call D
base.VBoo(1) ' call D
End Sub
End Module
Namespace NS
Public Class C1
Public Sub Goo(ByVal p As Integer)
Console.WriteLine("Base - Goo")
End Sub
Public Sub Bar(ByVal p As Integer)
Console.WriteLine("Base - Bar")
End Sub
Public Sub Boo(ByVal p As Integer)
Console.WriteLine("Base - Boo")
End Sub
Public Overridable Sub VGoo(ByVal p As Integer)
Console.WriteLine("Base - VGoo")
End Sub
Public Overridable Sub VBar(ByVal p As Integer)
Console.WriteLine("Base - VBar")
End Sub
Public Overridable Sub VBoo(ByVal p As Integer)
Console.WriteLine("Base - VBoo")
End Sub
End Class
Public Class C2
Inherits C1
Public Shadows Sub Goo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows Goo")
End Sub
Public Overloads Sub Bar(Optional ByVal p As Integer = 1)
Console.WriteLine("Derived - Overloads Bar")
End Sub
' warning
Public Sub Boo(Optional ByVal p As Integer = 2)
Console.WriteLine("Derived - Boo")
End Sub
' not virtual
Public Shadows Sub VGoo(Optional ByVal p As Integer = 0)
Console.WriteLine("Derived - Shadows VGoo")
End Sub
' hidebysig and virtual
Public Overloads Overrides Sub VBar(ByVal p As Integer)
Console.WriteLine("Derived - Overloads Overrides VBar")
End Sub
' virtual
Public Overrides Sub VBoo(ByVal p As Integer)
Console.WriteLine("Derived - Overrides VBoo")
End Sub
End Class
End Namespace
</file>
</compilation>)
Dim ns = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("NS").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetTypeMembers("C1").Single(), NamedTypeSymbol)
Dim mem = DirectCast(type1.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverridable)
mem = DirectCast(type1.GetMembers("VGoo").Single(), MethodSymbol)
Assert.True(mem.IsOverridable)
Dim type2 = DirectCast(ns.GetTypeMembers("C2").Single(), NamedTypeSymbol)
mem = DirectCast(type2.GetMembers("Goo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Bar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
mem = DirectCast(type2.GetMembers("Boo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
' overridable
mem = DirectCast(type2.GetMembers("VGoo").Single(), MethodSymbol)
Assert.False(mem.IsOverloads)
Assert.False(mem.IsOverrides)
Assert.False(mem.IsOverridable)
mem = DirectCast(type2.GetMembers("VBar").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
mem = DirectCast(type2.GetMembers("VBoo").Single(), MethodSymbol)
Assert.True(mem.IsOverloads)
Assert.True(mem.IsOverrides)
End Sub
<Fact>
Public Sub Bug2820()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="a.vb">
Class Class1
sub Test(x as T)
End sub
End Class
</file>
</compilation>)
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim test = class1.GetMembers("Test").OfType(Of MethodSymbol)().Single()
Assert.Equal("T", test.Parameters(0).Type.Name)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Sub baNana()
End Sub
Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Sub baNANa(xyz as String)
End Sub
Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' No "Overloads", so all methods should match first overloads in first source file
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNana").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNana" (from first file supplied to compilation).
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
If m.Parameters.Any Then
Assert.NotEqual("baNana", m.Name)
End If
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub baNANa(xyz as String)
End Sub
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overloads" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "baNANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Class Base
Overridable Sub BANANa(x as string, y as integer)
End Sub
End Class
Partial Class Class1
Inherits Base
Overloads Sub baNana()
End Sub
Overrides Sub baNANa(xyz as String, a as integer)
End Sub
Overloads Sub Banana(x as integer)
End Sub
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Sub BANANA(x as Long)
End Sub
End Class
</file>
</compilation>)
' "Overrides" specified, so all methods should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allMethods = class1.GetMembers("baNANa").OfType(Of MethodSymbol)()
' All methods in Class1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BANANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, so all methods should match methods in base
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "BANANa".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C">
<file name="b.vb">
Interface Base1
Sub BAnANa(x as string, y as integer)
End Interface
Interface Base2
Sub BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads Sub baNana()
Overloads Sub baNANa(xyz as String, a as integer)
Overloads Sub Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, but base methods have multiple casing, so don't use it.
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allMethods = interface1.GetMembers("baNANa").OfType(Of MethodSymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "baNana".
Dim count = 0
For Each m In allMethods
count = count + 1
Assert.Equal("baNana", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub ProbableExtensionMethod()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C">
<file name="a.vb">
Option Strict On
Class C1
Sub X()
goodext1()
goodext2()
goodext3()
goodext4()
goodext5()
goodext6()
goodext7()
goodext8()
badext1()
badext2()
badext3()
badext4()
badext5()
badext6()
End Sub
End Class
Namespace Blah
Class ExtensionAttribute
Inherits System.Attribute
End Class
End Namespace
</file>
<file name="b.vb"><![CDATA[
Option Strict On
Imports System
Imports System.Runtime.CompilerServices
Imports ExAttribute = System.Runtime.CompilerServices.ExtensionAttribute
Imports Ex2 = System.Runtime.CompilerServices.ExtensionAttribute
Module M1
<[Extension]>
Public Sub goodext1(this As C1)
End Sub
<ExtensionAttribute>
Public Sub goodext2(this As C1)
End Sub
<System.Runtime.CompilerServices.Extension>
Public Sub goodext3(this As C1)
End Sub
<System.Runtime.CompilerServices.ExtensionAttribute>
Public Sub goodext4(this As C1)
End Sub
<[ExAttribute]>
Public Sub goodext5(this As C1)
End Sub
<Ex>
Public Sub goodext6(this As C1)
End Sub
<Ex2>
Public Sub goodext7(this As C1)
End Sub
<AnExt>
Public Sub goodext8(this As C1)
End Sub
<AnExt>
Declare Sub goodext9 Lib "goo" (this As C1)
<Blah.Extension>
Public Sub badext1(this As C1)
End Sub
<Blah.ExtensionAttribute>
Public Sub badext2(this As C1)
End Sub
<Extension>
Public Sub badext3()
End Sub
End Module
]]></file>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System
Imports Blah
Module M2
<Extension>
Public Sub badext4(this As C1)
End Sub
<ExtensionAttribute>
Public Sub badext5(this As C1)
End Sub
<Extension>
Declare Sub badext6 Lib "goo" (this As C1)
End Module
]]></file>
</compilation>, references:={TestMetadata.Net40.SystemCore, TestMetadata.Net40.System}, options:=TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse("AnExt=System.Runtime.CompilerServices.ExtensionAttribute")))
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol)
Dim modM1 = DirectCast(globalNS.GetMembers("M1").Single(), NamedTypeSymbol)
Dim modM2 = DirectCast(globalNS.GetMembers("M2").Single(), NamedTypeSymbol)
Dim goodext1 = DirectCast(modM1.GetMembers("goodext1").Single(), MethodSymbol)
Assert.True(goodext1.IsExtensionMethod)
Assert.True(goodext1.MayBeReducibleExtensionMethod)
Dim goodext2 = DirectCast(modM1.GetMembers("goodext2").Single(), MethodSymbol)
Assert.True(goodext2.IsExtensionMethod)
Assert.True(goodext2.MayBeReducibleExtensionMethod)
Dim goodext3 = DirectCast(modM1.GetMembers("goodext3").Single(), MethodSymbol)
Assert.True(goodext3.IsExtensionMethod)
Assert.True(goodext3.MayBeReducibleExtensionMethod)
Dim goodext4 = DirectCast(modM1.GetMembers("goodext4").Single(), MethodSymbol)
Assert.True(goodext4.IsExtensionMethod)
Assert.True(goodext4.MayBeReducibleExtensionMethod)
Dim goodext5 = DirectCast(modM1.GetMembers("goodext5").Single(), MethodSymbol)
Assert.True(goodext5.IsExtensionMethod)
Assert.True(goodext5.MayBeReducibleExtensionMethod)
Dim goodext6 = DirectCast(modM1.GetMembers("goodext6").Single(), MethodSymbol)
Assert.True(goodext6.IsExtensionMethod)
Assert.True(goodext6.MayBeReducibleExtensionMethod)
Dim goodext7 = DirectCast(modM1.GetMembers("goodext7").Single(), MethodSymbol)
Assert.True(goodext7.IsExtensionMethod)
Assert.True(goodext7.MayBeReducibleExtensionMethod)
Dim goodext8 = DirectCast(modM1.GetMembers("goodext8").Single(), MethodSymbol)
Assert.True(goodext8.IsExtensionMethod)
Assert.True(goodext8.MayBeReducibleExtensionMethod)
Dim goodext9 = DirectCast(modM1.GetMembers("goodext9").Single(), MethodSymbol)
Assert.True(goodext9.IsExtensionMethod)
Assert.True(goodext9.MayBeReducibleExtensionMethod)
Dim badext1 = DirectCast(modM1.GetMembers("badext1").Single(), MethodSymbol)
Assert.False(badext1.IsExtensionMethod)
Assert.True(badext1.MayBeReducibleExtensionMethod)
Dim badext2 = DirectCast(modM1.GetMembers("badext2").Single(), MethodSymbol)
Assert.False(badext2.IsExtensionMethod)
Assert.True(badext2.MayBeReducibleExtensionMethod)
Dim badext3 = DirectCast(modM1.GetMembers("badext3").Single(), MethodSymbol)
Assert.False(badext3.IsExtensionMethod)
Assert.True(badext3.MayBeReducibleExtensionMethod)
Dim badext4 = DirectCast(modM2.GetMembers("badext4").Single(), MethodSymbol)
Assert.False(badext4.IsExtensionMethod)
Assert.True(badext4.MayBeReducibleExtensionMethod)
Dim badext5 = DirectCast(modM2.GetMembers("badext5").Single(), MethodSymbol)
Assert.False(badext5.IsExtensionMethod)
Assert.True(badext5.MayBeReducibleExtensionMethod)
Dim badext6 = DirectCast(modM2.GetMembers("badext6").Single(), MethodSymbol)
Assert.False(badext6.IsExtensionMethod)
Assert.True(badext6.MayBeReducibleExtensionMethod)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext1(this As C1)'.
badext1()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext2(this As C1)'.
badext2()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext4(this As C1)'.
badext4()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Sub badext5(this As C1)'.
badext5()
~~~~~~~
BC30455: Argument not specified for parameter 'this' of 'Public Declare Ansi Sub badext6 Lib "goo" (this As C1)'.
badext6()
~~~~~~~
BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend.
Public Sub badext3()
~~~~~~~
</expected>)
End Sub
<WorkItem(779441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779441")>
<Fact>
Public Sub UserDefinedOperatorLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(c As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim operatorPos = source.IndexOf("+"c)
Dim parenPos = source.IndexOf("("c)
Dim comp = CreateCompilationWithMscorlib40({Parse(source)})
Dim Symbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName).Single()
Dim span = Symbol.Locations.Single().SourceSpan
Assert.Equal(operatorPos, span.Start)
Assert.Equal(parenPos, span.End)
End Sub
<WorkItem(901815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/901815")>
<Fact>
Public Sub UserDefinedConversionLocation()
Dim source = <![CDATA[
Public Class C
Public Shared Operator +(Of T)
Return Nothing
End Operator
End Class
]]>.Value
' Used to raise an exception.
Dim comp = CreateCompilationWithMscorlib40({Parse(source)}, options:=TestOptions.ReleaseDll)
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC33016: Operator '+' must have either one or two parameters.
Public Shared Operator +(Of T)
~
BC30198: ')' expected.
Public Shared Operator +(Of T)
~
BC30199: '(' expected.
Public Shared Operator +(Of T)
~
BC32065: Type parameters cannot be specified on this declaration.
Public Shared Operator +(Of T)
~~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnNonPartial()
Dim source = <![CDATA[
Public Class C
Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.False(m.IsPartialDefinition)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionOnPartialDefinitionOnly()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.Null(m.PartialImplementationPart)
End Sub
<Fact, WorkItem(51082, "https://github.com/dotnet/roslyn/issues/51082")>
Public Sub IsPartialDefinitionWithPartialImplementation()
Dim source = <![CDATA[
Public Class C
Private Partial Sub M()
End Sub
Private Sub M()
End Sub
End Class
]]>.Value
Dim comp = CreateCompilation(source)
comp.AssertTheseDiagnostics()
Dim m As IMethodSymbol = comp.GetMember(Of MethodSymbol)("C.M")
Assert.True(m.IsPartialDefinition)
Assert.Null(m.PartialDefinitionPart)
Assert.False(m.PartialImplementationPart.IsPartialDefinition)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayCompilerInternalOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis
{
[Flags]
internal enum SymbolDisplayCompilerInternalOptions
{
/// <summary>
/// None
/// </summary>
None = 0,
/// <summary>
/// ".ctor" instead of "Goo"
/// </summary>
UseMetadataMethodNames = 1 << 0,
/// <summary>
/// "List`1" instead of "List<T>" ("List(of T)" in VB). Overrides GenericsOptions on
/// types.
/// </summary>
UseArityForGenericTypes = 1 << 1,
/// <summary>
/// Append "[Missing]" to missing Metadata types (for testing).
/// </summary>
FlagMissingMetadataTypes = 1 << 2,
/// <summary>
/// Include the Script type when qualifying type names.
/// </summary>
IncludeScriptType = 1 << 3,
/// <summary>
/// Include custom modifiers (e.g. modopt([mscorlib]System.Runtime.CompilerServices.IsConst)) on
/// the member (return) type and parameters.
/// </summary>
/// <remarks>
/// CONSIDER: custom modifiers are part of the public API, so we might want to move this to SymbolDisplayMemberOptions.
/// </remarks>
IncludeCustomModifiers = 1 << 4,
/// <summary>
/// For a type written as "int[][,]" in C#, then
/// a) setting this option will produce "int[,][]", and
/// b) not setting this option will produce "int[][,]".
/// </summary>
ReverseArrayRankSpecifiers = 1 << 5,
/// <summary>
/// Display `System.ValueTuple` instead of tuple syntax `(...)`.
/// </summary>
UseValueTuple = 1 << 6,
/// <summary>
/// Display `System.[U]IntPtr` instead of `n[u]int`.
/// </summary>
UseNativeIntegerUnderlyingType = 1 << 7,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis
{
[Flags]
internal enum SymbolDisplayCompilerInternalOptions
{
/// <summary>
/// None
/// </summary>
None = 0,
/// <summary>
/// ".ctor" instead of "Goo"
/// </summary>
UseMetadataMethodNames = 1 << 0,
/// <summary>
/// "List`1" instead of "List<T>" ("List(of T)" in VB). Overrides GenericsOptions on
/// types.
/// </summary>
UseArityForGenericTypes = 1 << 1,
/// <summary>
/// Append "[Missing]" to missing Metadata types (for testing).
/// </summary>
FlagMissingMetadataTypes = 1 << 2,
/// <summary>
/// Include the Script type when qualifying type names.
/// </summary>
IncludeScriptType = 1 << 3,
/// <summary>
/// Include custom modifiers (e.g. modopt([mscorlib]System.Runtime.CompilerServices.IsConst)) on
/// the member (return) type and parameters.
/// </summary>
/// <remarks>
/// CONSIDER: custom modifiers are part of the public API, so we might want to move this to SymbolDisplayMemberOptions.
/// </remarks>
IncludeCustomModifiers = 1 << 4,
/// <summary>
/// For a type written as "int[][,]" in C#, then
/// a) setting this option will produce "int[,][]", and
/// b) not setting this option will produce "int[][,]".
/// </summary>
ReverseArrayRankSpecifiers = 1 << 5,
/// <summary>
/// Display `System.ValueTuple` instead of tuple syntax `(...)`.
/// </summary>
UseValueTuple = 1 << 6,
/// <summary>
/// Display `System.[U]IntPtr` instead of `n[u]int`.
/// </summary>
UseNativeIntegerUnderlyingType = 1 << 7,
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Symbols/MemberSignatureComparer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class provides an easy way to combine a MethodSignatureComparer and a PropertySignatureComparer
''' to create a unified MemberSignatureComparer (e.g. for use in a HashSet).
''' </summary>
''' <remarks></remarks>
Friend Class MemberSignatureComparer
Implements IEqualityComparer(Of Symbol)
''' <summary>
''' This instance is used to compare potential WinRT fake members in type projection.
'''
''' FIXME(angocke): This is almost certainly wrong. The semantics of WinRT conflict
''' comparison should probably match overload resolution (i.e., we should not add a member
''' to lookup that would result in ambiguity), but this is closer to what Dev12 does.
'''
''' The real fix here is to establish a spec for how WinRT conflict comparison should be
''' performed. Once this is done we should remove these comments.
''' </summary>
Public Shared ReadOnly WinRTComparer As MemberSignatureComparer =
New MemberSignatureComparer(MethodSignatureComparer.WinRTConflictComparer,
PropertySignatureComparer.WinRTConflictComparer,
EventSignatureComparer.WinRTConflictComparer)
Private ReadOnly _methodComparer As MethodSignatureComparer
Private ReadOnly _propertyComparer As PropertySignatureComparer
Private ReadOnly _eventComparer As EventSignatureComparer
Private Sub New(methodComparer As MethodSignatureComparer,
propertyComparer As PropertySignatureComparer,
eventComparer As EventSignatureComparer)
Me._methodComparer = methodComparer
Me._propertyComparer = propertyComparer
Me._eventComparer = eventComparer
End Sub
Public Overloads Function Equals(sym1 As Symbol, sym2 As Symbol) As Boolean _
Implements IEqualityComparer(Of Symbol).Equals
CheckSymbolKind(sym1)
CheckSymbolKind(sym2)
If sym1.Kind <> sym2.Kind Then
Return False
End If
Select Case sym1.Kind
Case SymbolKind.Method
Return _methodComparer.Equals(DirectCast(sym1, MethodSymbol), DirectCast(sym2, MethodSymbol))
Case SymbolKind.Property
Return _propertyComparer.Equals(DirectCast(sym1, PropertySymbol), DirectCast(sym2, PropertySymbol))
Case SymbolKind.Event
Return _eventComparer.Equals(DirectCast(sym1, EventSymbol), DirectCast(sym2, EventSymbol))
Case Else
' To prevent warning
Return False
End Select
End Function
Public Overloads Function GetHashCode(sym As Symbol) As Integer _
Implements IEqualityComparer(Of Symbol).GetHashCode
Select Case sym.Kind
Case SymbolKind.Method
Return _methodComparer.GetHashCode(DirectCast(sym, MethodSymbol))
Case SymbolKind.Property
Return _propertyComparer.GetHashCode(DirectCast(sym, PropertySymbol))
Case SymbolKind.Event
Return _eventComparer.GetHashCode(DirectCast(sym, EventSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(sym.Kind)
End Select
End Function
<Conditional("DEBUG")>
Private Sub CheckSymbolKind(sym As Symbol)
Select Case sym.Kind
Case SymbolKind.Method, SymbolKind.Property, SymbolKind.Event
Exit Select
Case Else
Debug.Assert(False, "Unexpected symbol kind: " & sym.Kind)
End Select
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class provides an easy way to combine a MethodSignatureComparer and a PropertySignatureComparer
''' to create a unified MemberSignatureComparer (e.g. for use in a HashSet).
''' </summary>
''' <remarks></remarks>
Friend Class MemberSignatureComparer
Implements IEqualityComparer(Of Symbol)
''' <summary>
''' This instance is used to compare potential WinRT fake members in type projection.
'''
''' FIXME(angocke): This is almost certainly wrong. The semantics of WinRT conflict
''' comparison should probably match overload resolution (i.e., we should not add a member
''' to lookup that would result in ambiguity), but this is closer to what Dev12 does.
'''
''' The real fix here is to establish a spec for how WinRT conflict comparison should be
''' performed. Once this is done we should remove these comments.
''' </summary>
Public Shared ReadOnly WinRTComparer As MemberSignatureComparer =
New MemberSignatureComparer(MethodSignatureComparer.WinRTConflictComparer,
PropertySignatureComparer.WinRTConflictComparer,
EventSignatureComparer.WinRTConflictComparer)
Private ReadOnly _methodComparer As MethodSignatureComparer
Private ReadOnly _propertyComparer As PropertySignatureComparer
Private ReadOnly _eventComparer As EventSignatureComparer
Private Sub New(methodComparer As MethodSignatureComparer,
propertyComparer As PropertySignatureComparer,
eventComparer As EventSignatureComparer)
Me._methodComparer = methodComparer
Me._propertyComparer = propertyComparer
Me._eventComparer = eventComparer
End Sub
Public Overloads Function Equals(sym1 As Symbol, sym2 As Symbol) As Boolean _
Implements IEqualityComparer(Of Symbol).Equals
CheckSymbolKind(sym1)
CheckSymbolKind(sym2)
If sym1.Kind <> sym2.Kind Then
Return False
End If
Select Case sym1.Kind
Case SymbolKind.Method
Return _methodComparer.Equals(DirectCast(sym1, MethodSymbol), DirectCast(sym2, MethodSymbol))
Case SymbolKind.Property
Return _propertyComparer.Equals(DirectCast(sym1, PropertySymbol), DirectCast(sym2, PropertySymbol))
Case SymbolKind.Event
Return _eventComparer.Equals(DirectCast(sym1, EventSymbol), DirectCast(sym2, EventSymbol))
Case Else
' To prevent warning
Return False
End Select
End Function
Public Overloads Function GetHashCode(sym As Symbol) As Integer _
Implements IEqualityComparer(Of Symbol).GetHashCode
Select Case sym.Kind
Case SymbolKind.Method
Return _methodComparer.GetHashCode(DirectCast(sym, MethodSymbol))
Case SymbolKind.Property
Return _propertyComparer.GetHashCode(DirectCast(sym, PropertySymbol))
Case SymbolKind.Event
Return _eventComparer.GetHashCode(DirectCast(sym, EventSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(sym.Kind)
End Select
End Function
<Conditional("DEBUG")>
Private Sub CheckSymbolKind(sym As Symbol)
Select Case sym.Kind
Case SymbolKind.Method, SymbolKind.Property, SymbolKind.Event
Exit Select
Case Else
Debug.Assert(False, "Unexpected symbol kind: " & sym.Kind)
End Select
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.RenameType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType
{
public partial class MoveTypeTests : CSharpMoveTypeTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task SingleClassInFile_RenameType()
{
var code =
@"[||]class Class1 { }";
var codeWithTypeRenamedToMatchFileName =
@"class [|test1|] { }";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoreThanOneTypeInFile_RenameType()
{
var code =
@"[||]class Class1
{
class Inner { }
}";
var codeWithTypeRenamedToMatchFileName =
@"class [|test1|]
{
class Inner { }
}";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMissing_TypeNameMatchesFileName_RenameType()
{
// testworkspace creates files like test1.cs, test2.cs and so on..
// so type name matches filename here and rename file action should not be offered.
var code =
@"[||]class test1 { }";
await TestRenameTypeToMatchFileAsync(code, expectedCodeAction: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameType()
{
var code =
@"[||]class Class1 { }
class test1 { }";
await TestRenameTypeToMatchFileAsync(code, expectedCodeAction: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameType()
{
var code =
@"[||]class Class1 { }
class Class2 { }";
var codeWithTypeRenamedToMatchFileName =
@"class [|test1|] { }
class Class2 { }";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameType()
{
var code =
@"class Class1 { }
[||]class Class2 { }";
var codeWithTypeRenamedToMatchFileName =
@"class Class1 { }
class [|test1|] { }";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")]
public async Task NothingOfferedWhenTypeHasNoNameYet1()
{
var code = @"class[||]";
await TestMissingAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")]
public async Task NothingOfferedWhenTypeHasNoNameYet2()
{
var code = @"class [||]";
await TestMissingAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")]
public async Task NothingOfferedWhenTypeHasNoNameYet3()
{
var code = @"class [||] { }";
await TestMissingAsync(code);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType
{
public partial class MoveTypeTests : CSharpMoveTypeTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task SingleClassInFile_RenameType()
{
var code =
@"[||]class Class1 { }";
var codeWithTypeRenamedToMatchFileName =
@"class [|test1|] { }";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoreThanOneTypeInFile_RenameType()
{
var code =
@"[||]class Class1
{
class Inner { }
}";
var codeWithTypeRenamedToMatchFileName =
@"class [|test1|]
{
class Inner { }
}";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMissing_TypeNameMatchesFileName_RenameType()
{
// testworkspace creates files like test1.cs, test2.cs and so on..
// so type name matches filename here and rename file action should not be offered.
var code =
@"[||]class test1 { }";
await TestRenameTypeToMatchFileAsync(code, expectedCodeAction: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameType()
{
var code =
@"[||]class Class1 { }
class test1 { }";
await TestRenameTypeToMatchFileAsync(code, expectedCodeAction: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameType()
{
var code =
@"[||]class Class1 { }
class Class2 { }";
var codeWithTypeRenamedToMatchFileName =
@"class [|test1|] { }
class Class2 { }";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MultipleTopLevelTypesInFileAndNoneMatchFileName2_RenameType()
{
var code =
@"class Class1 { }
[||]class Class2 { }";
var codeWithTypeRenamedToMatchFileName =
@"class Class1 { }
class [|test1|] { }";
await TestRenameTypeToMatchFileAsync(code, codeWithTypeRenamedToMatchFileName);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")]
public async Task NothingOfferedWhenTypeHasNoNameYet1()
{
var code = @"class[||]";
await TestMissingAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")]
public async Task NothingOfferedWhenTypeHasNoNameYet2()
{
var code = @"class [||]";
await TestMissingAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")]
public async Task NothingOfferedWhenTypeHasNoNameYet3()
{
var code = @"class [||] { }";
await TestMissingAsync(code);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Test/Resources/Core/SymbolsTests/TypeForwarders/TypeForwarder1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
public class Base
{
};
public class Derived : Base
{
};
public class GenericBase<T>
{
public class NestedGenericBase<T1>
{
};
};
public class GenericDerived<S> : GenericBase<S>
{
};
public class GenericDerived1<S1, S2> : GenericBase<S1>.NestedGenericBase<S2>
{
};
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
public class Base
{
};
public class Derived : Base
{
};
public class GenericBase<T>
{
public class NestedGenericBase<T1>
{
};
};
public class GenericDerived<S> : GenericBase<S>
{
};
public class GenericDerived1<S1, S2> : GenericBase<S1>.NestedGenericBase<S2>
{
};
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/NamespaceOrTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbol
{
internal abstract Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol { get; }
ImmutableArray<ISymbol> INamespaceOrTypeSymbol.GetMembers()
{
return UnderlyingNamespaceOrTypeSymbol.GetMembers().GetPublicSymbols();
}
ImmutableArray<ISymbol> INamespaceOrTypeSymbol.GetMembers(string name)
{
return UnderlyingNamespaceOrTypeSymbol.GetMembers(name).GetPublicSymbols();
}
ImmutableArray<INamedTypeSymbol> INamespaceOrTypeSymbol.GetTypeMembers()
{
return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers().GetPublicSymbols();
}
ImmutableArray<INamedTypeSymbol> INamespaceOrTypeSymbol.GetTypeMembers(string name)
{
return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers(name).GetPublicSymbols();
}
ImmutableArray<INamedTypeSymbol> INamespaceOrTypeSymbol.GetTypeMembers(string name, int arity)
{
return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers(name, arity).GetPublicSymbols();
}
bool INamespaceOrTypeSymbol.IsNamespace => UnderlyingSymbol.Kind == SymbolKind.Namespace;
bool INamespaceOrTypeSymbol.IsType => UnderlyingSymbol.Kind != SymbolKind.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.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbol
{
internal abstract Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol { get; }
ImmutableArray<ISymbol> INamespaceOrTypeSymbol.GetMembers()
{
return UnderlyingNamespaceOrTypeSymbol.GetMembers().GetPublicSymbols();
}
ImmutableArray<ISymbol> INamespaceOrTypeSymbol.GetMembers(string name)
{
return UnderlyingNamespaceOrTypeSymbol.GetMembers(name).GetPublicSymbols();
}
ImmutableArray<INamedTypeSymbol> INamespaceOrTypeSymbol.GetTypeMembers()
{
return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers().GetPublicSymbols();
}
ImmutableArray<INamedTypeSymbol> INamespaceOrTypeSymbol.GetTypeMembers(string name)
{
return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers(name).GetPublicSymbols();
}
ImmutableArray<INamedTypeSymbol> INamespaceOrTypeSymbol.GetTypeMembers(string name, int arity)
{
return UnderlyingNamespaceOrTypeSymbol.GetTypeMembers(name, arity).GetPublicSymbols();
}
bool INamespaceOrTypeSymbol.IsNamespace => UnderlyingSymbol.Kind == SymbolKind.Namespace;
bool INamespaceOrTypeSymbol.IsType => UnderlyingSymbol.Kind != SymbolKind.Namespace;
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Test2/Diagnostics/GenerateEvent/GenerateEventCrossLanguageTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateEvent
Public Class GenerateEventCrossLanguageTests
Inherits AbstractCrossLanguageUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent.GenerateEventCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventInCSharpFileFromImplementsWithParameterList() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class c
Implements i
Event a(x As Integer) Implements $$i.goo
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document FilePath=<%= DestinationDocument %>>
public interface i
{
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>public interface i
{
event gooEventHandler goo;
}
public delegate void gooEventHandler(int x);
</text>.Value.Trim()
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventInCSharpFileFromImplementsWithType() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class c
Implements i
Event a as EventHandler Implements $$i.goo
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document FilePath=<%= DestinationDocument %>>
public interface i
{
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>using System;
public interface i
{
event EventHandler goo;
}</text>.Value.Trim()
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
<WorkItem(737021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737021")>
Public Async Function TestGenerateEventInCSharpFileFromHandles() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class c
WithEvents field as Program
Sub Goo(x as Integer) Handles field.Ev$$
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document FilePath=<%= DestinationDocument %>>
public class Program
{
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>public class Program
{
public event EvHandler Ev;
}
public delegate void EvHandler(int x);
</text>.Value.Trim()
Await TestAsync(input, expected)
End Function
#Disable Warning CA2243 ' Attribute string literals should parse correctly
<WorkItem(144843, "Generate method stub generates into *.Designer.cs")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function PreferNormalFileOverAutoGeneratedFile_Basic() As Task
#Enable Warning CA2243 ' Attribute string literals should parse correctly
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<Document>
Class c
WithEvents field as UserControl1
Sub Goo(x as Integer) Handles field.Ev$$
End Sub
End Class
</Document>
<Document FilePath="UserControl1.Designer.vb">
' This file is auto-generated
Partial Class UserControl1
End Class
</Document>
<Document FilePath="UserControl1.vb">
Partial Public Class UserControl1
End Class
</Document>
</Project>
</Workspace>
Dim expectedFileWithText =
New Dictionary(Of String, String) From {
{"UserControl1.vb",
<Text>
Partial Public Class UserControl1
Public Event Ev(x As Integer)
End Class
</Text>.Value.Trim()},
{"UserControl1.Designer.vb",
<Text>
' This file is auto-generated
Partial Class UserControl1
End Class
</Text>.Value.Trim()}
}
Await TestAsync(input, fileNameToExpected:=expectedFileWithText)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateEvent
Public Class GenerateEventCrossLanguageTests
Inherits AbstractCrossLanguageUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, language As String) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEvent.GenerateEventCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventInCSharpFileFromImplementsWithParameterList() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class c
Implements i
Event a(x As Integer) Implements $$i.goo
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document FilePath=<%= DestinationDocument %>>
public interface i
{
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>public interface i
{
event gooEventHandler goo;
}
public delegate void gooEventHandler(int x);
</text>.Value.Trim()
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function TestGenerateEventInCSharpFileFromImplementsWithType() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class c
Implements i
Event a as EventHandler Implements $$i.goo
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document FilePath=<%= DestinationDocument %>>
public interface i
{
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>using System;
public interface i
{
event EventHandler goo;
}</text>.Value.Trim()
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
<WorkItem(737021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737021")>
Public Async Function TestGenerateEventInCSharpFileFromHandles() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class c
WithEvents field as Program
Sub Goo(x as Integer) Handles field.Ev$$
End Sub
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSAssembly1" CommonReferences="true">
<Document FilePath=<%= DestinationDocument %>>
public class Program
{
}
</Document>
</Project>
</Workspace>
Dim expected =
<text>public class Program
{
public event EvHandler Ev;
}
public delegate void EvHandler(int x);
</text>.Value.Trim()
Await TestAsync(input, expected)
End Function
#Disable Warning CA2243 ' Attribute string literals should parse correctly
<WorkItem(144843, "Generate method stub generates into *.Designer.cs")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEvent)>
Public Async Function PreferNormalFileOverAutoGeneratedFile_Basic() As Task
#Enable Warning CA2243 ' Attribute string literals should parse correctly
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly1" CommonReferences="true">
<Document>
Class c
WithEvents field as UserControl1
Sub Goo(x as Integer) Handles field.Ev$$
End Sub
End Class
</Document>
<Document FilePath="UserControl1.Designer.vb">
' This file is auto-generated
Partial Class UserControl1
End Class
</Document>
<Document FilePath="UserControl1.vb">
Partial Public Class UserControl1
End Class
</Document>
</Project>
</Workspace>
Dim expectedFileWithText =
New Dictionary(Of String, String) From {
{"UserControl1.vb",
<Text>
Partial Public Class UserControl1
Public Event Ev(x As Integer)
End Class
</Text>.Value.Trim()},
{"UserControl1.Designer.vb",
<Text>
' This file is auto-generated
Partial Class UserControl1
End Class
</Text>.Value.Trim()}
}
Await TestAsync(input, fileNameToExpected:=expectedFileWithText)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/CodeFixes/CodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Implement this type to provide fixes for source code problems.
/// Remember to use <see cref="ExportCodeFixProviderAttribute"/> so the host environment can offer your fixes in a UI.
/// </summary>
public abstract class CodeFixProvider
{
/// <summary>
/// A list of diagnostic IDs that this provider can provide fixes for.
/// </summary>
public abstract ImmutableArray<string> FixableDiagnosticIds { get; }
/// <summary>
/// Computes one or more fixes for the specified <see cref="CodeFixContext"/>.
/// </summary>
/// <param name="context">
/// A <see cref="CodeFixContext"/> containing context information about the diagnostics to fix.
/// The context must only contain diagnostics with a <see cref="Diagnostic.Id"/> included in the <see cref="FixableDiagnosticIds"/> for the current provider.
/// </param>
public abstract Task RegisterCodeFixesAsync(CodeFixContext context);
/// <summary>
/// Gets an optional <see cref="FixAllProvider"/> that can fix all/multiple occurrences of diagnostics fixed by this code fix provider.
/// Return null if the provider doesn't support fix all/multiple occurrences.
/// Otherwise, you can return any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/> or implement your own fix all provider.
/// </summary>
public virtual FixAllProvider? GetFixAllProvider()
=> null;
/// <summary>
/// What priority this provider should run at.
/// </summary>
internal CodeActionRequestPriority RequestPriority
{
get
{
var priority = ComputeRequestPriority();
Contract.ThrowIfFalse(priority is CodeActionRequestPriority.Normal or CodeActionRequestPriority.High);
return priority;
}
}
private protected virtual CodeActionRequestPriority ComputeRequestPriority()
=> CodeActionRequestPriority.Normal;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Implement this type to provide fixes for source code problems.
/// Remember to use <see cref="ExportCodeFixProviderAttribute"/> so the host environment can offer your fixes in a UI.
/// </summary>
public abstract class CodeFixProvider
{
/// <summary>
/// A list of diagnostic IDs that this provider can provide fixes for.
/// </summary>
public abstract ImmutableArray<string> FixableDiagnosticIds { get; }
/// <summary>
/// Computes one or more fixes for the specified <see cref="CodeFixContext"/>.
/// </summary>
/// <param name="context">
/// A <see cref="CodeFixContext"/> containing context information about the diagnostics to fix.
/// The context must only contain diagnostics with a <see cref="Diagnostic.Id"/> included in the <see cref="FixableDiagnosticIds"/> for the current provider.
/// </param>
public abstract Task RegisterCodeFixesAsync(CodeFixContext context);
/// <summary>
/// Gets an optional <see cref="FixAllProvider"/> that can fix all/multiple occurrences of diagnostics fixed by this code fix provider.
/// Return null if the provider doesn't support fix all/multiple occurrences.
/// Otherwise, you can return any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/> or implement your own fix all provider.
/// </summary>
public virtual FixAllProvider? GetFixAllProvider()
=> null;
/// <summary>
/// What priority this provider should run at.
/// </summary>
internal CodeActionRequestPriority RequestPriority
{
get
{
var priority = ComputeRequestPriority();
Contract.ThrowIfFalse(priority is CodeActionRequestPriority.Normal or CodeActionRequestPriority.High);
return priority;
}
}
private protected virtual CodeActionRequestPriority ComputeRequestPriority()
=> CodeActionRequestPriority.Normal;
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/Core/Impl/SolutionExplorer/IAnalyzersCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Internal.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal interface IAnalyzersCommandHandler
{
IContextMenuController AnalyzerFolderContextMenuController { get; }
IContextMenuController AnalyzerContextMenuController { get; }
IContextMenuController DiagnosticContextMenuController { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Internal.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal interface IAnalyzersCommandHandler
{
IContextMenuController AnalyzerFolderContextMenuController { get; }
IContextMenuController AnalyzerContextMenuController { get; }
IContextMenuController DiagnosticContextMenuController { get; }
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResultFlags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
namespace Microsoft.VisualStudio.Debugger.Evaluation
{
[Flags]
public enum DkmEvaluationResultFlags
{
None = 0x0,
SideEffect = 0x1,
Expandable = 0x2,
Boolean = 0x4,
BooleanTrue = 0x8,
RawString = 0x10,
Address = 0x20,
ReadOnly = 0x40,
ILInterpreter = 0x80,
UnflushedSideEffects = 0x100,
HasObjectId = 0x200,
CanHaveObjectId = 0x400,
CrossThreadDependency = 0x800,
Invalid = 0x1000,
Visualized = 0x2000,
ExpandableError = 0x4000,
ExceptionThrown = 0x8000,
ReturnValue = 0x10000,
IsBuiltInType = 0x20000,
CanEvaluateNow = 0x40000,
EnableExtendedSideEffectsUponRefresh = 0x80000,
MemoryFuture = 0x100000,
MemoryPast = 0x200000,
MemoryGap = 0x400000,
HasDataBreakpoint = 0x800000,
CanFavorite = 0x1000000,
IsFavorite = 0x2000000,
HasFavorites = 0x4000000,
IsObjectReplaceable = 0x8000000,
ExpansionHasSideEffects = 0x10000000,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
namespace Microsoft.VisualStudio.Debugger.Evaluation
{
[Flags]
public enum DkmEvaluationResultFlags
{
None = 0x0,
SideEffect = 0x1,
Expandable = 0x2,
Boolean = 0x4,
BooleanTrue = 0x8,
RawString = 0x10,
Address = 0x20,
ReadOnly = 0x40,
ILInterpreter = 0x80,
UnflushedSideEffects = 0x100,
HasObjectId = 0x200,
CanHaveObjectId = 0x400,
CrossThreadDependency = 0x800,
Invalid = 0x1000,
Visualized = 0x2000,
ExpandableError = 0x4000,
ExceptionThrown = 0x8000,
ReturnValue = 0x10000,
IsBuiltInType = 0x20000,
CanEvaluateNow = 0x40000,
EnableExtendedSideEffectsUponRefresh = 0x80000,
MemoryFuture = 0x100000,
MemoryPast = 0x200000,
MemoryGap = 0x400000,
HasDataBreakpoint = 0x800000,
CanFavorite = 0x1000000,
IsFavorite = 0x2000000,
HasFavorites = 0x4000000,
IsObjectReplaceable = 0x8000000,
ExpansionHasSideEffects = 0x10000000,
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/IntegrationTest/TestUtilities/AutomationElementExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using UIAutomationClient;
using AutomationElementIdentifiers = System.Windows.Automation.AutomationElementIdentifiers;
using ControlType = System.Windows.Automation.ControlType;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
public static class AutomationElementExtensions
{
private const int UIA_E_ELEMENTNOTAVAILABLE = unchecked((int)0x80040201);
/// <summary>
/// The number of times to retry a UI automation operation that failed with
/// <see cref="UIA_E_ELEMENTNOTAVAILABLE"/>, not counting the initial call. A value of 2 means the operation
/// will be attempted a total of three times.
/// </summary>
private const int AutomationRetryCount = 2;
/// <summary>
/// The delay between retrying a UI automation operation that failed with
/// <see cref="UIA_E_ELEMENTNOTAVAILABLE"/>.
/// </summary>
private static readonly TimeSpan AutomationRetryDelay = TimeSpan.FromMilliseconds(100);
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendant with the automation ID specified by <paramref name="automationId"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByAutomationId(this IUIAutomationElement parent, string automationId)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.AutomationIdProperty.Id, automationId);
var child = Helper.Retry(
() => parent.FindFirst(TreeScope.TreeScope_Descendants, condition),
AutomationRetryDelay,
retryCount: AutomationRetryCount);
if (child == null)
{
throw new InvalidOperationException($"Could not find item with Automation ID '{automationId}' under '{parent.GetNameForExceptionMessage()}'.");
}
return child;
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendant with the automation ID specified by <paramref name="name"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByName(this IUIAutomationElement parent, string name)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.NameProperty.Id, name);
var child = Helper.Retry(
() => parent.FindFirst(TreeScope.TreeScope_Descendants, condition),
AutomationRetryDelay,
retryCount: AutomationRetryCount);
if (child == null)
{
throw new InvalidOperationException($"Could not find item with name '{name}' under '{parent.GetNameForExceptionMessage()}'.");
}
return child;
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendant with the className specified by <paramref name="className"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByClass(this IUIAutomationElement parent, string className)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.ClassNameProperty.Id, className);
var child = Helper.Retry(
() => parent.FindFirst(TreeScope.TreeScope_Descendants, condition),
AutomationRetryDelay,
retryCount: AutomationRetryCount);
if (child == null)
{
throw new InvalidOperationException($"Could not find item with class '{className}' under '{parent.GetNameForExceptionMessage()}'.");
}
return child;
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns all descendants with the given <paramref name="className"/>.
/// If none are found, the resulting collection will be empty.
/// </summary>
/// <returns></returns>
public static IUIAutomationElementArray FindDescendantsByClass(this IUIAutomationElement parent, string className)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.ClassNameProperty.Id, className);
return parent.FindAll(TreeScope.TreeScope_Descendants, condition);
}
public static T GetCurrentPattern<T>(this IUIAutomationElement element, int patternId)
{
return RetryIfNotAvailable(
e => (T)element.GetCurrentPattern(patternId),
element);
}
/// <summary>
/// Invokes an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationInvokePattern"/>.
/// </summary>
public static void Invoke(this IUIAutomationElement element)
{
var invokePattern = element.GetCurrentPattern<IUIAutomationInvokePattern>(UIA_PatternIds.UIA_InvokePatternId);
if (invokePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Invoke(),
invokePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the InvokePattern.");
}
}
/// <summary>
/// Expands an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationExpandCollapsePattern"/>.
/// </summary>
public static void Expand(this IUIAutomationElement element)
{
var expandCollapsePattern = element.GetCurrentPattern<IUIAutomationExpandCollapsePattern>(UIA_PatternIds.UIA_ExpandCollapsePatternId);
if (expandCollapsePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Expand(),
expandCollapsePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ExpandCollapsePattern.");
}
}
/// <summary>
/// Collapses an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationExpandCollapsePattern"/>.
/// </summary>
public static void Collapse(this IUIAutomationElement element)
{
var expandCollapsePattern = element.GetCurrentPattern<IUIAutomationExpandCollapsePattern>(UIA_PatternIds.UIA_ExpandCollapsePatternId);
if (expandCollapsePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Collapse(),
expandCollapsePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ExpandCollapsePattern.");
}
}
/// <summary>
/// Selects an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationSelectionItemPattern"/>.
/// </summary>
public static void Select(this IUIAutomationElement element)
{
var selectionItemPattern = element.GetCurrentPattern<IUIAutomationSelectionItemPattern>(UIA_PatternIds.UIA_SelectionItemPatternId);
if (selectionItemPattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Select(),
selectionItemPattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the SelectionItemPattern.");
}
}
/// <summary>
/// Gets the value of the given <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationValuePattern"/>.
/// </summary>
public static string GetValue(this IUIAutomationElement element)
{
var valuePattern = element.GetCurrentPattern<IUIAutomationValuePattern>(UIA_PatternIds.UIA_ValuePatternId);
if (valuePattern != null)
{
return RetryIfNotAvailable(
pattern => pattern.CurrentValue,
valuePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ValuePattern.");
}
}
/// <summary>
/// Sets the value of the given <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationValuePattern"/>.
/// </summary>
public static void SetValue(this IUIAutomationElement element, string value)
{
var valuePattern = element.GetCurrentPattern<IUIAutomationValuePattern>(UIA_PatternIds.UIA_ValuePatternId);
if (valuePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.SetValue(value),
valuePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ValuePattern.");
}
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendent following the <paramref name="path"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByPath(this IUIAutomationElement element, string path)
{
var pathParts = path.Split(".".ToCharArray());
// traverse the path
var item = element;
foreach (var pathPart in pathParts)
{
var next = item.FindFirst(TreeScope.TreeScope_Descendants, Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.LocalizedControlTypeProperty.Id, pathPart));
if (next == null)
{
ThrowUnableToFindChildException(path, item);
}
item = next;
}
return item;
}
[DoesNotReturn]
private static void ThrowUnableToFindChildException(string path, IUIAutomationElement item)
{
// if not found, build a list of available children for debugging purposes
var validChildren = new List<string?>();
try
{
var children = item.GetCachedChildren();
for (var i = 0; i < children.Length; i++)
{
validChildren.Add(SimpleControlTypeName(children.GetElement(i)));
}
}
catch (InvalidOperationException)
{
// if the cached children can't be enumerated, don't blow up trying to display debug info
}
throw new InvalidOperationException(string.Format("Unable to find a child named {0}. Possible values: ({1}).",
path,
string.Join(", ", validChildren)));
}
private static string? SimpleControlTypeName(IUIAutomationElement element)
{
var type = ControlType.LookupById((int)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ControlTypeProperty.Id));
return type?.LocalizedControlType;
}
/// <summary>
/// Returns true if the given <see cref="IUIAutomationElement"/> is in the <see cref="ToggleState.ToggleState_On"/> state.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationTogglePattern"/>.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static bool IsToggledOn(this IUIAutomationElement element)
{
var togglePattern = element.GetCurrentPattern<IUIAutomationTogglePattern>(UIA_PatternIds.UIA_TogglePatternId);
if (togglePattern != null)
{
return RetryIfNotAvailable(
pattern => pattern.CurrentToggleState == ToggleState.ToggleState_On,
togglePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the TogglePattern.");
}
}
/// <summary>
/// Cycles through the <see cref="ToggleState"/>s of the given <see cref="IUIAutomationElement"/>.
/// </summary>
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationTogglePattern"/>.
public static void Toggle(this IUIAutomationElement element)
{
var togglePattern = element.GetCurrentPattern<IUIAutomationTogglePattern>(UIA_PatternIds.UIA_TogglePatternId);
if (togglePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Toggle(),
togglePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the TogglePattern.");
}
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/> returns a string representing the "name" of the element, if it has one.
/// </summary>
private static string GetNameForExceptionMessage(this IUIAutomationElement element)
{
return RetryIfNotAvailable(e => e.CurrentAutomationId, element)
?? RetryIfNotAvailable(e => e.CurrentName, element)
?? "<unnamed>";
}
internal static void RetryIfNotAvailable<T>(Action<T> action, T state)
{
// NOTE: The loop termination condition if exceptions are thrown is in the exception filter
for (var i = 0; true; i++)
{
try
{
action(state);
return;
}
catch (COMException e) when (e.HResult == UIA_E_ELEMENTNOTAVAILABLE && i < AutomationRetryCount)
{
Thread.Sleep(AutomationRetryDelay);
continue;
}
}
}
internal static TResult RetryIfNotAvailable<T, TResult>(Func<T, TResult> function, T state)
{
// NOTE: The loop termination condition if exceptions are thrown is in the exception filter
for (var i = 0; true; i++)
{
try
{
return function(state);
}
catch (COMException e) when (e.HResult == UIA_E_ELEMENTNOTAVAILABLE && i < AutomationRetryCount)
{
Thread.Sleep(AutomationRetryDelay);
continue;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using UIAutomationClient;
using AutomationElementIdentifiers = System.Windows.Automation.AutomationElementIdentifiers;
using ControlType = System.Windows.Automation.ControlType;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
public static class AutomationElementExtensions
{
private const int UIA_E_ELEMENTNOTAVAILABLE = unchecked((int)0x80040201);
/// <summary>
/// The number of times to retry a UI automation operation that failed with
/// <see cref="UIA_E_ELEMENTNOTAVAILABLE"/>, not counting the initial call. A value of 2 means the operation
/// will be attempted a total of three times.
/// </summary>
private const int AutomationRetryCount = 2;
/// <summary>
/// The delay between retrying a UI automation operation that failed with
/// <see cref="UIA_E_ELEMENTNOTAVAILABLE"/>.
/// </summary>
private static readonly TimeSpan AutomationRetryDelay = TimeSpan.FromMilliseconds(100);
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendant with the automation ID specified by <paramref name="automationId"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByAutomationId(this IUIAutomationElement parent, string automationId)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.AutomationIdProperty.Id, automationId);
var child = Helper.Retry(
() => parent.FindFirst(TreeScope.TreeScope_Descendants, condition),
AutomationRetryDelay,
retryCount: AutomationRetryCount);
if (child == null)
{
throw new InvalidOperationException($"Could not find item with Automation ID '{automationId}' under '{parent.GetNameForExceptionMessage()}'.");
}
return child;
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendant with the automation ID specified by <paramref name="name"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByName(this IUIAutomationElement parent, string name)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.NameProperty.Id, name);
var child = Helper.Retry(
() => parent.FindFirst(TreeScope.TreeScope_Descendants, condition),
AutomationRetryDelay,
retryCount: AutomationRetryCount);
if (child == null)
{
throw new InvalidOperationException($"Could not find item with name '{name}' under '{parent.GetNameForExceptionMessage()}'.");
}
return child;
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendant with the className specified by <paramref name="className"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByClass(this IUIAutomationElement parent, string className)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.ClassNameProperty.Id, className);
var child = Helper.Retry(
() => parent.FindFirst(TreeScope.TreeScope_Descendants, condition),
AutomationRetryDelay,
retryCount: AutomationRetryCount);
if (child == null)
{
throw new InvalidOperationException($"Could not find item with class '{className}' under '{parent.GetNameForExceptionMessage()}'.");
}
return child;
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns all descendants with the given <paramref name="className"/>.
/// If none are found, the resulting collection will be empty.
/// </summary>
/// <returns></returns>
public static IUIAutomationElementArray FindDescendantsByClass(this IUIAutomationElement parent, string className)
{
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
var condition = Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.ClassNameProperty.Id, className);
return parent.FindAll(TreeScope.TreeScope_Descendants, condition);
}
public static T GetCurrentPattern<T>(this IUIAutomationElement element, int patternId)
{
return RetryIfNotAvailable(
e => (T)element.GetCurrentPattern(patternId),
element);
}
/// <summary>
/// Invokes an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationInvokePattern"/>.
/// </summary>
public static void Invoke(this IUIAutomationElement element)
{
var invokePattern = element.GetCurrentPattern<IUIAutomationInvokePattern>(UIA_PatternIds.UIA_InvokePatternId);
if (invokePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Invoke(),
invokePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the InvokePattern.");
}
}
/// <summary>
/// Expands an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationExpandCollapsePattern"/>.
/// </summary>
public static void Expand(this IUIAutomationElement element)
{
var expandCollapsePattern = element.GetCurrentPattern<IUIAutomationExpandCollapsePattern>(UIA_PatternIds.UIA_ExpandCollapsePatternId);
if (expandCollapsePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Expand(),
expandCollapsePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ExpandCollapsePattern.");
}
}
/// <summary>
/// Collapses an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationExpandCollapsePattern"/>.
/// </summary>
public static void Collapse(this IUIAutomationElement element)
{
var expandCollapsePattern = element.GetCurrentPattern<IUIAutomationExpandCollapsePattern>(UIA_PatternIds.UIA_ExpandCollapsePatternId);
if (expandCollapsePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Collapse(),
expandCollapsePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ExpandCollapsePattern.");
}
}
/// <summary>
/// Selects an <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationSelectionItemPattern"/>.
/// </summary>
public static void Select(this IUIAutomationElement element)
{
var selectionItemPattern = element.GetCurrentPattern<IUIAutomationSelectionItemPattern>(UIA_PatternIds.UIA_SelectionItemPatternId);
if (selectionItemPattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Select(),
selectionItemPattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the SelectionItemPattern.");
}
}
/// <summary>
/// Gets the value of the given <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationValuePattern"/>.
/// </summary>
public static string GetValue(this IUIAutomationElement element)
{
var valuePattern = element.GetCurrentPattern<IUIAutomationValuePattern>(UIA_PatternIds.UIA_ValuePatternId);
if (valuePattern != null)
{
return RetryIfNotAvailable(
pattern => pattern.CurrentValue,
valuePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ValuePattern.");
}
}
/// <summary>
/// Sets the value of the given <see cref="IUIAutomationElement"/>.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationValuePattern"/>.
/// </summary>
public static void SetValue(this IUIAutomationElement element, string value)
{
var valuePattern = element.GetCurrentPattern<IUIAutomationValuePattern>(UIA_PatternIds.UIA_ValuePatternId);
if (valuePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.SetValue(value),
valuePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ValuePattern.");
}
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/>, returns a descendent following the <paramref name="path"/>.
/// Throws an <see cref="InvalidOperationException"/> if no such descendant is found.
/// </summary>
public static IUIAutomationElement FindDescendantByPath(this IUIAutomationElement element, string path)
{
var pathParts = path.Split(".".ToCharArray());
// traverse the path
var item = element;
foreach (var pathPart in pathParts)
{
var next = item.FindFirst(TreeScope.TreeScope_Descendants, Helper.Automation.CreatePropertyCondition(AutomationElementIdentifiers.LocalizedControlTypeProperty.Id, pathPart));
if (next == null)
{
ThrowUnableToFindChildException(path, item);
}
item = next;
}
return item;
}
[DoesNotReturn]
private static void ThrowUnableToFindChildException(string path, IUIAutomationElement item)
{
// if not found, build a list of available children for debugging purposes
var validChildren = new List<string?>();
try
{
var children = item.GetCachedChildren();
for (var i = 0; i < children.Length; i++)
{
validChildren.Add(SimpleControlTypeName(children.GetElement(i)));
}
}
catch (InvalidOperationException)
{
// if the cached children can't be enumerated, don't blow up trying to display debug info
}
throw new InvalidOperationException(string.Format("Unable to find a child named {0}. Possible values: ({1}).",
path,
string.Join(", ", validChildren)));
}
private static string? SimpleControlTypeName(IUIAutomationElement element)
{
var type = ControlType.LookupById((int)element.GetCurrentPropertyValue(AutomationElementIdentifiers.ControlTypeProperty.Id));
return type?.LocalizedControlType;
}
/// <summary>
/// Returns true if the given <see cref="IUIAutomationElement"/> is in the <see cref="ToggleState.ToggleState_On"/> state.
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationTogglePattern"/>.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static bool IsToggledOn(this IUIAutomationElement element)
{
var togglePattern = element.GetCurrentPattern<IUIAutomationTogglePattern>(UIA_PatternIds.UIA_TogglePatternId);
if (togglePattern != null)
{
return RetryIfNotAvailable(
pattern => pattern.CurrentToggleState == ToggleState.ToggleState_On,
togglePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the TogglePattern.");
}
}
/// <summary>
/// Cycles through the <see cref="ToggleState"/>s of the given <see cref="IUIAutomationElement"/>.
/// </summary>
/// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not
/// support the <see cref="IUIAutomationTogglePattern"/>.
public static void Toggle(this IUIAutomationElement element)
{
var togglePattern = element.GetCurrentPattern<IUIAutomationTogglePattern>(UIA_PatternIds.UIA_TogglePatternId);
if (togglePattern != null)
{
RetryIfNotAvailable(
pattern => pattern.Toggle(),
togglePattern);
}
else
{
throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the TogglePattern.");
}
}
/// <summary>
/// Given an <see cref="IUIAutomationElement"/> returns a string representing the "name" of the element, if it has one.
/// </summary>
private static string GetNameForExceptionMessage(this IUIAutomationElement element)
{
return RetryIfNotAvailable(e => e.CurrentAutomationId, element)
?? RetryIfNotAvailable(e => e.CurrentName, element)
?? "<unnamed>";
}
internal static void RetryIfNotAvailable<T>(Action<T> action, T state)
{
// NOTE: The loop termination condition if exceptions are thrown is in the exception filter
for (var i = 0; true; i++)
{
try
{
action(state);
return;
}
catch (COMException e) when (e.HResult == UIA_E_ELEMENTNOTAVAILABLE && i < AutomationRetryCount)
{
Thread.Sleep(AutomationRetryDelay);
continue;
}
}
}
internal static TResult RetryIfNotAvailable<T, TResult>(Func<T, TResult> function, T state)
{
// NOTE: The loop termination condition if exceptions are thrown is in the exception filter
for (var i = 0; true; i++)
{
try
{
return function(state);
}
catch (COMException e) when (e.HResult == UIA_E_ELEMENTNOTAVAILABLE && i < AutomationRetryCount)
{
Thread.Sleep(AutomationRetryDelay);
continue;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Lowering/AsyncRewriter/AsyncRewriter.AsyncMethodToClassRewriter.Spilling.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class AsyncRewriter
Inherits StateMachineRewriter(Of CapturedSymbolOrExpression)
Partial Friend Class AsyncMethodToClassRewriter
Inherits StateMachineMethodToClassRewriter
Private Shared Function NeedsSpill(node As BoundExpression) As Boolean
If node Is Nothing Then
Return False
End If
Select Case node.Kind
Case BoundKind.SpillSequence
Return True
Case BoundKind.ArrayInitialization
Debug.Assert(False, "How BoundArrayInitialization got here? ArrayInitializerNeedsSpill(...) should be used instead")
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
Case Else
Return False
End Select
End Function
Private Shared Function NeedsSpill(nodes As ImmutableArray(Of BoundExpression)) As Boolean
If Not nodes.IsEmpty Then
For Each node In nodes
If NeedsSpill(node) Then
Return True
End If
Next
End If
Return False
End Function
Private Shared Function ArrayInitializerNeedsSpill(node As BoundArrayInitialization) As Boolean
If node Is Nothing Then
Return False
End If
For Each initializer In node.Initializers
If initializer.Kind = BoundKind.ArrayInitialization Then
If ArrayInitializerNeedsSpill(DirectCast(initializer, BoundArrayInitialization)) Then
Return True
End If
Else
If NeedsSpill(initializer) Then
Return True
End If
End If
Next
Return False
End Function
Private Structure ExpressionsWithReceiver
Public ReadOnly ReceiverOpt As BoundExpression
Public ReadOnly Arguments As ImmutableArray(Of BoundExpression)
Public Sub New(receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression))
Me.ReceiverOpt = receiverOpt
Me.Arguments = arguments
End Sub
End Structure
''' <summary>
''' Spill an expression list with a receiver (e.g. array access, method call),
''' where at least one of the receiver or the arguments contains an await expression.
''' </summary>
Private Function SpillExpressionsWithReceiver(receiverOpt As BoundExpression,
isReceiverOfAMethodCall As Boolean,
expressions As ImmutableArray(Of BoundExpression),
<[In], Out> ByRef spillBuilder As SpillBuilder) As ExpressionsWithReceiver
If receiverOpt Is Nothing Then
Return New ExpressionsWithReceiver(Nothing, SpillExpressionList(spillBuilder, expressions, firstArgumentIsAReceiverOfAMethodCall:=False))
End If
' We have a non-null receiver, and an expression of the form:
' receiver(arg1/index1, arg2/index2, ..., argN/indexN)
' or:
' receiver.M(arg1, arg2, ... argN)
' Build a list containing the receiver and all expressions (in that order)
Dim allExpressions = ImmutableArray.Create(Of BoundExpression)(receiverOpt).Concat(expressions)
' Spill the expressions (and possibly the receiver):
Dim allSpilledExpressions = SpillExpressionList(spillBuilder, allExpressions, isReceiverOfAMethodCall)
Return New ExpressionsWithReceiver(allSpilledExpressions.First(), allSpilledExpressions.RemoveAt(0))
End Function
''' <summary>
''' Spill a list of expressions (e.g. the arguments of a method call).
'''
''' The expressions are processed right-to-left. Once an expression has been found that contains an await
''' expression, all subsequent expressions are spilled.
'''
''' Example:
'''
''' (1 + 2, await t1, Goo(), await t2, 3 + 4)
'''
''' becomes:
'''
''' Spill(
''' spill1 = 1 + 2,
''' spill2 = await t1,
''' spill3 = Goo(),
''' (spill1, spill2, spill3, await t2, 3 + 4))
'''
''' NOTE: Consider nested array initializers:
'''
''' new int[] {
''' { 1, await t1 },
''' { 3, await t2 }
''' }
'''
''' If the arguments of the top-level initializer had already been spilled, we would end up trying to spill
''' something like this:
'''
''' new int[] {
''' Spill(
''' spill1 = 1,
''' { spill1, await t1 }),
''' Spill(
''' spill2 = 3,
''' { spill2, await t2 })
''' }
'''
''' The normal rewriting would produce:
'''
''' Spill(
''' spill1 = 1,
''' spill3 = { spill1, await t1 },
''' spill2 = 3,
''' int[] a = new int[] {
''' spill3,
''' { spill2, await t2 }))
'''
''' Which is invalid, because spill3 does not have a type.
'''
''' To solve this problem the expression list spilled descends into nested array initializers.
'''
''' </summary>
Private Function SpillExpressionList(<[In], Out> ByRef builder As SpillBuilder,
expressions As ImmutableArray(Of BoundExpression),
firstArgumentIsAReceiverOfAMethodCall As Boolean
) As ImmutableArray(Of BoundExpression)
Dim spillBuilders = ArrayBuilder(Of SpillBuilder).GetInstance()
Dim newArgs As ImmutableArray(Of BoundExpression) = SpillArgumentListInner(expressions, spillBuilders, firstArgumentIsAReceiverOfAMethodCall, False)
For index = spillBuilders.Count - 1 To 0 Step -1
builder.AddSpill(spillBuilders(index))
spillBuilders(index).Free()
Next
spillBuilders.Free()
Debug.Assert(expressions.Length = newArgs.Length)
Return newArgs
End Function
Private Function SpillExpressionList(<[In], Out> ByRef builder As SpillBuilder,
ParamArray expressions() As BoundExpression) As ImmutableArray(Of BoundExpression)
Return SpillExpressionList(builder, expressions.AsImmutableOrNull, firstArgumentIsAReceiverOfAMethodCall:=False)
End Function
Private Function SpillArgumentListInner(arguments As ImmutableArray(Of BoundExpression),
spillBuilders As ArrayBuilder(Of SpillBuilder),
firstArgumentIsAReceiverOfAMethodCall As Boolean,
<[In], Out> ByRef spilledFirstArg As Boolean) As ImmutableArray(Of BoundExpression)
Dim newArgs(arguments.Length - 1) As BoundExpression
For index = arguments.Length - 1 To 0 Step -1
Dim arg As BoundExpression = arguments(index)
If arg.Kind = BoundKind.ArrayInitialization Then
' Descend into a nested array initializer:
Dim nestedInitializer = DirectCast(arg, BoundArrayInitialization)
Dim newInitializers As ImmutableArray(Of BoundExpression) =
SpillArgumentListInner(nestedInitializer.Initializers, spillBuilders, False, spilledFirstArg)
newArgs(index) = nestedInitializer.Update(newInitializers, nestedInitializer.Type)
Continue For
End If
Dim builder As New SpillBuilder()
Dim newExpression As BoundExpression
If Not spilledFirstArg Then
If arg.Kind = BoundKind.SpillSequence Then
' We have found the right-most expression containing an await expression.
' Save the await result to a temp local
spilledFirstArg = True
Dim spill = DirectCast(arg, BoundSpillSequence)
builder.AddSpill(spill)
newExpression = spill.ValueOpt
Debug.Assert(newExpression IsNot Nothing)
Else
' We are to the right of any await-containing expressions.
' The args do not yet need to be spilled.
newExpression = arg
End If
Else
' We are to the left of an await-containing expression. Spill the arg.
newExpression = SpillValue(arg,
isReceiver:=(index = 0 AndAlso firstArgumentIsAReceiverOfAMethodCall),
evaluateSideEffects:=True,
builder:=builder)
End If
newArgs(index) = newExpression
If Not builder.IsEmpty Then
spillBuilders.Add(builder)
End If
Next
Return newArgs.AsImmutableOrNull
End Function
Private Function SpillValue(expr As BoundExpression, <[In], Out> ByRef builder As SpillBuilder) As BoundExpression
Return SpillValue(expr, isReceiver:=False, evaluateSideEffects:=True, builder:=builder)
End Function
Private Function SpillValue(expr As BoundExpression, isReceiver As Boolean, evaluateSideEffects As Boolean, <[In], Out> ByRef builder As SpillBuilder) As BoundExpression
If Unspillable(expr) Then
Return expr
ElseIf isReceiver OrElse expr.IsLValue Then
Return SpillLValue(expr, isReceiver, evaluateSideEffects, builder)
Else
Return SpillRValue(expr, builder)
End If
End Function
Private Function SpillLValue(expr As BoundExpression, isReceiver As Boolean, evaluateSideEffects As Boolean, <[In], Out> ByRef builder As SpillBuilder, Optional isAssignmentTarget As Boolean = False) As BoundExpression
Debug.Assert(expr IsNot Nothing)
Debug.Assert(isReceiver OrElse expr.IsLValue)
If isReceiver AndAlso expr.Type.IsReferenceType AndAlso
Not expr.Type.IsTypeParameter() Then ' Skip type parameters to enforce Dev12 behavior
Return SpillRValue(expr.MakeRValue(), builder)
End If
Select Case expr.Kind
Case BoundKind.Sequence
Dim sequence = DirectCast(expr, BoundSequence)
builder.AddLocals(sequence.Locals)
Dim sideEffects As ImmutableArray(Of BoundExpression) = sequence.SideEffects
If Not sideEffects.IsEmpty Then
For Each sideEffect In sideEffects
If NeedsSpill(sideEffect) Then
Debug.Assert(sideEffect.Kind = BoundKind.SpillSequence)
Dim spill = DirectCast(sideEffect, BoundSpillSequence)
builder.AssumeFieldsIfNeeded(spill)
builder.AddStatement(Me.RewriteSpillSequenceIntoBlock(spill, True))
Else
builder.AddStatement(Me.F.ExpressionStatement(sideEffect))
End If
Next
End If
Return SpillLValue(sequence.ValueOpt, evaluateSideEffects, isReceiver, builder)
Case BoundKind.SpillSequence
Dim spill = DirectCast(expr, BoundSpillSequence)
builder.AddSpill(spill)
Debug.Assert(spill.ValueOpt IsNot Nothing)
Return SpillLValue(spill.ValueOpt, isReceiver, evaluateSideEffects, builder)
Case BoundKind.ArrayAccess
Dim array = DirectCast(expr, BoundArrayAccess)
Dim spilledExpression As BoundExpression = SpillRValue(array.Expression, builder)
Dim indices As ImmutableArray(Of BoundExpression) = array.Indices
Dim spilledIndices(indices.Length - 1) As BoundExpression
For i = 0 To indices.Length - 1
spilledIndices(i) = SpillRValue(indices(i), builder)
Next
array = array.Update(spilledExpression, spilledIndices.AsImmutableOrNull, array.IsLValue, array.Type)
' An assignment target is only evaluated on write, so don't evaluate it's side effects
If evaluateSideEffects And Not isAssignmentTarget Then
builder.AddStatement(Me.F.ExpressionStatement(array))
End If
Return array
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(expr, BoundFieldAccess)
If Unspillable(fieldAccess.ReceiverOpt) Then
Return fieldAccess
End If
' An assignment target is only evaluated on write, so don't evaluate it's side effects, but do evaluate side effects of the receiver expression
' Evaluating a field of a struct has no side effects, so only evaluate side effects of the receiver expression
Dim evaluateSideEffectsHere = evaluateSideEffects And Not isAssignmentTarget And fieldAccess.FieldSymbol.ContainingType.IsReferenceType
Dim newReceiver As BoundExpression = SpillValue(fieldAccess.ReceiverOpt,
isReceiver:=True,
evaluateSideEffects:=evaluateSideEffects And Not evaluateSideEffectsHere,
builder:=builder)
fieldAccess = fieldAccess.Update(newReceiver,
fieldAccess.FieldSymbol,
fieldAccess.IsLValue,
fieldAccess.SuppressVirtualCalls,
constantsInProgressOpt:=Nothing,
fieldAccess.Type)
If evaluateSideEffectsHere Then
builder.AddStatement(Me.F.ExpressionStatement(fieldAccess))
End If
Return fieldAccess
Case BoundKind.Local
' Ref locals that appear as l-values in await-containing expressions get hoisted
Debug.Assert(Not DirectCast(expr, BoundLocal).LocalSymbol.IsByRef)
Return expr
Case BoundKind.Parameter
Debug.Assert(Me.Proxies.ContainsKey(DirectCast(expr, BoundParameter).ParameterSymbol))
Return expr
Case Else
Debug.Assert(Not expr.IsLValue, "stack spilling for lvalue: " + expr.Kind.ToString())
Return SpillRValue(expr, builder)
End Select
End Function
Private Function SpillRValue(expr As BoundExpression, <[In], Out> ByRef builder As SpillBuilder) As BoundExpression
Debug.Assert(Not expr.IsLValue)
Select Case expr.Kind
Case BoundKind.Literal
' TODO: do we want to do that for all/some other nodes with const values?
Return expr
Case BoundKind.SpillSequence
Dim spill = DirectCast(expr, BoundSpillSequence)
builder.AddSpill(spill)
Debug.Assert(spill.ValueOpt IsNot Nothing)
Return SpillRValue(spill.ValueOpt, builder)
Case BoundKind.ArrayInitialization
Dim arrayInit = DirectCast(expr, BoundArrayInitialization)
Return arrayInit.Update(SpillExpressionList(builder, arrayInit.Initializers, firstArgumentIsAReceiverOfAMethodCall:=False), arrayInit.Type)
Case BoundKind.ConditionalAccessReceiverPlaceholder
If _conditionalAccessReceiverPlaceholderReplacementInfo Is Nothing OrElse
_conditionalAccessReceiverPlaceholderReplacementInfo.PlaceholderId <> DirectCast(expr, BoundConditionalAccessReceiverPlaceholder).PlaceholderId Then
Throw ExceptionUtilities.Unreachable
End If
_conditionalAccessReceiverPlaceholderReplacementInfo.IsSpilled = True
Return expr
Case BoundKind.ComplexConditionalAccessReceiver
Throw ExceptionUtilities.Unreachable
Case Else
' Create a field for a spill
Dim spillField As FieldSymbol = Me._spillFieldAllocator.AllocateField(expr.Type)
Dim initialization As BoundStatement = Me.F.Assignment(Me.F.Field(Me.F.Me(), spillField, True), expr)
If expr.Kind = BoundKind.SpillSequence Then
initialization = Me.RewriteSpillSequenceIntoBlock(DirectCast(expr, BoundSpillSequence), True, initialization)
End If
builder.AddFieldWithInitialization(spillField, initialization)
Return Me.F.Field(Me.F.Me(), spillField, False)
End Select
Throw ExceptionUtilities.UnexpectedValue(expr.Kind)
End Function
Private Function RewriteSpillSequenceIntoBlock(spill As BoundSpillSequence,
addValueAsExpression As Boolean) As BoundBlock
Return RewriteSpillSequenceIntoBlock(spill, addValueAsExpression, Array.Empty(Of BoundStatement))
End Function
Private Function RewriteSpillSequenceIntoBlock(spill As BoundSpillSequence,
addValueAsExpression As Boolean,
ParamArray additional() As BoundStatement) As BoundBlock
Dim newStatements = ArrayBuilder(Of BoundStatement).GetInstance()
newStatements.AddRange(spill.Statements)
If addValueAsExpression AndAlso spill.ValueOpt IsNot Nothing Then
newStatements.Add(Me.F.ExpressionStatement(spill.ValueOpt))
End If
newStatements.AddRange(additional)
' Release references held by the spill temps:
Dim fields As ImmutableArray(Of FieldSymbol) = spill.SpillFields
For i = 0 To fields.Length - 1
Dim field As FieldSymbol = fields(i)
If TypeNeedsClearing(field.Type) Then
newStatements.Add(F.Assignment(F.Field(F.Me(), field, True), F.Null(field.Type)))
End If
Me._spillFieldAllocator.FreeField(field)
Next
Return Me.F.Block(spill.Locals, newStatements.ToImmutableAndFree())
End Function
Private Function TypeNeedsClearing(type As TypeSymbol) As Boolean
Dim result As Boolean = False
If Me._typesNeedingClearingCache.TryGetValue(type, result) Then
Return result
End If
If type.IsArrayType OrElse type.IsTypeParameter Then
Me._typesNeedingClearingCache.Add(type, True)
Return True
End If
If type.IsErrorType OrElse type.IsEnumType Then
Me._typesNeedingClearingCache.Add(type, False)
Return False
End If
' Short-circuit common cases.
Select Case type.SpecialType
Case SpecialType.System_Void,
SpecialType.System_Boolean,
SpecialType.System_Char,
SpecialType.System_SByte,
SpecialType.System_Byte,
SpecialType.System_Int16,
SpecialType.System_UInt16,
SpecialType.System_Int32,
SpecialType.System_UInt32,
SpecialType.System_Int64,
SpecialType.System_UInt64,
SpecialType.System_Decimal,
SpecialType.System_Single,
SpecialType.System_Double,
SpecialType.System_IntPtr,
SpecialType.System_UIntPtr,
SpecialType.System_TypedReference,
SpecialType.System_ArgIterator,
SpecialType.System_RuntimeArgumentHandle
result = False
Case SpecialType.System_Object,
SpecialType.System_String
result = True
Case Else
Dim namedType = TryCast(type, NamedTypeSymbol)
If namedType IsNot Nothing AndAlso namedType.IsGenericType Then
result = True
Exit Select
End If
Debug.Assert(Not type.IsTypeParameter)
Debug.Assert(Not type.IsEnumType)
If type.TypeKind <> TypeKind.Structure Then
result = True
Exit Select
End If
Debug.Assert(namedType IsNot Nothing, "Structure which is not a NamedTypeSymbol??")
' Prevent cycles
Me._typesNeedingClearingCache.Add(type, True)
result = False
' For structures, go through the fields
For Each member In type.GetMembersUnordered
If Not member.IsShared Then
Select Case member.Kind
Case SymbolKind.Event
If TypeNeedsClearing(DirectCast(member, EventSymbol).AssociatedField.Type) Then
result = True
Exit Select
End If
Case SymbolKind.Field
If TypeNeedsClearing(DirectCast(member, FieldSymbol).Type) Then
result = True
Exit Select
End If
End Select
End If
Next
Me._typesNeedingClearingCache.Remove(type)
' Note: structures with cycles will *NOT* be cleared
End Select
Me._typesNeedingClearingCache.Add(type, result)
Return result
End Function
Private Shared Function Unspillable(node As BoundExpression) As Boolean
If node Is Nothing Then
Return True
End If
Select Case node.Kind
Case BoundKind.Literal
Return True
Case BoundKind.MeReference
Return True
Case BoundKind.MyBaseReference,
BoundKind.MyClassReference
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
Case BoundKind.TypeExpression
Return True
Case Else
Return False
End Select
End Function
Private Shared Function SpillSequenceWithNewValue(spill As BoundSpillSequence, newValue As BoundExpression) As BoundSpillSequence
Return spill.Update(spill.Locals, spill.SpillFields, spill.Statements, newValue, newValue.Type)
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class AsyncRewriter
Inherits StateMachineRewriter(Of CapturedSymbolOrExpression)
Partial Friend Class AsyncMethodToClassRewriter
Inherits StateMachineMethodToClassRewriter
Private Shared Function NeedsSpill(node As BoundExpression) As Boolean
If node Is Nothing Then
Return False
End If
Select Case node.Kind
Case BoundKind.SpillSequence
Return True
Case BoundKind.ArrayInitialization
Debug.Assert(False, "How BoundArrayInitialization got here? ArrayInitializerNeedsSpill(...) should be used instead")
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
Case Else
Return False
End Select
End Function
Private Shared Function NeedsSpill(nodes As ImmutableArray(Of BoundExpression)) As Boolean
If Not nodes.IsEmpty Then
For Each node In nodes
If NeedsSpill(node) Then
Return True
End If
Next
End If
Return False
End Function
Private Shared Function ArrayInitializerNeedsSpill(node As BoundArrayInitialization) As Boolean
If node Is Nothing Then
Return False
End If
For Each initializer In node.Initializers
If initializer.Kind = BoundKind.ArrayInitialization Then
If ArrayInitializerNeedsSpill(DirectCast(initializer, BoundArrayInitialization)) Then
Return True
End If
Else
If NeedsSpill(initializer) Then
Return True
End If
End If
Next
Return False
End Function
Private Structure ExpressionsWithReceiver
Public ReadOnly ReceiverOpt As BoundExpression
Public ReadOnly Arguments As ImmutableArray(Of BoundExpression)
Public Sub New(receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression))
Me.ReceiverOpt = receiverOpt
Me.Arguments = arguments
End Sub
End Structure
''' <summary>
''' Spill an expression list with a receiver (e.g. array access, method call),
''' where at least one of the receiver or the arguments contains an await expression.
''' </summary>
Private Function SpillExpressionsWithReceiver(receiverOpt As BoundExpression,
isReceiverOfAMethodCall As Boolean,
expressions As ImmutableArray(Of BoundExpression),
<[In], Out> ByRef spillBuilder As SpillBuilder) As ExpressionsWithReceiver
If receiverOpt Is Nothing Then
Return New ExpressionsWithReceiver(Nothing, SpillExpressionList(spillBuilder, expressions, firstArgumentIsAReceiverOfAMethodCall:=False))
End If
' We have a non-null receiver, and an expression of the form:
' receiver(arg1/index1, arg2/index2, ..., argN/indexN)
' or:
' receiver.M(arg1, arg2, ... argN)
' Build a list containing the receiver and all expressions (in that order)
Dim allExpressions = ImmutableArray.Create(Of BoundExpression)(receiverOpt).Concat(expressions)
' Spill the expressions (and possibly the receiver):
Dim allSpilledExpressions = SpillExpressionList(spillBuilder, allExpressions, isReceiverOfAMethodCall)
Return New ExpressionsWithReceiver(allSpilledExpressions.First(), allSpilledExpressions.RemoveAt(0))
End Function
''' <summary>
''' Spill a list of expressions (e.g. the arguments of a method call).
'''
''' The expressions are processed right-to-left. Once an expression has been found that contains an await
''' expression, all subsequent expressions are spilled.
'''
''' Example:
'''
''' (1 + 2, await t1, Goo(), await t2, 3 + 4)
'''
''' becomes:
'''
''' Spill(
''' spill1 = 1 + 2,
''' spill2 = await t1,
''' spill3 = Goo(),
''' (spill1, spill2, spill3, await t2, 3 + 4))
'''
''' NOTE: Consider nested array initializers:
'''
''' new int[] {
''' { 1, await t1 },
''' { 3, await t2 }
''' }
'''
''' If the arguments of the top-level initializer had already been spilled, we would end up trying to spill
''' something like this:
'''
''' new int[] {
''' Spill(
''' spill1 = 1,
''' { spill1, await t1 }),
''' Spill(
''' spill2 = 3,
''' { spill2, await t2 })
''' }
'''
''' The normal rewriting would produce:
'''
''' Spill(
''' spill1 = 1,
''' spill3 = { spill1, await t1 },
''' spill2 = 3,
''' int[] a = new int[] {
''' spill3,
''' { spill2, await t2 }))
'''
''' Which is invalid, because spill3 does not have a type.
'''
''' To solve this problem the expression list spilled descends into nested array initializers.
'''
''' </summary>
Private Function SpillExpressionList(<[In], Out> ByRef builder As SpillBuilder,
expressions As ImmutableArray(Of BoundExpression),
firstArgumentIsAReceiverOfAMethodCall As Boolean
) As ImmutableArray(Of BoundExpression)
Dim spillBuilders = ArrayBuilder(Of SpillBuilder).GetInstance()
Dim newArgs As ImmutableArray(Of BoundExpression) = SpillArgumentListInner(expressions, spillBuilders, firstArgumentIsAReceiverOfAMethodCall, False)
For index = spillBuilders.Count - 1 To 0 Step -1
builder.AddSpill(spillBuilders(index))
spillBuilders(index).Free()
Next
spillBuilders.Free()
Debug.Assert(expressions.Length = newArgs.Length)
Return newArgs
End Function
Private Function SpillExpressionList(<[In], Out> ByRef builder As SpillBuilder,
ParamArray expressions() As BoundExpression) As ImmutableArray(Of BoundExpression)
Return SpillExpressionList(builder, expressions.AsImmutableOrNull, firstArgumentIsAReceiverOfAMethodCall:=False)
End Function
Private Function SpillArgumentListInner(arguments As ImmutableArray(Of BoundExpression),
spillBuilders As ArrayBuilder(Of SpillBuilder),
firstArgumentIsAReceiverOfAMethodCall As Boolean,
<[In], Out> ByRef spilledFirstArg As Boolean) As ImmutableArray(Of BoundExpression)
Dim newArgs(arguments.Length - 1) As BoundExpression
For index = arguments.Length - 1 To 0 Step -1
Dim arg As BoundExpression = arguments(index)
If arg.Kind = BoundKind.ArrayInitialization Then
' Descend into a nested array initializer:
Dim nestedInitializer = DirectCast(arg, BoundArrayInitialization)
Dim newInitializers As ImmutableArray(Of BoundExpression) =
SpillArgumentListInner(nestedInitializer.Initializers, spillBuilders, False, spilledFirstArg)
newArgs(index) = nestedInitializer.Update(newInitializers, nestedInitializer.Type)
Continue For
End If
Dim builder As New SpillBuilder()
Dim newExpression As BoundExpression
If Not spilledFirstArg Then
If arg.Kind = BoundKind.SpillSequence Then
' We have found the right-most expression containing an await expression.
' Save the await result to a temp local
spilledFirstArg = True
Dim spill = DirectCast(arg, BoundSpillSequence)
builder.AddSpill(spill)
newExpression = spill.ValueOpt
Debug.Assert(newExpression IsNot Nothing)
Else
' We are to the right of any await-containing expressions.
' The args do not yet need to be spilled.
newExpression = arg
End If
Else
' We are to the left of an await-containing expression. Spill the arg.
newExpression = SpillValue(arg,
isReceiver:=(index = 0 AndAlso firstArgumentIsAReceiverOfAMethodCall),
evaluateSideEffects:=True,
builder:=builder)
End If
newArgs(index) = newExpression
If Not builder.IsEmpty Then
spillBuilders.Add(builder)
End If
Next
Return newArgs.AsImmutableOrNull
End Function
Private Function SpillValue(expr As BoundExpression, <[In], Out> ByRef builder As SpillBuilder) As BoundExpression
Return SpillValue(expr, isReceiver:=False, evaluateSideEffects:=True, builder:=builder)
End Function
Private Function SpillValue(expr As BoundExpression, isReceiver As Boolean, evaluateSideEffects As Boolean, <[In], Out> ByRef builder As SpillBuilder) As BoundExpression
If Unspillable(expr) Then
Return expr
ElseIf isReceiver OrElse expr.IsLValue Then
Return SpillLValue(expr, isReceiver, evaluateSideEffects, builder)
Else
Return SpillRValue(expr, builder)
End If
End Function
Private Function SpillLValue(expr As BoundExpression, isReceiver As Boolean, evaluateSideEffects As Boolean, <[In], Out> ByRef builder As SpillBuilder, Optional isAssignmentTarget As Boolean = False) As BoundExpression
Debug.Assert(expr IsNot Nothing)
Debug.Assert(isReceiver OrElse expr.IsLValue)
If isReceiver AndAlso expr.Type.IsReferenceType AndAlso
Not expr.Type.IsTypeParameter() Then ' Skip type parameters to enforce Dev12 behavior
Return SpillRValue(expr.MakeRValue(), builder)
End If
Select Case expr.Kind
Case BoundKind.Sequence
Dim sequence = DirectCast(expr, BoundSequence)
builder.AddLocals(sequence.Locals)
Dim sideEffects As ImmutableArray(Of BoundExpression) = sequence.SideEffects
If Not sideEffects.IsEmpty Then
For Each sideEffect In sideEffects
If NeedsSpill(sideEffect) Then
Debug.Assert(sideEffect.Kind = BoundKind.SpillSequence)
Dim spill = DirectCast(sideEffect, BoundSpillSequence)
builder.AssumeFieldsIfNeeded(spill)
builder.AddStatement(Me.RewriteSpillSequenceIntoBlock(spill, True))
Else
builder.AddStatement(Me.F.ExpressionStatement(sideEffect))
End If
Next
End If
Return SpillLValue(sequence.ValueOpt, evaluateSideEffects, isReceiver, builder)
Case BoundKind.SpillSequence
Dim spill = DirectCast(expr, BoundSpillSequence)
builder.AddSpill(spill)
Debug.Assert(spill.ValueOpt IsNot Nothing)
Return SpillLValue(spill.ValueOpt, isReceiver, evaluateSideEffects, builder)
Case BoundKind.ArrayAccess
Dim array = DirectCast(expr, BoundArrayAccess)
Dim spilledExpression As BoundExpression = SpillRValue(array.Expression, builder)
Dim indices As ImmutableArray(Of BoundExpression) = array.Indices
Dim spilledIndices(indices.Length - 1) As BoundExpression
For i = 0 To indices.Length - 1
spilledIndices(i) = SpillRValue(indices(i), builder)
Next
array = array.Update(spilledExpression, spilledIndices.AsImmutableOrNull, array.IsLValue, array.Type)
' An assignment target is only evaluated on write, so don't evaluate it's side effects
If evaluateSideEffects And Not isAssignmentTarget Then
builder.AddStatement(Me.F.ExpressionStatement(array))
End If
Return array
Case BoundKind.FieldAccess
Dim fieldAccess = DirectCast(expr, BoundFieldAccess)
If Unspillable(fieldAccess.ReceiverOpt) Then
Return fieldAccess
End If
' An assignment target is only evaluated on write, so don't evaluate it's side effects, but do evaluate side effects of the receiver expression
' Evaluating a field of a struct has no side effects, so only evaluate side effects of the receiver expression
Dim evaluateSideEffectsHere = evaluateSideEffects And Not isAssignmentTarget And fieldAccess.FieldSymbol.ContainingType.IsReferenceType
Dim newReceiver As BoundExpression = SpillValue(fieldAccess.ReceiverOpt,
isReceiver:=True,
evaluateSideEffects:=evaluateSideEffects And Not evaluateSideEffectsHere,
builder:=builder)
fieldAccess = fieldAccess.Update(newReceiver,
fieldAccess.FieldSymbol,
fieldAccess.IsLValue,
fieldAccess.SuppressVirtualCalls,
constantsInProgressOpt:=Nothing,
fieldAccess.Type)
If evaluateSideEffectsHere Then
builder.AddStatement(Me.F.ExpressionStatement(fieldAccess))
End If
Return fieldAccess
Case BoundKind.Local
' Ref locals that appear as l-values in await-containing expressions get hoisted
Debug.Assert(Not DirectCast(expr, BoundLocal).LocalSymbol.IsByRef)
Return expr
Case BoundKind.Parameter
Debug.Assert(Me.Proxies.ContainsKey(DirectCast(expr, BoundParameter).ParameterSymbol))
Return expr
Case Else
Debug.Assert(Not expr.IsLValue, "stack spilling for lvalue: " + expr.Kind.ToString())
Return SpillRValue(expr, builder)
End Select
End Function
Private Function SpillRValue(expr As BoundExpression, <[In], Out> ByRef builder As SpillBuilder) As BoundExpression
Debug.Assert(Not expr.IsLValue)
Select Case expr.Kind
Case BoundKind.Literal
' TODO: do we want to do that for all/some other nodes with const values?
Return expr
Case BoundKind.SpillSequence
Dim spill = DirectCast(expr, BoundSpillSequence)
builder.AddSpill(spill)
Debug.Assert(spill.ValueOpt IsNot Nothing)
Return SpillRValue(spill.ValueOpt, builder)
Case BoundKind.ArrayInitialization
Dim arrayInit = DirectCast(expr, BoundArrayInitialization)
Return arrayInit.Update(SpillExpressionList(builder, arrayInit.Initializers, firstArgumentIsAReceiverOfAMethodCall:=False), arrayInit.Type)
Case BoundKind.ConditionalAccessReceiverPlaceholder
If _conditionalAccessReceiverPlaceholderReplacementInfo Is Nothing OrElse
_conditionalAccessReceiverPlaceholderReplacementInfo.PlaceholderId <> DirectCast(expr, BoundConditionalAccessReceiverPlaceholder).PlaceholderId Then
Throw ExceptionUtilities.Unreachable
End If
_conditionalAccessReceiverPlaceholderReplacementInfo.IsSpilled = True
Return expr
Case BoundKind.ComplexConditionalAccessReceiver
Throw ExceptionUtilities.Unreachable
Case Else
' Create a field for a spill
Dim spillField As FieldSymbol = Me._spillFieldAllocator.AllocateField(expr.Type)
Dim initialization As BoundStatement = Me.F.Assignment(Me.F.Field(Me.F.Me(), spillField, True), expr)
If expr.Kind = BoundKind.SpillSequence Then
initialization = Me.RewriteSpillSequenceIntoBlock(DirectCast(expr, BoundSpillSequence), True, initialization)
End If
builder.AddFieldWithInitialization(spillField, initialization)
Return Me.F.Field(Me.F.Me(), spillField, False)
End Select
Throw ExceptionUtilities.UnexpectedValue(expr.Kind)
End Function
Private Function RewriteSpillSequenceIntoBlock(spill As BoundSpillSequence,
addValueAsExpression As Boolean) As BoundBlock
Return RewriteSpillSequenceIntoBlock(spill, addValueAsExpression, Array.Empty(Of BoundStatement))
End Function
Private Function RewriteSpillSequenceIntoBlock(spill As BoundSpillSequence,
addValueAsExpression As Boolean,
ParamArray additional() As BoundStatement) As BoundBlock
Dim newStatements = ArrayBuilder(Of BoundStatement).GetInstance()
newStatements.AddRange(spill.Statements)
If addValueAsExpression AndAlso spill.ValueOpt IsNot Nothing Then
newStatements.Add(Me.F.ExpressionStatement(spill.ValueOpt))
End If
newStatements.AddRange(additional)
' Release references held by the spill temps:
Dim fields As ImmutableArray(Of FieldSymbol) = spill.SpillFields
For i = 0 To fields.Length - 1
Dim field As FieldSymbol = fields(i)
If TypeNeedsClearing(field.Type) Then
newStatements.Add(F.Assignment(F.Field(F.Me(), field, True), F.Null(field.Type)))
End If
Me._spillFieldAllocator.FreeField(field)
Next
Return Me.F.Block(spill.Locals, newStatements.ToImmutableAndFree())
End Function
Private Function TypeNeedsClearing(type As TypeSymbol) As Boolean
Dim result As Boolean = False
If Me._typesNeedingClearingCache.TryGetValue(type, result) Then
Return result
End If
If type.IsArrayType OrElse type.IsTypeParameter Then
Me._typesNeedingClearingCache.Add(type, True)
Return True
End If
If type.IsErrorType OrElse type.IsEnumType Then
Me._typesNeedingClearingCache.Add(type, False)
Return False
End If
' Short-circuit common cases.
Select Case type.SpecialType
Case SpecialType.System_Void,
SpecialType.System_Boolean,
SpecialType.System_Char,
SpecialType.System_SByte,
SpecialType.System_Byte,
SpecialType.System_Int16,
SpecialType.System_UInt16,
SpecialType.System_Int32,
SpecialType.System_UInt32,
SpecialType.System_Int64,
SpecialType.System_UInt64,
SpecialType.System_Decimal,
SpecialType.System_Single,
SpecialType.System_Double,
SpecialType.System_IntPtr,
SpecialType.System_UIntPtr,
SpecialType.System_TypedReference,
SpecialType.System_ArgIterator,
SpecialType.System_RuntimeArgumentHandle
result = False
Case SpecialType.System_Object,
SpecialType.System_String
result = True
Case Else
Dim namedType = TryCast(type, NamedTypeSymbol)
If namedType IsNot Nothing AndAlso namedType.IsGenericType Then
result = True
Exit Select
End If
Debug.Assert(Not type.IsTypeParameter)
Debug.Assert(Not type.IsEnumType)
If type.TypeKind <> TypeKind.Structure Then
result = True
Exit Select
End If
Debug.Assert(namedType IsNot Nothing, "Structure which is not a NamedTypeSymbol??")
' Prevent cycles
Me._typesNeedingClearingCache.Add(type, True)
result = False
' For structures, go through the fields
For Each member In type.GetMembersUnordered
If Not member.IsShared Then
Select Case member.Kind
Case SymbolKind.Event
If TypeNeedsClearing(DirectCast(member, EventSymbol).AssociatedField.Type) Then
result = True
Exit Select
End If
Case SymbolKind.Field
If TypeNeedsClearing(DirectCast(member, FieldSymbol).Type) Then
result = True
Exit Select
End If
End Select
End If
Next
Me._typesNeedingClearingCache.Remove(type)
' Note: structures with cycles will *NOT* be cleared
End Select
Me._typesNeedingClearingCache.Add(type, result)
Return result
End Function
Private Shared Function Unspillable(node As BoundExpression) As Boolean
If node Is Nothing Then
Return True
End If
Select Case node.Kind
Case BoundKind.Literal
Return True
Case BoundKind.MeReference
Return True
Case BoundKind.MyBaseReference,
BoundKind.MyClassReference
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
Case BoundKind.TypeExpression
Return True
Case Else
Return False
End Select
End Function
Private Shared Function SpillSequenceWithNewValue(spill As BoundSpillSequence, newValue As BoundExpression) As BoundSpillSequence
Return spill.Update(spill.Locals, spill.SpillFields, spill.Statements, newValue, newValue.Type)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OrdinaryMethodReferenceFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal class OrdinaryMethodReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol>
{
protected override bool CanFind(IMethodSymbol symbol)
{
return
symbol.MethodKind == MethodKind.Ordinary ||
symbol.MethodKind == MethodKind.DelegateInvoke ||
symbol.MethodKind == MethodKind.DeclareMethod ||
symbol.MethodKind == MethodKind.ReducedExtension ||
symbol.MethodKind == MethodKind.LocalFunction;
}
protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync(
IMethodSymbol symbol,
Solution solution,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// If it's a delegate method, then cascade to the type as well. These guys are
// practically equivalent for users.
if (symbol.ContainingType.TypeKind == TypeKind.Delegate)
{
return Task.FromResult(ImmutableArray.Create<ISymbol>(symbol.ContainingType));
}
else
{
return Task.FromResult(GetOtherPartsOfPartial(symbol));
}
}
private static ImmutableArray<ISymbol> GetOtherPartsOfPartial(IMethodSymbol symbol)
{
if (symbol.PartialDefinitionPart != null)
return ImmutableArray.Create<ISymbol>(symbol.PartialDefinitionPart);
if (symbol.PartialImplementationPart != null)
return ImmutableArray.Create<ISymbol>(symbol.PartialImplementationPart);
return ImmutableArray<ISymbol>.Empty;
}
protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
IMethodSymbol methodSymbol,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// TODO(cyrusn): Handle searching for IDisposable.Dispose (or an implementation
// thereof). in that case, we need to look at documents that have a using in them
// and see if that using binds to this dispose method. We also need to look at
// 'foreach's as the will call 'Dispose' afterwards.
// TODO(cyrusn): Handle searching for linq methods. If the user searches for 'Cast',
// 'Where', 'Select', 'SelectMany', 'Join', 'GroupJoin', 'OrderBy',
// 'OrderByDescending', 'GroupBy', 'ThenBy' or 'ThenByDescending', then we want to
// search in files that have query expressions and see if any query clause binds to
// these methods.
// TODO(cyrusn): Handle searching for Monitor.Enter and Monitor.Exit. If a user
// searches for these, then we should find usages of 'lock(goo)' or 'synclock(goo)'
// since they implicitly call those methods.
var ordinaryDocuments = await FindDocumentsAsync(project, documents, cancellationToken, methodSymbol.Name).ConfigureAwait(false);
var forEachDocuments = IsForEachMethod(methodSymbol)
? await FindDocumentsWithForEachStatementsAsync(project, documents, cancellationToken).ConfigureAwait(false)
: ImmutableArray<Document>.Empty;
var deconstructDocuments = IsDeconstructMethod(methodSymbol)
? await FindDocumentsWithDeconstructionAsync(project, documents, cancellationToken).ConfigureAwait(false)
: ImmutableArray<Document>.Empty;
var awaitExpressionDocuments = IsGetAwaiterMethod(methodSymbol)
? await FindDocumentsWithAwaitExpressionAsync(project, documents, cancellationToken).ConfigureAwait(false)
: ImmutableArray<Document>.Empty;
var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false);
return ordinaryDocuments.Concat(forEachDocuments, deconstructDocuments, awaitExpressionDocuments, documentsWithGlobalAttributes);
}
private static bool IsForEachMethod(IMethodSymbol methodSymbol)
{
return
methodSymbol.Name == WellKnownMemberNames.GetEnumeratorMethodName ||
methodSymbol.Name == WellKnownMemberNames.MoveNextMethodName;
}
private static bool IsDeconstructMethod(IMethodSymbol methodSymbol)
=> methodSymbol.Name == WellKnownMemberNames.DeconstructMethodName;
private static bool IsGetAwaiterMethod(IMethodSymbol methodSymbol)
=> methodSymbol.Name == WellKnownMemberNames.GetAwaiter;
protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
IMethodSymbol symbol,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var nameMatches = await FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false);
var forEachMatches = IsForEachMethod(symbol)
? await FindReferencesInForEachStatementsAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false)
: ImmutableArray<FinderLocation>.Empty;
var deconstructMatches = IsDeconstructMethod(symbol)
? await FindReferencesInDeconstructionAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false)
: ImmutableArray<FinderLocation>.Empty;
var getAwaiterMatches = IsGetAwaiterMethod(symbol)
? await FindReferencesInAwaitExpressionAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false)
: ImmutableArray<FinderLocation>.Empty;
var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false);
return nameMatches.Concat(forEachMatches, deconstructMatches, getAwaiterMatches, suppressionReferences);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal class OrdinaryMethodReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol>
{
protected override bool CanFind(IMethodSymbol symbol)
{
return
symbol.MethodKind == MethodKind.Ordinary ||
symbol.MethodKind == MethodKind.DelegateInvoke ||
symbol.MethodKind == MethodKind.DeclareMethod ||
symbol.MethodKind == MethodKind.ReducedExtension ||
symbol.MethodKind == MethodKind.LocalFunction;
}
protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync(
IMethodSymbol symbol,
Solution solution,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// If it's a delegate method, then cascade to the type as well. These guys are
// practically equivalent for users.
if (symbol.ContainingType.TypeKind == TypeKind.Delegate)
{
return Task.FromResult(ImmutableArray.Create<ISymbol>(symbol.ContainingType));
}
else
{
return Task.FromResult(GetOtherPartsOfPartial(symbol));
}
}
private static ImmutableArray<ISymbol> GetOtherPartsOfPartial(IMethodSymbol symbol)
{
if (symbol.PartialDefinitionPart != null)
return ImmutableArray.Create<ISymbol>(symbol.PartialDefinitionPart);
if (symbol.PartialImplementationPart != null)
return ImmutableArray.Create<ISymbol>(symbol.PartialImplementationPart);
return ImmutableArray<ISymbol>.Empty;
}
protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
IMethodSymbol methodSymbol,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// TODO(cyrusn): Handle searching for IDisposable.Dispose (or an implementation
// thereof). in that case, we need to look at documents that have a using in them
// and see if that using binds to this dispose method. We also need to look at
// 'foreach's as the will call 'Dispose' afterwards.
// TODO(cyrusn): Handle searching for linq methods. If the user searches for 'Cast',
// 'Where', 'Select', 'SelectMany', 'Join', 'GroupJoin', 'OrderBy',
// 'OrderByDescending', 'GroupBy', 'ThenBy' or 'ThenByDescending', then we want to
// search in files that have query expressions and see if any query clause binds to
// these methods.
// TODO(cyrusn): Handle searching for Monitor.Enter and Monitor.Exit. If a user
// searches for these, then we should find usages of 'lock(goo)' or 'synclock(goo)'
// since they implicitly call those methods.
var ordinaryDocuments = await FindDocumentsAsync(project, documents, cancellationToken, methodSymbol.Name).ConfigureAwait(false);
var forEachDocuments = IsForEachMethod(methodSymbol)
? await FindDocumentsWithForEachStatementsAsync(project, documents, cancellationToken).ConfigureAwait(false)
: ImmutableArray<Document>.Empty;
var deconstructDocuments = IsDeconstructMethod(methodSymbol)
? await FindDocumentsWithDeconstructionAsync(project, documents, cancellationToken).ConfigureAwait(false)
: ImmutableArray<Document>.Empty;
var awaitExpressionDocuments = IsGetAwaiterMethod(methodSymbol)
? await FindDocumentsWithAwaitExpressionAsync(project, documents, cancellationToken).ConfigureAwait(false)
: ImmutableArray<Document>.Empty;
var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false);
return ordinaryDocuments.Concat(forEachDocuments, deconstructDocuments, awaitExpressionDocuments, documentsWithGlobalAttributes);
}
private static bool IsForEachMethod(IMethodSymbol methodSymbol)
{
return
methodSymbol.Name == WellKnownMemberNames.GetEnumeratorMethodName ||
methodSymbol.Name == WellKnownMemberNames.MoveNextMethodName;
}
private static bool IsDeconstructMethod(IMethodSymbol methodSymbol)
=> methodSymbol.Name == WellKnownMemberNames.DeconstructMethodName;
private static bool IsGetAwaiterMethod(IMethodSymbol methodSymbol)
=> methodSymbol.Name == WellKnownMemberNames.GetAwaiter;
protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
IMethodSymbol symbol,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var nameMatches = await FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false);
var forEachMatches = IsForEachMethod(symbol)
? await FindReferencesInForEachStatementsAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false)
: ImmutableArray<FinderLocation>.Empty;
var deconstructMatches = IsDeconstructMethod(symbol)
? await FindReferencesInDeconstructionAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false)
: ImmutableArray<FinderLocation>.Empty;
var getAwaiterMatches = IsGetAwaiterMethod(symbol)
? await FindReferencesInAwaitExpressionAsync(symbol, document, semanticModel, cancellationToken).ConfigureAwait(false)
: ImmutableArray<FinderLocation>.Empty;
var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false);
return nameMatches.Concat(forEachMatches, deconstructMatches, getAwaiterMatches, suppressionReferences);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/MSBuildTaskTests/CscTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.CodeAnalysis.BuildTasks;
using Xunit;
using Moq;
using System.IO;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.BuildTasks.UnitTests.TestUtilities;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
public sealed class CscTests
{
[Fact]
public void SingleSource()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void MultipleSourceFiles()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test1.cs", "test2.cs");
Assert.Equal("/out:test1.exe test1.cs test2.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void PathMapOption()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.PathMap = "K1=V1,K2=V2";
Assert.Equal("/pathmap:\"K1=V1,K2=V2\" /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void DeterministicFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Deterministic = true;
Assert.Equal("/out:test.exe /deterministic+ test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Deterministic = false;
Assert.Equal("/out:test.exe /deterministic- test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void PublicSignFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.PublicSign = true;
Assert.Equal("/out:test.exe /publicsign+ test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.PublicSign = false;
Assert.Equal("/out:test.exe /publicsign- test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void RuntimeMetadataVersionFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.RuntimeMetadataVersion = "v1234";
Assert.Equal("/out:test.exe /runtimemetadataversion:v1234 test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.RuntimeMetadataVersion = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void LangVersionFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.LangVersion = "iso-1";
Assert.Equal("/out:test.exe /langversion:iso-1 test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void ChecksumAlgorithmOption()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.ChecksumAlgorithm = "sha256";
Assert.Equal("/out:test.exe /checksumalgorithm:sha256 test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.ChecksumAlgorithm = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.ChecksumAlgorithm = "";
Assert.Equal("/out:test.exe /checksumalgorithm: test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void InstrumentTestNamesFlag()
{
var csc = new Csc();
csc.Instrument = null;
Assert.Equal(string.Empty, csc.GenerateResponseFileContents());
csc = new Csc();
csc.Instrument = "TestCoverage";
Assert.Equal("/instrument:TestCoverage", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Instrument = "TestCoverage,Mumble";
Assert.Equal("/instrument:TestCoverage,Mumble", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Instrument = "TestCoverage,Mumble;Stumble";
Assert.Equal("/instrument:TestCoverage,Mumble,Stumble", csc.GenerateResponseFileContents());
}
[Fact]
public void TargetTypeDll()
{
var csc = new Csc();
csc.TargetType = "library";
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.dll /target:library test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void TargetTypeBad()
{
var csc = new Csc();
csc.TargetType = "bad";
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe /target:bad test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void OutputAssembly()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.OutputAssembly = MSBuildUtil.CreateTaskItem("x.exe");
Assert.Equal("/out:x.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void DefineConstantsSimple()
{
Action<string> test = (s) =>
{
var csc = new Csc();
csc.DefineConstants = s;
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/define:D1;D2 /out:test.exe test.cs", csc.GenerateResponseFileContents());
};
test("D1;D2");
test("D1,D2");
test("D1 D2");
}
[Fact]
public void Features()
{
Action<string> test = (s) =>
{
var csc = new Csc();
csc.Features = s;
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe /features:a /features:b test.cs", csc.GenerateResponseFileContents());
};
test("a;b");
test("a,b");
test("a b");
test(",a;b ");
test(";a;;b;");
test(",a,,b,");
}
[Fact]
public void FeaturesEmpty()
{
foreach (var cur in new[] { "", null })
{
var csc = new Csc();
csc.Features = cur;
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
}
[Fact]
public void DebugType()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "full";
Assert.Equal("/debug:full /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "pdbonly";
Assert.Equal("/debug:pdbonly /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
Assert.Equal("/debug:portable /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "embedded";
Assert.Equal("/debug:embedded /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "";
Assert.Equal("/debug: /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void SourceLink()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.SourceLink = @"C:\x y\z.json";
Assert.Equal(@"/debug:portable /out:test.exe /sourcelink:""C:\x y\z.json"" test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.SourceLink = null;
Assert.Equal(@"/debug:portable /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.SourceLink = "";
Assert.Equal(@"/debug:portable /out:test.exe /sourcelink: test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void Embed()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems(@"test.cs", @"test.txt");
Assert.Equal(@"/debug:portable /out:test.exe /embed:test.cs /embed:test.txt test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems(@"C:\x y\z.json");
Assert.Equal(@"/debug:portable /out:test.exe /embed:""C:\x y\z.json"" test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.EmbeddedFiles = null;
Assert.Equal(@"/debug:portable /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "full";
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems();
Assert.Equal(@"/debug:full /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void EmbedAllSources()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems(@"test.cs", @"test.txt");
csc.EmbedAllSources = true;
Assert.Equal(@"/out:test.exe /embed /embed:test.cs /embed:test.txt test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.EmbedAllSources = true;
Assert.Equal(@"/out:test.exe /embed test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void RefOut()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.OutputRefAssembly = MSBuildUtil.CreateTaskItem("ref\\test.dll");
Assert.Equal("/out:test.exe /refout:ref\\test.dll test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void RefOnly()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.RefOnly = true;
Assert.Equal("/out:test.exe /refonly test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Enabled()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "enable";
Assert.Equal("/nullable:enable /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Disabled()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "disable";
Assert.Equal("/nullable:disable /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Safeonly()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "safeonly";
Assert.Equal("/nullable:safeonly /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Warnings()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "warnings";
Assert.Equal("/nullable:warnings /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Safeonlywarnings()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "safeonlywarnings";
Assert.Equal("/nullable:safeonlywarnings /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Default_01()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Default_02()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")]
public void DisableSdkPath()
{
var csc = new Csc();
csc.DisableSdkPath = true;
Assert.Equal(@"/nosdkpath", csc.GenerateResponseFileContents());
}
[Fact]
public void SharedCompilationId()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.UseSharedCompilation = true;
csc.SharedCompilationId = "testPipeName";
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.UseSharedCompilation = false;
csc.SharedCompilationId = "testPipeName";
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.SharedCompilationId = "testPipeName";
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void EmptyCscToolPath()
{
var csc = new Csc();
csc.ToolPath = "";
csc.ToolExe = Path.Combine("path", "to", "custom_csc");
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
Assert.Equal(Path.Combine("path", "to", "custom_csc"), csc.GeneratePathToTool());
csc = new Csc();
csc.ToolExe = Path.Combine("path", "to", "custom_csc");
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
Assert.Equal(Path.Combine("path", "to", "custom_csc"), csc.GeneratePathToTool());
}
[Fact]
public void EmptyCscToolExe()
{
var csc = new Csc();
csc.ToolPath = Path.Combine("path", "to", "custom_csc");
csc.ToolExe = "";
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
// StartsWith because it can be csc.exe or csc.dll
Assert.StartsWith(Path.Combine("path", "to", "custom_csc", "csc."), csc.GeneratePathToTool());
csc = new Csc();
csc.ToolPath = Path.Combine("path", "to", "custom_csc");
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
Assert.StartsWith(Path.Combine("path", "to", "custom_csc", "csc."), csc.GeneratePathToTool());
}
[Fact]
public void EditorConfig()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.AnalyzerConfigFiles = MSBuildUtil.CreateTaskItems(".editorconfig");
Assert.Equal(@"/out:test.exe /analyzerconfig:.editorconfig test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs", "subdir\\test.cs");
csc.AnalyzerConfigFiles = MSBuildUtil.CreateTaskItems(".editorconfig", "subdir\\.editorconfig");
Assert.Equal($@"/out:test.exe /analyzerconfig:.editorconfig /analyzerconfig:subdir\.editorconfig test.cs subdir{Path.DirectorySeparatorChar}test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.AnalyzerConfigFiles = MSBuildUtil.CreateTaskItems("..\\.editorconfig", "sub dir\\.editorconfig");
Assert.Equal(@"/out:test.exe /analyzerconfig:..\.editorconfig /analyzerconfig:""sub dir\.editorconfig"" test.cs", csc.GenerateResponseFileContents());
}
[Fact]
[WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")]
public void SkipAnalyzersFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.SkipAnalyzers = true;
Assert.Equal("/out:test.exe /skipanalyzers+ test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.SkipAnalyzers = false;
Assert.Equal("/out:test.exe /skipanalyzers- test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
[WorkItem(52467, "https://github.com/dotnet/roslyn/issues/52467")]
public void UnexpectedExceptionLogsMessage()
{
var engine = new MockEngine();
var csc = new Csc()
{
BuildEngine = engine,
};
csc.ExecuteTool(@"q:\path\csc.exe", "", "", new TestableCompilerServerLogger()
{
LogFunc = delegate { throw new Exception(""); }
});
Assert.False(string.IsNullOrEmpty(engine.Log));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.CodeAnalysis.BuildTasks;
using Xunit;
using Moq;
using System.IO;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.BuildTasks.UnitTests.TestUtilities;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
public sealed class CscTests
{
[Fact]
public void SingleSource()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void MultipleSourceFiles()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test1.cs", "test2.cs");
Assert.Equal("/out:test1.exe test1.cs test2.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void PathMapOption()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.PathMap = "K1=V1,K2=V2";
Assert.Equal("/pathmap:\"K1=V1,K2=V2\" /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void DeterministicFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Deterministic = true;
Assert.Equal("/out:test.exe /deterministic+ test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Deterministic = false;
Assert.Equal("/out:test.exe /deterministic- test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void PublicSignFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.PublicSign = true;
Assert.Equal("/out:test.exe /publicsign+ test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.PublicSign = false;
Assert.Equal("/out:test.exe /publicsign- test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void RuntimeMetadataVersionFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.RuntimeMetadataVersion = "v1234";
Assert.Equal("/out:test.exe /runtimemetadataversion:v1234 test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.RuntimeMetadataVersion = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void LangVersionFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.LangVersion = "iso-1";
Assert.Equal("/out:test.exe /langversion:iso-1 test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void ChecksumAlgorithmOption()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.ChecksumAlgorithm = "sha256";
Assert.Equal("/out:test.exe /checksumalgorithm:sha256 test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.ChecksumAlgorithm = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.ChecksumAlgorithm = "";
Assert.Equal("/out:test.exe /checksumalgorithm: test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void InstrumentTestNamesFlag()
{
var csc = new Csc();
csc.Instrument = null;
Assert.Equal(string.Empty, csc.GenerateResponseFileContents());
csc = new Csc();
csc.Instrument = "TestCoverage";
Assert.Equal("/instrument:TestCoverage", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Instrument = "TestCoverage,Mumble";
Assert.Equal("/instrument:TestCoverage,Mumble", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Instrument = "TestCoverage,Mumble;Stumble";
Assert.Equal("/instrument:TestCoverage,Mumble,Stumble", csc.GenerateResponseFileContents());
}
[Fact]
public void TargetTypeDll()
{
var csc = new Csc();
csc.TargetType = "library";
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.dll /target:library test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void TargetTypeBad()
{
var csc = new Csc();
csc.TargetType = "bad";
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe /target:bad test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void OutputAssembly()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.OutputAssembly = MSBuildUtil.CreateTaskItem("x.exe");
Assert.Equal("/out:x.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void DefineConstantsSimple()
{
Action<string> test = (s) =>
{
var csc = new Csc();
csc.DefineConstants = s;
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/define:D1;D2 /out:test.exe test.cs", csc.GenerateResponseFileContents());
};
test("D1;D2");
test("D1,D2");
test("D1 D2");
}
[Fact]
public void Features()
{
Action<string> test = (s) =>
{
var csc = new Csc();
csc.Features = s;
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe /features:a /features:b test.cs", csc.GenerateResponseFileContents());
};
test("a;b");
test("a,b");
test("a b");
test(",a;b ");
test(";a;;b;");
test(",a,,b,");
}
[Fact]
public void FeaturesEmpty()
{
foreach (var cur in new[] { "", null })
{
var csc = new Csc();
csc.Features = cur;
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
}
[Fact]
public void DebugType()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "full";
Assert.Equal("/debug:full /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "pdbonly";
Assert.Equal("/debug:pdbonly /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
Assert.Equal("/debug:portable /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "embedded";
Assert.Equal("/debug:embedded /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "";
Assert.Equal("/debug: /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void SourceLink()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.SourceLink = @"C:\x y\z.json";
Assert.Equal(@"/debug:portable /out:test.exe /sourcelink:""C:\x y\z.json"" test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.SourceLink = null;
Assert.Equal(@"/debug:portable /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.SourceLink = "";
Assert.Equal(@"/debug:portable /out:test.exe /sourcelink: test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void Embed()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems(@"test.cs", @"test.txt");
Assert.Equal(@"/debug:portable /out:test.exe /embed:test.cs /embed:test.txt test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems(@"C:\x y\z.json");
Assert.Equal(@"/debug:portable /out:test.exe /embed:""C:\x y\z.json"" test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "portable";
csc.EmbeddedFiles = null;
Assert.Equal(@"/debug:portable /out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.DebugType = "full";
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems();
Assert.Equal(@"/debug:full /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void EmbedAllSources()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.EmbeddedFiles = MSBuildUtil.CreateTaskItems(@"test.cs", @"test.txt");
csc.EmbedAllSources = true;
Assert.Equal(@"/out:test.exe /embed /embed:test.cs /embed:test.txt test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.EmbedAllSources = true;
Assert.Equal(@"/out:test.exe /embed test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void RefOut()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.OutputRefAssembly = MSBuildUtil.CreateTaskItem("ref\\test.dll");
Assert.Equal("/out:test.exe /refout:ref\\test.dll test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void RefOnly()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.RefOnly = true;
Assert.Equal("/out:test.exe /refonly test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Enabled()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "enable";
Assert.Equal("/nullable:enable /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Disabled()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "disable";
Assert.Equal("/nullable:disable /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Safeonly()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "safeonly";
Assert.Equal("/nullable:safeonly /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Warnings()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "warnings";
Assert.Equal("/nullable:warnings /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Safeonlywarnings()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = "safeonlywarnings";
Assert.Equal("/nullable:safeonlywarnings /out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Default_01()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.Nullable = null;
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void NullableReferenceTypes_Default_02()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")]
public void DisableSdkPath()
{
var csc = new Csc();
csc.DisableSdkPath = true;
Assert.Equal(@"/nosdkpath", csc.GenerateResponseFileContents());
}
[Fact]
public void SharedCompilationId()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.UseSharedCompilation = true;
csc.SharedCompilationId = "testPipeName";
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.UseSharedCompilation = false;
csc.SharedCompilationId = "testPipeName";
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.SharedCompilationId = "testPipeName";
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
public void EmptyCscToolPath()
{
var csc = new Csc();
csc.ToolPath = "";
csc.ToolExe = Path.Combine("path", "to", "custom_csc");
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
Assert.Equal(Path.Combine("path", "to", "custom_csc"), csc.GeneratePathToTool());
csc = new Csc();
csc.ToolExe = Path.Combine("path", "to", "custom_csc");
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
Assert.Equal(Path.Combine("path", "to", "custom_csc"), csc.GeneratePathToTool());
}
[Fact]
public void EmptyCscToolExe()
{
var csc = new Csc();
csc.ToolPath = Path.Combine("path", "to", "custom_csc");
csc.ToolExe = "";
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
// StartsWith because it can be csc.exe or csc.dll
Assert.StartsWith(Path.Combine("path", "to", "custom_csc", "csc."), csc.GeneratePathToTool());
csc = new Csc();
csc.ToolPath = Path.Combine("path", "to", "custom_csc");
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("", csc.GenerateCommandLine());
Assert.StartsWith(Path.Combine("path", "to", "custom_csc", "csc."), csc.GeneratePathToTool());
}
[Fact]
public void EditorConfig()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.AnalyzerConfigFiles = MSBuildUtil.CreateTaskItems(".editorconfig");
Assert.Equal(@"/out:test.exe /analyzerconfig:.editorconfig test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs", "subdir\\test.cs");
csc.AnalyzerConfigFiles = MSBuildUtil.CreateTaskItems(".editorconfig", "subdir\\.editorconfig");
Assert.Equal($@"/out:test.exe /analyzerconfig:.editorconfig /analyzerconfig:subdir\.editorconfig test.cs subdir{Path.DirectorySeparatorChar}test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.AnalyzerConfigFiles = MSBuildUtil.CreateTaskItems("..\\.editorconfig", "sub dir\\.editorconfig");
Assert.Equal(@"/out:test.exe /analyzerconfig:..\.editorconfig /analyzerconfig:""sub dir\.editorconfig"" test.cs", csc.GenerateResponseFileContents());
}
[Fact]
[WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")]
public void SkipAnalyzersFlag()
{
var csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.SkipAnalyzers = true;
Assert.Equal("/out:test.exe /skipanalyzers+ test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
csc.SkipAnalyzers = false;
Assert.Equal("/out:test.exe /skipanalyzers- test.cs", csc.GenerateResponseFileContents());
csc = new Csc();
csc.Sources = MSBuildUtil.CreateTaskItems("test.cs");
Assert.Equal("/out:test.exe test.cs", csc.GenerateResponseFileContents());
}
[Fact]
[WorkItem(52467, "https://github.com/dotnet/roslyn/issues/52467")]
public void UnexpectedExceptionLogsMessage()
{
var engine = new MockEngine();
var csc = new Csc()
{
BuildEngine = engine,
};
csc.ExecuteTool(@"q:\path\csc.exe", "", "", new TestableCompilerServerLogger()
{
LogFunc = delegate { throw new Exception(""); }
});
Assert.False(string.IsNullOrEmpty(engine.Log));
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/TestUtilities/Diagnostics/TestHostDiagnosticUpdateSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
internal class TestHostDiagnosticUpdateSource : AbstractHostDiagnosticUpdateSource
{
private readonly Workspace _workspace;
public TestHostDiagnosticUpdateSource(Workspace workspace)
=> _workspace = workspace;
public override Workspace Workspace
{
get
{
return _workspace;
}
}
public override int GetHashCode()
=> _workspace.GetHashCode();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
internal class TestHostDiagnosticUpdateSource : AbstractHostDiagnosticUpdateSource
{
private readonly Workspace _workspace;
public TestHostDiagnosticUpdateSource(Workspace workspace)
=> _workspace = workspace;
public override Workspace Workspace
{
get
{
return _workspace;
}
}
public override int GetHashCode()
=> _workspace.GetHashCode();
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/VisualBasic/Portable/Structure/Providers/TryBlockStructureProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class TryBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of TryBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As TryBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.TryStatement, autoCollapse:=False,
type:=BlockTypes.Statement, isCollapsible:=True))
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class TryBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of TryBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As TryBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.TryStatement, autoCollapse:=False,
type:=BlockTypes.Statement, isCollapsible:=True))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Types/BuiltInTypesKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Types
''' <summary>
''' Recommends built-in types in various contexts.
''' </summary>
Friend Class BuiltInTypesKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Dim targetToken = context.TargetToken
' Are we right after an As in an Enum declaration?
Dim enumDeclaration = targetToken.GetAncestor(Of EnumStatementSyntax)()
If enumDeclaration IsNot Nothing AndAlso
enumDeclaration.UnderlyingType IsNot Nothing AndAlso
targetToken = enumDeclaration.UnderlyingType.AsKeyword Then
Dim keywordList = GetIntrinsicTypeKeywords(context)
Return keywordList.WhereAsArray(
Function(k) k.Keyword.EndsWith("Byte", StringComparison.Ordinal) OrElse
k.Keyword.EndsWith("Short", StringComparison.Ordinal) OrElse
k.Keyword.EndsWith("Integer", StringComparison.Ordinal) OrElse
k.Keyword.EndsWith("Long", StringComparison.Ordinal))
End If
' Are we inside a type constraint? Because these are never allowed there
If targetToken.GetAncestor(Of TypeParameterSingleConstraintClauseSyntax)() IsNot Nothing OrElse
targetToken.GetAncestor(Of TypeParameterMultipleConstraintClauseSyntax)() IsNot Nothing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' Are we inside an attribute block? They're at least not allowed as the attribute itself
If targetToken.Parent.IsKind(SyntaxKind.AttributeList) Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' Are we in an Imports statement? Type keywords aren't allowed there, just fully qualified type names
If targetToken.GetAncestor(Of ImportsStatementSyntax)() IsNot Nothing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' Are we after Inherits or Implements? Type keywords aren't allowed here.
If targetToken.IsChildToken(Of InheritsStatementSyntax)(Function(n) n.InheritsKeyword) OrElse
targetToken.IsChildToken(Of ImplementsStatementSyntax)(Function(n) n.ImplementsKeyword) Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
If context.IsTypeContext Then
Return GetIntrinsicTypeKeywords(context)
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
Private Shared ReadOnly s_intrinsicKeywordNames As String() = {
"Boolean",
"Byte",
"Char",
"Date",
"Decimal",
"Double",
"Integer",
"Long",
"Object",
"SByte",
"Short",
"Single",
"String",
"UInteger",
"ULong",
"UShort"}
Private Shared ReadOnly s_intrinsicSpecialTypes As SByte() = {
SpecialType.System_Boolean,
SpecialType.System_Byte,
SpecialType.System_Char,
SpecialType.System_DateTime,
SpecialType.System_Decimal,
SpecialType.System_Double,
SpecialType.System_Int32,
SpecialType.System_Int64,
SpecialType.System_Object,
SpecialType.System_SByte,
SpecialType.System_Int16,
SpecialType.System_Single,
SpecialType.System_String,
SpecialType.System_UInt32,
SpecialType.System_UInt64,
SpecialType.System_UInt16}
Private Shared Function GetIntrinsicTypeKeywords(context As VisualBasicSyntaxContext) As ImmutableArray(Of RecommendedKeyword)
Debug.Assert(s_intrinsicKeywordNames.Length = s_intrinsicSpecialTypes.Length)
Dim inferredSpecialTypes = context.InferredTypes.Select(Function(t) t.SpecialType).ToSet()
Dim recommendedKeywords(s_intrinsicKeywordNames.Length - 1) As RecommendedKeyword
For i = 0 To s_intrinsicKeywordNames.Length - 1
Dim keyword As String = s_intrinsicKeywordNames(i)
Dim specialType As SpecialType = DirectCast(s_intrinsicSpecialTypes(i), SpecialType)
Dim priority = If(inferredSpecialTypes.Contains(specialType), SymbolMatchPriority.Keyword, MatchPriority.Default)
recommendedKeywords(i) = New RecommendedKeyword(s_intrinsicKeywordNames(i), Glyph.Keyword,
Function(cancellationToken)
Dim tooltip = GetDocumentationCommentText(context, specialType, cancellationToken)
Return RecommendedKeyword.CreateDisplayParts(keyword, tooltip)
End Function, isIntrinsic:=True, matchPriority:=priority)
Next
Return recommendedKeywords.ToImmutableArray()
End Function
Private Shared Function GetDocumentationCommentText(context As VisualBasicSyntaxContext, type As SpecialType, cancellationToken As CancellationToken) As String
Dim symbol = context.SemanticModel.Compilation.GetSpecialType(type)
Return symbol.GetDocumentationComment(context.SemanticModel.Compilation, Globalization.CultureInfo.CurrentUICulture, expandIncludes:=True, expandInheritdoc:=True, cancellationToken:=cancellationToken).SummaryText
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Types
''' <summary>
''' Recommends built-in types in various contexts.
''' </summary>
Friend Class BuiltInTypesKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Dim targetToken = context.TargetToken
' Are we right after an As in an Enum declaration?
Dim enumDeclaration = targetToken.GetAncestor(Of EnumStatementSyntax)()
If enumDeclaration IsNot Nothing AndAlso
enumDeclaration.UnderlyingType IsNot Nothing AndAlso
targetToken = enumDeclaration.UnderlyingType.AsKeyword Then
Dim keywordList = GetIntrinsicTypeKeywords(context)
Return keywordList.WhereAsArray(
Function(k) k.Keyword.EndsWith("Byte", StringComparison.Ordinal) OrElse
k.Keyword.EndsWith("Short", StringComparison.Ordinal) OrElse
k.Keyword.EndsWith("Integer", StringComparison.Ordinal) OrElse
k.Keyword.EndsWith("Long", StringComparison.Ordinal))
End If
' Are we inside a type constraint? Because these are never allowed there
If targetToken.GetAncestor(Of TypeParameterSingleConstraintClauseSyntax)() IsNot Nothing OrElse
targetToken.GetAncestor(Of TypeParameterMultipleConstraintClauseSyntax)() IsNot Nothing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' Are we inside an attribute block? They're at least not allowed as the attribute itself
If targetToken.Parent.IsKind(SyntaxKind.AttributeList) Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' Are we in an Imports statement? Type keywords aren't allowed there, just fully qualified type names
If targetToken.GetAncestor(Of ImportsStatementSyntax)() IsNot Nothing Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
' Are we after Inherits or Implements? Type keywords aren't allowed here.
If targetToken.IsChildToken(Of InheritsStatementSyntax)(Function(n) n.InheritsKeyword) OrElse
targetToken.IsChildToken(Of ImplementsStatementSyntax)(Function(n) n.ImplementsKeyword) Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
If context.IsTypeContext Then
Return GetIntrinsicTypeKeywords(context)
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
Private Shared ReadOnly s_intrinsicKeywordNames As String() = {
"Boolean",
"Byte",
"Char",
"Date",
"Decimal",
"Double",
"Integer",
"Long",
"Object",
"SByte",
"Short",
"Single",
"String",
"UInteger",
"ULong",
"UShort"}
Private Shared ReadOnly s_intrinsicSpecialTypes As SByte() = {
SpecialType.System_Boolean,
SpecialType.System_Byte,
SpecialType.System_Char,
SpecialType.System_DateTime,
SpecialType.System_Decimal,
SpecialType.System_Double,
SpecialType.System_Int32,
SpecialType.System_Int64,
SpecialType.System_Object,
SpecialType.System_SByte,
SpecialType.System_Int16,
SpecialType.System_Single,
SpecialType.System_String,
SpecialType.System_UInt32,
SpecialType.System_UInt64,
SpecialType.System_UInt16}
Private Shared Function GetIntrinsicTypeKeywords(context As VisualBasicSyntaxContext) As ImmutableArray(Of RecommendedKeyword)
Debug.Assert(s_intrinsicKeywordNames.Length = s_intrinsicSpecialTypes.Length)
Dim inferredSpecialTypes = context.InferredTypes.Select(Function(t) t.SpecialType).ToSet()
Dim recommendedKeywords(s_intrinsicKeywordNames.Length - 1) As RecommendedKeyword
For i = 0 To s_intrinsicKeywordNames.Length - 1
Dim keyword As String = s_intrinsicKeywordNames(i)
Dim specialType As SpecialType = DirectCast(s_intrinsicSpecialTypes(i), SpecialType)
Dim priority = If(inferredSpecialTypes.Contains(specialType), SymbolMatchPriority.Keyword, MatchPriority.Default)
recommendedKeywords(i) = New RecommendedKeyword(s_intrinsicKeywordNames(i), Glyph.Keyword,
Function(cancellationToken)
Dim tooltip = GetDocumentationCommentText(context, specialType, cancellationToken)
Return RecommendedKeyword.CreateDisplayParts(keyword, tooltip)
End Function, isIntrinsic:=True, matchPriority:=priority)
Next
Return recommendedKeywords.ToImmutableArray()
End Function
Private Shared Function GetDocumentationCommentText(context As VisualBasicSyntaxContext, type As SpecialType, cancellationToken As CancellationToken) As String
Dim symbol = context.SemanticModel.Compilation.GetSpecialType(type)
Return symbol.GetDocumentationComment(context.SemanticModel.Compilation, Globalization.CultureInfo.CurrentUICulture, expandIncludes:=True, expandInheritdoc:=True, cancellationToken:=cancellationToken).SummaryText
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/CSharp/Portable/ConvertForToForEach/CSharpConvertForToForEachCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertForToForEach;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared]
internal class CSharpConvertForToForEachCodeRefactoringProvider :
AbstractConvertForToForEachCodeRefactoringProvider<
StatementSyntax,
ForStatementSyntax,
ExpressionSyntax,
MemberAccessExpressionSyntax,
TypeSyntax,
VariableDeclaratorSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpConvertForToForEachCodeRefactoringProvider()
{
}
protected override string GetTitle()
=> CSharpFeaturesResources.Convert_to_foreach;
protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement)
=> forStatement.Statement is BlockSyntax block
? block.Statements
: SyntaxFactory.SingletonList(forStatement.Statement);
protected override bool TryGetForStatementComponents(
ForStatementSyntax forStatement,
out SyntaxToken iterationVariable, out ExpressionSyntax initializer,
out MemberAccessExpressionSyntax memberAccess,
out ExpressionSyntax stepValueExpressionOpt,
CancellationToken cancellationToken)
{
// Look for very specific forms. Basically, only minor variations around:
// for (var i = 0; i < expr.Lenth; i++)
if (forStatement.Declaration != null &&
forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) &&
forStatement.Incrementors.Count == 1)
{
var declaration = forStatement.Declaration;
if (declaration.Variables.Count == 1)
{
var declarator = declaration.Variables[0];
if (declarator.Initializer != null)
{
iterationVariable = declarator.Identifier;
initializer = declarator.Initializer.Value;
var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition;
// Look for: i < expr.Length
if (binaryExpression.Left is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText &&
binaryExpression.Right is MemberAccessExpressionSyntax)
{
memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right;
var incrementor = forStatement.Incrementors[0];
return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt);
}
}
}
}
iterationVariable = default;
memberAccess = null;
initializer = null;
stepValueExpressionOpt = null;
return false;
}
private static bool TryGetStepValue(
SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue)
{
// support
// x++
// ++x
// x += constant_1
ExpressionSyntax operand;
switch (incrementor.Kind())
{
case SyntaxKind.PostIncrementExpression:
operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.PreIncrementExpression:
operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.AddAssignmentExpression:
var assignment = (AssignmentExpressionSyntax)incrementor;
operand = assignment.Left;
stepValue = assignment.Right;
break;
default:
stepValue = null;
return false;
}
return operand is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText;
}
protected override SyntaxNode ConvertForNode(
ForStatementSyntax forStatement, TypeSyntax typeNode,
SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression,
ITypeSymbol iterationVariableType, OptionSet optionSet)
{
typeNode ??= iterationVariableType.GenerateTypeSyntax();
return SyntaxFactory.ForEachStatement(
SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword),
forStatement.OpenParenToken,
typeNode,
foreachIdentifier,
SyntaxFactory.Token(SyntaxKind.InKeyword),
collectionExpression,
forStatement.CloseParenToken,
forStatement.Statement);
}
// C# has no special variable declarator forms that would cause us to not be able to convert.
protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable)
=> true;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertForToForEach;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared]
internal class CSharpConvertForToForEachCodeRefactoringProvider :
AbstractConvertForToForEachCodeRefactoringProvider<
StatementSyntax,
ForStatementSyntax,
ExpressionSyntax,
MemberAccessExpressionSyntax,
TypeSyntax,
VariableDeclaratorSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpConvertForToForEachCodeRefactoringProvider()
{
}
protected override string GetTitle()
=> CSharpFeaturesResources.Convert_to_foreach;
protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement)
=> forStatement.Statement is BlockSyntax block
? block.Statements
: SyntaxFactory.SingletonList(forStatement.Statement);
protected override bool TryGetForStatementComponents(
ForStatementSyntax forStatement,
out SyntaxToken iterationVariable, out ExpressionSyntax initializer,
out MemberAccessExpressionSyntax memberAccess,
out ExpressionSyntax stepValueExpressionOpt,
CancellationToken cancellationToken)
{
// Look for very specific forms. Basically, only minor variations around:
// for (var i = 0; i < expr.Lenth; i++)
if (forStatement.Declaration != null &&
forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) &&
forStatement.Incrementors.Count == 1)
{
var declaration = forStatement.Declaration;
if (declaration.Variables.Count == 1)
{
var declarator = declaration.Variables[0];
if (declarator.Initializer != null)
{
iterationVariable = declarator.Identifier;
initializer = declarator.Initializer.Value;
var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition;
// Look for: i < expr.Length
if (binaryExpression.Left is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText &&
binaryExpression.Right is MemberAccessExpressionSyntax)
{
memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right;
var incrementor = forStatement.Incrementors[0];
return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt);
}
}
}
}
iterationVariable = default;
memberAccess = null;
initializer = null;
stepValueExpressionOpt = null;
return false;
}
private static bool TryGetStepValue(
SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue)
{
// support
// x++
// ++x
// x += constant_1
ExpressionSyntax operand;
switch (incrementor.Kind())
{
case SyntaxKind.PostIncrementExpression:
operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.PreIncrementExpression:
operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.AddAssignmentExpression:
var assignment = (AssignmentExpressionSyntax)incrementor;
operand = assignment.Left;
stepValue = assignment.Right;
break;
default:
stepValue = null;
return false;
}
return operand is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText;
}
protected override SyntaxNode ConvertForNode(
ForStatementSyntax forStatement, TypeSyntax typeNode,
SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression,
ITypeSymbol iterationVariableType, OptionSet optionSet)
{
typeNode ??= iterationVariableType.GenerateTypeSyntax();
return SyntaxFactory.ForEachStatement(
SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword),
forStatement.OpenParenToken,
typeNode,
foreachIdentifier,
SyntaxFactory.Token(SyntaxKind.InKeyword),
collectionExpression,
forStatement.CloseParenToken,
forStatement.Statement);
}
// C# has no special variable declarator forms that would cause us to not be able to convert.
protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable)
=> true;
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Tools/ExternalAccess/OmniSharp/InlineHints/OmniSharpInlineHintsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.InlineHints;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.InlineHints
{
internal static class OmniSharpInlineHintsService
{
public static async Task<ImmutableArray<OmniSharpInlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService<IInlineHintsService>();
var hints = await service.GetInlineHintsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
return hints.SelectAsArray(static h => new OmniSharpInlineHint(
h.Span,
h.DisplayParts,
(document, cancellationToken) => h.GetDescriptionAsync(document, cancellationToken)));
}
}
internal readonly struct OmniSharpInlineHint
{
private readonly Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> _getDescriptionAsync;
public OmniSharpInlineHint(
TextSpan span,
ImmutableArray<TaggedText> displayParts,
Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> getDescriptionAsync)
{
Span = span;
DisplayParts = displayParts;
_getDescriptionAsync = getDescriptionAsync;
}
public readonly TextSpan Span { get; }
public readonly ImmutableArray<TaggedText> DisplayParts { get; }
public Task<ImmutableArray<TaggedText>> GetDescrptionAsync(Document document, CancellationToken cancellationToken)
=> _getDescriptionAsync.Invoke(document, 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.InlineHints;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.InlineHints
{
internal static class OmniSharpInlineHintsService
{
public static async Task<ImmutableArray<OmniSharpInlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService<IInlineHintsService>();
var hints = await service.GetInlineHintsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
return hints.SelectAsArray(static h => new OmniSharpInlineHint(
h.Span,
h.DisplayParts,
(document, cancellationToken) => h.GetDescriptionAsync(document, cancellationToken)));
}
}
internal readonly struct OmniSharpInlineHint
{
private readonly Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> _getDescriptionAsync;
public OmniSharpInlineHint(
TextSpan span,
ImmutableArray<TaggedText> displayParts,
Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>> getDescriptionAsync)
{
Span = span;
DisplayParts = displayParts;
_getDescriptionAsync = getDescriptionAsync;
}
public readonly TextSpan Span { get; }
public readonly ImmutableArray<TaggedText> DisplayParts { get; }
public Task<ImmutableArray<TaggedText>> GetDescrptionAsync(Document document, CancellationToken cancellationToken)
=> _getDescriptionAsync.Invoke(document, cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Compilation/TypeCompilationState.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Represents the state of compilation of one particular type.
''' This includes, for example, a collection of synthesized methods created during lowering.
''' WARNING: Note that the underlying collection classes are not thread-safe and this will
''' need to be revised if emit phase is changed to support multithreading when
''' translating a particular type.
''' </summary>
Friend Class TypeCompilationState
''' <summary> Method's information </summary>
Public Structure MethodWithBody
Public ReadOnly Method As MethodSymbol
Public ReadOnly Body As BoundStatement
Friend Sub New(_method As MethodSymbol, _body As BoundStatement)
Me.Method = _method
Me.Body = _body
End Sub
End Structure
Public ReadOnly Compilation As VisualBasicCompilation
Public staticLambdaFrame As LambdaFrame
' Can be Nothing if we're not emitting.
' During the lowering phase, however, it cannot be Nothing.
Public ReadOnly ModuleBuilderOpt As PEModuleBuilder
''' <summary> Flat array of created methods, non-empty if not-nothing </summary>
Private _synthesizedMethods As ArrayBuilder(Of MethodWithBody) = Nothing
Public ReadOnly InitializeComponentOpt As MethodSymbol
''' <summary>
''' A mapping from (source) iterator or async methods to the compiler-generated classes that implement them.
''' </summary>
Public ReadOnly StateMachineImplementationClass As New Dictionary(Of MethodSymbol, NamedTypeSymbol)(ReferenceEqualityComparer.Instance)
''' <summary>
''' Map of 'MyBase' or 'MyClass' call wrappers; actually each method symbol will
''' only need one wrapper to call it non-virtually;
'''
''' Indeed, if the type have a virtual method M1 overridden, MyBase.M1 will use
''' a wrapper for base type's method and MyClass.M1 a wrapper for this type's method.
'''
''' And if the type does not override a virtual method M1, both MyBase.M1
''' and MyClass.M1 will use a wrapper for base type's method.
''' </summary>
Private _methodWrappers As Dictionary(Of MethodSymbol, MethodSymbol) = Nothing
Private _initializeComponentCallTree As Dictionary(Of MethodSymbol, ImmutableArray(Of MethodSymbol)) = Nothing
Public Sub New(compilation As VisualBasicCompilation, moduleBuilderOpt As PEModuleBuilder, initializeComponentOpt As MethodSymbol)
Me.Compilation = compilation
Me.ModuleBuilderOpt = moduleBuilderOpt
Me.InitializeComponentOpt = initializeComponentOpt
End Sub
''' <summary>
''' Is there any content in the methods collection.
''' </summary>
Public ReadOnly Property HasSynthesizedMethods As Boolean
Get
Return _synthesizedMethods IsNot Nothing
End Get
End Property
''' <summary> Method created with their bodies </summary>
Public ReadOnly Property SynthesizedMethods As ArrayBuilder(Of MethodWithBody)
Get
Return _synthesizedMethods
End Get
End Property
Public Sub AddSynthesizedMethod(method As MethodSymbol, body As BoundStatement)
If _synthesizedMethods Is Nothing Then
_synthesizedMethods = ArrayBuilder(Of MethodWithBody).GetInstance()
End If
_synthesizedMethods.Add(New MethodWithBody(method, body))
End Sub
Public Function HasMethodWrapper(method As MethodSymbol) As Boolean
Return _methodWrappers IsNot Nothing AndAlso _methodWrappers.ContainsKey(method)
End Function
Public Sub AddMethodWrapper(method As MethodSymbol, wrapper As MethodSymbol, body As BoundStatement)
If _methodWrappers Is Nothing Then
_methodWrappers = New Dictionary(Of MethodSymbol, MethodSymbol)()
End If
_methodWrappers(method) = wrapper
AddSynthesizedMethod(wrapper, body)
End Sub
Public Function GetMethodWrapper(method As MethodSymbol) As MethodSymbol
Dim wrapper As MethodSymbol = Nothing
Return If(_methodWrappers IsNot Nothing AndAlso _methodWrappers.TryGetValue(method, wrapper), wrapper, Nothing)
End Function
''' <summary> Free resources </summary>
Public Sub Free()
If Me._synthesizedMethods IsNot Nothing Then
Me._synthesizedMethods.Free()
Me._synthesizedMethods = Nothing
End If
If _methodWrappers IsNot Nothing Then
_methodWrappers = Nothing
End If
End Sub
Public Sub AddToInitializeComponentCallTree(method As MethodSymbol, callees As ImmutableArray(Of MethodSymbol))
#If DEBUG Then
Debug.Assert(method.IsDefinition)
For Each m In callees
Debug.Assert(m.IsDefinition)
Next
#End If
If _initializeComponentCallTree Is Nothing Then
_initializeComponentCallTree = New Dictionary(Of MethodSymbol, ImmutableArray(Of MethodSymbol))(ReferenceEqualityComparer.Instance)
End If
_initializeComponentCallTree.Add(method, callees)
End Sub
Public Function CallsInitializeComponent(method As MethodSymbol) As Boolean
Debug.Assert(method.IsDefinition)
If _initializeComponentCallTree Is Nothing Then
Return False
End If
Return CallsInitializeComponent(method, New HashSet(Of MethodSymbol)(ReferenceEqualityComparer.Instance))
End Function
Private Function CallsInitializeComponent(method As MethodSymbol, visited As HashSet(Of MethodSymbol)) As Boolean
Dim added = visited.Add(method)
Debug.Assert(added)
Dim callees As ImmutableArray(Of MethodSymbol) = Nothing
If _initializeComponentCallTree.TryGetValue(method, callees) Then
For Each m In callees
If m Is InitializeComponentOpt Then
Return True
ElseIf Not visited.Contains(m) AndAlso CallsInitializeComponent(m, visited) Then
Return True
End If
Next
End If
Return False
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Represents the state of compilation of one particular type.
''' This includes, for example, a collection of synthesized methods created during lowering.
''' WARNING: Note that the underlying collection classes are not thread-safe and this will
''' need to be revised if emit phase is changed to support multithreading when
''' translating a particular type.
''' </summary>
Friend Class TypeCompilationState
''' <summary> Method's information </summary>
Public Structure MethodWithBody
Public ReadOnly Method As MethodSymbol
Public ReadOnly Body As BoundStatement
Friend Sub New(_method As MethodSymbol, _body As BoundStatement)
Me.Method = _method
Me.Body = _body
End Sub
End Structure
Public ReadOnly Compilation As VisualBasicCompilation
Public staticLambdaFrame As LambdaFrame
' Can be Nothing if we're not emitting.
' During the lowering phase, however, it cannot be Nothing.
Public ReadOnly ModuleBuilderOpt As PEModuleBuilder
''' <summary> Flat array of created methods, non-empty if not-nothing </summary>
Private _synthesizedMethods As ArrayBuilder(Of MethodWithBody) = Nothing
Public ReadOnly InitializeComponentOpt As MethodSymbol
''' <summary>
''' A mapping from (source) iterator or async methods to the compiler-generated classes that implement them.
''' </summary>
Public ReadOnly StateMachineImplementationClass As New Dictionary(Of MethodSymbol, NamedTypeSymbol)(ReferenceEqualityComparer.Instance)
''' <summary>
''' Map of 'MyBase' or 'MyClass' call wrappers; actually each method symbol will
''' only need one wrapper to call it non-virtually;
'''
''' Indeed, if the type have a virtual method M1 overridden, MyBase.M1 will use
''' a wrapper for base type's method and MyClass.M1 a wrapper for this type's method.
'''
''' And if the type does not override a virtual method M1, both MyBase.M1
''' and MyClass.M1 will use a wrapper for base type's method.
''' </summary>
Private _methodWrappers As Dictionary(Of MethodSymbol, MethodSymbol) = Nothing
Private _initializeComponentCallTree As Dictionary(Of MethodSymbol, ImmutableArray(Of MethodSymbol)) = Nothing
Public Sub New(compilation As VisualBasicCompilation, moduleBuilderOpt As PEModuleBuilder, initializeComponentOpt As MethodSymbol)
Me.Compilation = compilation
Me.ModuleBuilderOpt = moduleBuilderOpt
Me.InitializeComponentOpt = initializeComponentOpt
End Sub
''' <summary>
''' Is there any content in the methods collection.
''' </summary>
Public ReadOnly Property HasSynthesizedMethods As Boolean
Get
Return _synthesizedMethods IsNot Nothing
End Get
End Property
''' <summary> Method created with their bodies </summary>
Public ReadOnly Property SynthesizedMethods As ArrayBuilder(Of MethodWithBody)
Get
Return _synthesizedMethods
End Get
End Property
Public Sub AddSynthesizedMethod(method As MethodSymbol, body As BoundStatement)
If _synthesizedMethods Is Nothing Then
_synthesizedMethods = ArrayBuilder(Of MethodWithBody).GetInstance()
End If
_synthesizedMethods.Add(New MethodWithBody(method, body))
End Sub
Public Function HasMethodWrapper(method As MethodSymbol) As Boolean
Return _methodWrappers IsNot Nothing AndAlso _methodWrappers.ContainsKey(method)
End Function
Public Sub AddMethodWrapper(method As MethodSymbol, wrapper As MethodSymbol, body As BoundStatement)
If _methodWrappers Is Nothing Then
_methodWrappers = New Dictionary(Of MethodSymbol, MethodSymbol)()
End If
_methodWrappers(method) = wrapper
AddSynthesizedMethod(wrapper, body)
End Sub
Public Function GetMethodWrapper(method As MethodSymbol) As MethodSymbol
Dim wrapper As MethodSymbol = Nothing
Return If(_methodWrappers IsNot Nothing AndAlso _methodWrappers.TryGetValue(method, wrapper), wrapper, Nothing)
End Function
''' <summary> Free resources </summary>
Public Sub Free()
If Me._synthesizedMethods IsNot Nothing Then
Me._synthesizedMethods.Free()
Me._synthesizedMethods = Nothing
End If
If _methodWrappers IsNot Nothing Then
_methodWrappers = Nothing
End If
End Sub
Public Sub AddToInitializeComponentCallTree(method As MethodSymbol, callees As ImmutableArray(Of MethodSymbol))
#If DEBUG Then
Debug.Assert(method.IsDefinition)
For Each m In callees
Debug.Assert(m.IsDefinition)
Next
#End If
If _initializeComponentCallTree Is Nothing Then
_initializeComponentCallTree = New Dictionary(Of MethodSymbol, ImmutableArray(Of MethodSymbol))(ReferenceEqualityComparer.Instance)
End If
_initializeComponentCallTree.Add(method, callees)
End Sub
Public Function CallsInitializeComponent(method As MethodSymbol) As Boolean
Debug.Assert(method.IsDefinition)
If _initializeComponentCallTree Is Nothing Then
Return False
End If
Return CallsInitializeComponent(method, New HashSet(Of MethodSymbol)(ReferenceEqualityComparer.Instance))
End Function
Private Function CallsInitializeComponent(method As MethodSymbol, visited As HashSet(Of MethodSymbol)) As Boolean
Dim added = visited.Add(method)
Debug.Assert(added)
Dim callees As ImmutableArray(Of MethodSymbol) = Nothing
If _initializeComponentCallTree.TryGetValue(method, callees) Then
For Each m In callees
If m Is InitializeComponentOpt Then
Return True
ElseIf Not visited.Contains(m) AndAlso CallsInitializeComponent(m, visited) Then
Return True
End If
Next
End If
Return False
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/IntegrationTest/TestUtilities/Helper.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using UIAutomationClient;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
public static class Helper
{
/// <summary>
/// A long timeout used to avoid hangs in tests, where a test failure manifests as an operation never occurring.
/// </summary>
public static readonly TimeSpan HangMitigatingTimeout = TimeSpan.FromMinutes(1);
private static IUIAutomation2? _automation;
public static IUIAutomation2 Automation
{
get
{
if (_automation == null)
{
Interlocked.CompareExchange(ref _automation, new CUIAutomation8(), null);
}
return _automation;
}
}
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// milliseconds, waiting 'delay' milliseconds after each retry. If a given retry returns a value
/// other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries in milliseconds</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? Retry<T>(Func<T> action, int delay)
=> Retry(action, TimeSpan.FromMilliseconds(delay));
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// milliseconds, waiting 'delay' milliseconds after each retry and will swallow all exceptions.
/// If a given retry returns a value other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries in milliseconds</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? RetryIgnoringExceptions<T>(Func<T> action, int delay)
=> RetryIgnoringExceptions(action, TimeSpan.FromMilliseconds(delay));
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// waiting for 'delay' time after each retry. If a given retry returns a value
/// other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? Retry<T>(Func<T> action, TimeSpan delay, int retryCount = -1)
{
return RetryHelper(() =>
{
try
{
return action();
}
catch (COMException)
{
// Devenv can throw COMExceptions if it's busy when we make DTE calls.
return default;
}
},
delay,
retryCount);
}
/// <summary>
/// This method will retry the asynchronous action represented by <paramref name="action"/>,
/// waiting for <paramref name="delay"/> time after each retry. If a given retry returns a value
/// other than the default value of <typeparamref name="T"/>, this value is returned.
/// </summary>
/// <param name="action">the asynchronous action to retry</param>
/// <param name="delay">the amount of time to wait between retries</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of <paramref name="action"/></returns>
public static Task<T?> RetryAsync<T>(Func<Task<T>> action, TimeSpan delay)
{
return RetryAsyncHelper(async () =>
{
try
{
return await action();
}
catch (COMException)
{
// Devenv can throw COMExceptions if it's busy when we make DTE calls.
return default;
}
},
delay);
}
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// milliseconds, waiting 'delay' milliseconds after each retry and will swallow all exceptions.
/// If a given retry returns a value other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries in milliseconds</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? RetryIgnoringExceptions<T>(Func<T> action, TimeSpan delay, int retryCount = -1)
{
return RetryHelper(() =>
{
try
{
return action();
}
catch (Exception)
{
return default;
}
},
delay,
retryCount);
}
private static T RetryHelper<T>(Func<T> action, TimeSpan delay, int retryCount)
{
for (var i = 0; true; i++)
{
var retval = action();
if (i == retryCount)
{
return retval;
}
if (!Equals(default(T), retval))
{
return retval;
}
Thread.Sleep(delay);
}
}
private static async Task<T> RetryAsyncHelper<T>(Func<Task<T>> action, TimeSpan delay)
{
while (true)
{
var retval = await action().ConfigureAwait(true);
if (!Equals(default(T), retval))
{
return retval;
}
await Task.Delay(delay).ConfigureAwait(true);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using UIAutomationClient;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
public static class Helper
{
/// <summary>
/// A long timeout used to avoid hangs in tests, where a test failure manifests as an operation never occurring.
/// </summary>
public static readonly TimeSpan HangMitigatingTimeout = TimeSpan.FromMinutes(1);
private static IUIAutomation2? _automation;
public static IUIAutomation2 Automation
{
get
{
if (_automation == null)
{
Interlocked.CompareExchange(ref _automation, new CUIAutomation8(), null);
}
return _automation;
}
}
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// milliseconds, waiting 'delay' milliseconds after each retry. If a given retry returns a value
/// other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries in milliseconds</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? Retry<T>(Func<T> action, int delay)
=> Retry(action, TimeSpan.FromMilliseconds(delay));
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// milliseconds, waiting 'delay' milliseconds after each retry and will swallow all exceptions.
/// If a given retry returns a value other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries in milliseconds</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? RetryIgnoringExceptions<T>(Func<T> action, int delay)
=> RetryIgnoringExceptions(action, TimeSpan.FromMilliseconds(delay));
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// waiting for 'delay' time after each retry. If a given retry returns a value
/// other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? Retry<T>(Func<T> action, TimeSpan delay, int retryCount = -1)
{
return RetryHelper(() =>
{
try
{
return action();
}
catch (COMException)
{
// Devenv can throw COMExceptions if it's busy when we make DTE calls.
return default;
}
},
delay,
retryCount);
}
/// <summary>
/// This method will retry the asynchronous action represented by <paramref name="action"/>,
/// waiting for <paramref name="delay"/> time after each retry. If a given retry returns a value
/// other than the default value of <typeparamref name="T"/>, this value is returned.
/// </summary>
/// <param name="action">the asynchronous action to retry</param>
/// <param name="delay">the amount of time to wait between retries</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of <paramref name="action"/></returns>
public static Task<T?> RetryAsync<T>(Func<Task<T>> action, TimeSpan delay)
{
return RetryAsyncHelper(async () =>
{
try
{
return await action();
}
catch (COMException)
{
// Devenv can throw COMExceptions if it's busy when we make DTE calls.
return default;
}
},
delay);
}
/// <summary>
/// This method will retry the action represented by the 'action' argument,
/// milliseconds, waiting 'delay' milliseconds after each retry and will swallow all exceptions.
/// If a given retry returns a value other than default(T), this value is returned.
/// </summary>
/// <param name="action">the action to retry</param>
/// <param name="delay">the amount of time to wait between retries in milliseconds</param>
/// <typeparam name="T">type of return value</typeparam>
/// <returns>the return value of 'action'</returns>
public static T? RetryIgnoringExceptions<T>(Func<T> action, TimeSpan delay, int retryCount = -1)
{
return RetryHelper(() =>
{
try
{
return action();
}
catch (Exception)
{
return default;
}
},
delay,
retryCount);
}
private static T RetryHelper<T>(Func<T> action, TimeSpan delay, int retryCount)
{
for (var i = 0; true; i++)
{
var retval = action();
if (i == retryCount)
{
return retval;
}
if (!Equals(default(T), retval))
{
return retval;
}
Thread.Sleep(delay);
}
}
private static async Task<T> RetryAsyncHelper<T>(Func<Task<T>> action, TimeSpan delay)
{
while (true)
{
var retval = await action().ConfigureAwait(true);
if (!Equals(default(T), retval))
{
return retval;
}
await Task.Delay(delay).ConfigureAwait(true);
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingEventSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
internal sealed class RetargetingEventSymbol : WrappedEventSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations;
private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized;
public RetargetingEventSymbol(RetargetingModuleSymbol retargetingModule, EventSymbol underlyingEvent)
: base(underlyingEvent)
{
RoslynDebug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingEvent is RetargetingEventSymbol));
_retargetingModule = retargetingModule;
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingEvent.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
}
public override MethodSymbol? AddMethod
{
get
{
return (object?)_underlyingEvent.AddMethod == null
? null
: this.RetargetingTranslator.Retarget(_underlyingEvent.AddMethod);
}
}
public override MethodSymbol? RemoveMethod
{
get
{
return (object?)_underlyingEvent.RemoveMethod == null
? null
: this.RetargetingTranslator.Retarget(_underlyingEvent.RemoveMethod);
}
}
internal override FieldSymbol? AssociatedField
{
get
{
return (object?)_underlyingEvent.AssociatedField == null
? null
: this.RetargetingTranslator.Retarget(_underlyingEvent.AssociatedField);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return _underlyingEvent.IsExplicitInterfaceImplementation; }
}
public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
this.RetargetExplicitInterfaceImplementations(),
default(ImmutableArray<EventSymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
private ImmutableArray<EventSymbol> RetargetExplicitInterfaceImplementations()
{
var impls = _underlyingEvent.ExplicitInterfaceImplementations;
if (impls.IsEmpty)
{
return impls;
}
// CONSIDER: we could skip the builder until the first time we see a different method after retargeting
var builder = ArrayBuilder<EventSymbol>.GetInstance();
for (int i = 0; i < impls.Length; i++)
{
var retargeted = this.RetargetingTranslator.Retarget(impls[i]);
if ((object?)retargeted != null)
{
builder.Add(retargeted);
}
}
return builder.ToImmutableAndFree();
}
public override Symbol? ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingEvent.ContainingSymbol);
}
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return _underlyingEvent.GetAttributes();
}
internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return this.RetargetingTranslator.RetargetAttributes(_underlyingEvent.GetCustomAttributesToEmit(moduleBuilder));
}
internal override bool MustCallMethodsDirectly
{
get
{
return _underlyingEvent.MustCallMethodsDirectly;
}
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
if (!_lazyCachedUseSiteInfo.IsInitialized)
{
AssemblySymbol primaryDependency = PrimaryDependency;
var result = new UseSiteInfo<AssemblySymbol>(primaryDependency);
CalculateUseSiteDiagnostic(ref result);
_lazyCachedUseSiteInfo.Initialize(primaryDependency, result);
}
return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency);
}
internal sealed override CSharpCompilation? DeclaringCompilation // perf, not correctness
{
get { return null; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
internal sealed class RetargetingEventSymbol : WrappedEventSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations;
private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized;
public RetargetingEventSymbol(RetargetingModuleSymbol retargetingModule, EventSymbol underlyingEvent)
: base(underlyingEvent)
{
RoslynDebug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingEvent is RetargetingEventSymbol));
_retargetingModule = retargetingModule;
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingEvent.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
}
public override MethodSymbol? AddMethod
{
get
{
return (object?)_underlyingEvent.AddMethod == null
? null
: this.RetargetingTranslator.Retarget(_underlyingEvent.AddMethod);
}
}
public override MethodSymbol? RemoveMethod
{
get
{
return (object?)_underlyingEvent.RemoveMethod == null
? null
: this.RetargetingTranslator.Retarget(_underlyingEvent.RemoveMethod);
}
}
internal override FieldSymbol? AssociatedField
{
get
{
return (object?)_underlyingEvent.AssociatedField == null
? null
: this.RetargetingTranslator.Retarget(_underlyingEvent.AssociatedField);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return _underlyingEvent.IsExplicitInterfaceImplementation; }
}
public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
this.RetargetExplicitInterfaceImplementations(),
default(ImmutableArray<EventSymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
private ImmutableArray<EventSymbol> RetargetExplicitInterfaceImplementations()
{
var impls = _underlyingEvent.ExplicitInterfaceImplementations;
if (impls.IsEmpty)
{
return impls;
}
// CONSIDER: we could skip the builder until the first time we see a different method after retargeting
var builder = ArrayBuilder<EventSymbol>.GetInstance();
for (int i = 0; i < impls.Length; i++)
{
var retargeted = this.RetargetingTranslator.Retarget(impls[i]);
if ((object?)retargeted != null)
{
builder.Add(retargeted);
}
}
return builder.ToImmutableAndFree();
}
public override Symbol? ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingEvent.ContainingSymbol);
}
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return _underlyingEvent.GetAttributes();
}
internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return this.RetargetingTranslator.RetargetAttributes(_underlyingEvent.GetCustomAttributesToEmit(moduleBuilder));
}
internal override bool MustCallMethodsDirectly
{
get
{
return _underlyingEvent.MustCallMethodsDirectly;
}
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
if (!_lazyCachedUseSiteInfo.IsInitialized)
{
AssemblySymbol primaryDependency = PrimaryDependency;
var result = new UseSiteInfo<AssemblySymbol>(primaryDependency);
CalculateUseSiteDiagnostic(ref result);
_lazyCachedUseSiteInfo.Initialize(primaryDependency, result);
}
return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency);
}
internal sealed override CSharpCompilation? DeclaringCompilation // perf, not correctness
{
get { return null; }
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/Portable/Text/SourceText.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// An abstraction of source text.
/// </summary>
public abstract class SourceText
{
private const int CharBufferSize = 32 * 1024;
private const int CharBufferCount = 5;
internal const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB
private static readonly ObjectPool<char[]> s_charArrayPool = new ObjectPool<char[]>(() => new char[CharBufferSize], CharBufferCount);
private readonly SourceHashAlgorithm _checksumAlgorithm;
private SourceTextContainer? _lazyContainer;
private TextLineCollection? _lazyLineInfo;
private ImmutableArray<byte> _lazyChecksum;
private ImmutableArray<byte> _precomputedEmbeddedTextBlob;
private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);
protected SourceText(ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, SourceTextContainer? container = null)
{
ValidateChecksumAlgorithm(checksumAlgorithm);
if (!checksum.IsDefault && checksum.Length != CryptographicHashProvider.GetHashSize(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.InvalidHash, nameof(checksum));
}
_checksumAlgorithm = checksumAlgorithm;
_lazyChecksum = checksum;
_lazyContainer = container;
}
internal SourceText(ImmutableArray<byte> checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray<byte> embeddedTextBlob)
: this(checksum, checksumAlgorithm, container: null)
{
// We should never have precomputed the embedded text blob without precomputing the checksum.
Debug.Assert(embeddedTextBlob.IsDefault || !checksum.IsDefault);
if (!checksum.IsDefault && embeddedTextBlob.IsDefault)
{
// We can't compute the embedded text blob lazily if we're given a precomputed checksum.
// This happens when source bytes/stream were given, but canBeEmbedded=true was not passed.
_precomputedEmbeddedTextBlob = ImmutableArray<byte>.Empty;
}
else
{
_precomputedEmbeddedTextBlob = embeddedTextBlob;
}
}
internal static void ValidateChecksumAlgorithm(SourceHashAlgorithm checksumAlgorithm)
{
if (!SourceHashAlgorithms.IsSupportedAlgorithm(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.UnsupportedHashAlgorithm, nameof(checksumAlgorithm));
}
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="text">Text.</param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="text"/> was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// If the encoding is not specified the resulting <see cref="SourceText"/> isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="text"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(string text, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
return new StringText(text, encoding, checksumAlgorithm: checksumAlgorithm);
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="reader">TextReader</param>
/// <param name="length">length of content from <paramref name="reader"/></param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="reader"/> was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// If the encoding is not specified the resulting <see cref="SourceText"/> isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(
TextReader reader,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (length >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(reader, length, encoding, checksumAlgorithm);
}
string text = reader.ReadToEnd();
return From(text, encoding, checksumAlgorithm);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(Stream stream, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from stream content.
/// </summary>
/// <param name="stream">Stream. The stream must be seekable.</param>
/// <param name="encoding">
/// Data encoding to use if the stream doesn't start with Byte Order Mark specifying the encoding.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> doesn't support reading or seeking.
/// <paramref name="checksumAlgorithm"/> is not supported.
/// </exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <remarks>Reads from the beginning of the stream. Leaves the stream open.</remarks>
public static SourceText From(
Stream stream,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(stream));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
encoding = encoding ?? s_utf8EncodingWithNoBOM;
if (stream.CanSeek)
{
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (encoding.GetMaxCharCountOrThrowIfHuge(stream) >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
}
}
string text = Decode(stream, encoding, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(stream, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(byte[] buffer, int length, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(buffer, length, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from a byte array.
/// </summary>
/// <param name="buffer">The encoded source buffer.</param>
/// <param name="length">The number of bytes to read from the buffer.</param>
/// <param name="encoding">
/// Data encoding to use if the encoded buffer doesn't start with Byte Order Mark.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <returns>The decoded text.</returns>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException">The <paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="length"/> is negative or longer than the <paramref name="buffer"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
public static SourceText From(
byte[] buffer,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (length < 0 || length > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
string text = Decode(buffer, length, encoding ?? s_utf8EncodingWithNoBOM, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(buffer, 0, length, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(new ArraySegment<byte>(buffer, 0, length)) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
/// <summary>
/// Decode text from a stream.
/// </summary>
/// <param name="stream">The stream containing encoded text.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(Stream stream, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(stream != null);
RoslynDebug.Assert(encoding != null);
const int maxBufferSize = 4096;
int bufferSize = maxBufferSize;
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
int length = (int)stream.Length;
if (length == 0)
{
actualEncoding = encoding;
return string.Empty;
}
bufferSize = Math.Min(maxBufferSize, length);
}
// Note: We are setting the buffer size to 4KB instead of the default 1KB. That's
// because we can reach this code path for FileStreams and, to avoid FileStream
// buffer allocations for small files, we may intentionally be using a FileStream
// with a very small (1 byte) buffer. Using 4KB here matches the default buffer
// size for FileStream and means we'll still be doing file I/O in 4KB chunks.
using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: bufferSize, leaveOpen: true))
{
string text = reader.ReadToEnd();
actualEncoding = reader.CurrentEncoding;
return text;
}
}
/// <summary>
/// Decode text from a byte array.
/// </summary>
/// <param name="buffer">The byte array containing encoded text.</param>
/// <param name="length">The count of valid bytes in <paramref name="buffer"/>.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(byte[] buffer, int length, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(buffer != null);
RoslynDebug.Assert(encoding != null);
int preambleLength;
actualEncoding = TryReadByteOrderMark(buffer, length, out preambleLength) ?? encoding;
return actualEncoding.GetString(buffer, preambleLength, length - preambleLength);
}
/// <summary>
/// Check for occurrence of two consecutive NUL (U+0000) characters.
/// This is unlikely to appear in genuine text, so it's a good heuristic
/// to detect binary files.
/// </summary>
/// <remarks>
/// internal for unit testing
/// </remarks>
internal static bool IsBinary(string text)
{
// PERF: We can advance two chars at a time unless we find a NUL.
for (int i = 1; i < text.Length;)
{
if (text[i] == '\0')
{
if (text[i - 1] == '\0')
{
return true;
}
i += 1;
}
else
{
i += 2;
}
}
return false;
}
/// <summary>
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </summary>
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
/// <summary>
/// Encoding of the file that the text was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// </summary>
/// <remarks>
/// If the encoding is not specified the source isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </remarks>
public abstract Encoding? Encoding { get; }
/// <summary>
/// The length of the text in characters.
/// </summary>
public abstract int Length { get; }
/// <summary>
/// The size of the storage representation of the text (in characters).
/// This can differ from length when storage buffers are reused to represent fragments/subtext.
/// </summary>
internal virtual int StorageSize
{
get { return this.Length; }
}
internal virtual ImmutableArray<SourceText> Segments
{
get { return ImmutableArray<SourceText>.Empty; }
}
internal virtual SourceText StorageKey
{
get { return this; }
}
/// <summary>
/// Indicates whether this source text can be embedded in the PDB.
/// </summary>
/// <remarks>
/// If this text was constructed via <see cref="From(byte[], int, Encoding, SourceHashAlgorithm, bool, bool)"/> or
/// <see cref="From(Stream, Encoding, SourceHashAlgorithm, bool, bool)"/>, then the canBeEmbedded arg must have
/// been true.
///
/// Otherwise, <see cref="Encoding" /> must be non-null.
/// </remarks>
public bool CanBeEmbedded
{
get
{
if (_precomputedEmbeddedTextBlob.IsDefault)
{
// If we didn't precompute the embedded text blob from bytes/stream,
// we can only support embedding if we have an encoding with which
// to encode the text in the PDB.
return Encoding != null;
}
// We use a sentinel empty blob to indicate that embedding has been disallowed.
return !_precomputedEmbeddedTextBlob.IsEmpty;
}
}
/// <summary>
/// If the text was created from a stream or byte[] and canBeEmbedded argument was true,
/// this provides the embedded text blob that was precomputed using the original stream
/// or byte[]. The precomputation was required in that case so that the bytes written to
/// the PDB match the original bytes exactly (and match the checksum of the original
/// bytes).
/// </summary>
internal ImmutableArray<byte> PrecomputedEmbeddedTextBlob => _precomputedEmbeddedTextBlob;
/// <summary>
/// Returns a character at given position.
/// </summary>
/// <param name="position">The position to get the character from.</param>
/// <returns>The character.</returns>
/// <exception cref="ArgumentOutOfRangeException">When position is negative or
/// greater than <see cref="Length"/>.</exception>
public abstract char this[int position] { get; }
/// <summary>
/// Copy a range of characters from this SourceText to a destination array.
/// </summary>
public abstract void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
/// <summary>
/// The container of this <see cref="SourceText"/>.
/// </summary>
public virtual SourceTextContainer Container
{
get
{
if (_lazyContainer == null)
{
Interlocked.CompareExchange(ref _lazyContainer, new StaticContainer(this), null);
}
return _lazyContainer;
}
}
internal void CheckSubSpan(TextSpan span)
{
Debug.Assert(0 <= span.Start && span.Start <= span.End);
if (span.End > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(span));
}
}
/// <summary>
/// Gets a <see cref="SourceText"/> that contains the characters in the specified span of this text.
/// </summary>
public virtual SourceText GetSubText(TextSpan span)
{
CheckSubSpan(span);
int spanLength = span.Length;
if (spanLength == 0)
{
return SourceText.From(string.Empty, this.Encoding, this.ChecksumAlgorithm);
}
else if (spanLength == this.Length && span.Start == 0)
{
return this;
}
else
{
return new SubText(this, span);
}
}
/// <summary>
/// Returns a <see cref="SourceText"/> that has the contents of this text including and after the start position.
/// </summary>
public SourceText GetSubText(int start)
{
if (start < 0 || start > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (start == 0)
{
return this;
}
else
{
return this.GetSubText(new TextSpan(start, this.Length - start));
}
}
/// <summary>
/// Write this <see cref="SourceText"/> to a text writer.
/// </summary>
public void Write(TextWriter textWriter, CancellationToken cancellationToken = default(CancellationToken))
{
this.Write(textWriter, new TextSpan(0, this.Length), cancellationToken);
}
/// <summary>
/// Write a span of text to a text writer.
/// </summary>
public virtual void Write(TextWriter writer, TextSpan span, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSubSpan(span);
var buffer = s_charArrayPool.Allocate();
try
{
int offset = span.Start;
int end = span.End;
while (offset < end)
{
cancellationToken.ThrowIfCancellationRequested();
int count = Math.Min(buffer.Length, end - offset);
this.CopyTo(offset, buffer, 0, count);
writer.Write(buffer, 0, count);
offset += count;
}
}
finally
{
s_charArrayPool.Free(buffer);
}
}
public ImmutableArray<byte> GetChecksum()
{
if (_lazyChecksum.IsDefault)
{
using (var stream = new SourceTextStream(this, useDefaultEncodingIfNull: true))
{
ImmutableInterlocked.InterlockedInitialize(ref _lazyChecksum, CalculateChecksum(stream, _checksumAlgorithm));
}
}
return _lazyChecksum;
}
internal static ImmutableArray<byte> CalculateChecksum(byte[] buffer, int offset, int count, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
return ImmutableArray.Create(algorithm.ComputeHash(buffer, offset, count));
}
}
internal static ImmutableArray<byte> CalculateChecksum(Stream stream, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
return ImmutableArray.Create(algorithm.ComputeHash(stream));
}
}
/// <summary>
/// Provides a string representation of the SourceText.
/// </summary>
public override string ToString()
{
return ToString(new TextSpan(0, this.Length));
}
/// <summary>
/// Gets a string containing the characters in specified span.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception>
public virtual string ToString(TextSpan span)
{
CheckSubSpan(span);
// default implementation constructs text using CopyTo
var builder = new StringBuilder();
var buffer = new char[Math.Min(span.Length, 1024)];
int position = Math.Max(Math.Min(span.Start, this.Length), 0);
int length = Math.Min(span.End, this.Length) - position;
while (position < this.Length && length > 0)
{
int copyLength = Math.Min(buffer.Length, length);
this.CopyTo(position, buffer, 0, copyLength);
builder.Append(buffer, 0, copyLength);
length -= copyLength;
position += copyLength;
}
return builder.ToString();
}
#region Changes
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// </summary>
public virtual SourceText WithChanges(IEnumerable<TextChange> changes)
{
if (changes == null)
{
throw new ArgumentNullException(nameof(changes));
}
if (!changes.Any())
{
return this;
}
var segments = ArrayBuilder<SourceText>.GetInstance();
var changeRanges = ArrayBuilder<TextChangeRange>.GetInstance();
try
{
int position = 0;
foreach (var change in changes)
{
if (change.Span.End > this.Length)
throw new ArgumentException(CodeAnalysisResources.ChangesMustBeWithinBoundsOfSourceText, nameof(changes));
// there can be no overlapping changes
if (change.Span.Start < position)
{
// Handle the case of unordered changes by sorting the input and retrying. This is inefficient, but
// downstream consumers have been known to hit this case in the past and we want to avoid crashes.
// https://github.com/dotnet/roslyn/pull/26339
if (change.Span.End <= changeRanges.Last().Span.Start)
{
changes = (from c in changes
where !c.Span.IsEmpty || c.NewText?.Length > 0
orderby c.Span
select c).ToList();
return WithChanges(changes);
}
throw new ArgumentException(CodeAnalysisResources.ChangesMustNotOverlap, nameof(changes));
}
var newTextLength = change.NewText?.Length ?? 0;
// ignore changes that don't change anything
if (change.Span.Length == 0 && newTextLength == 0)
continue;
// if we've skipped a range, add
if (change.Span.Start > position)
{
var subText = this.GetSubText(new TextSpan(position, change.Span.Start - position));
CompositeText.AddSegments(segments, subText);
}
if (newTextLength > 0)
{
var segment = SourceText.From(change.NewText!, this.Encoding, this.ChecksumAlgorithm);
CompositeText.AddSegments(segments, segment);
}
position = change.Span.End;
changeRanges.Add(new TextChangeRange(change.Span, newTextLength));
}
// no changes actually happened?
if (position == 0 && segments.Count == 0)
{
return this;
}
if (position < this.Length)
{
var subText = this.GetSubText(new TextSpan(position, this.Length - position));
CompositeText.AddSegments(segments, subText);
}
var newText = CompositeText.ToSourceText(segments, this, adjustSegments: true);
if (newText != this)
{
return new ChangedText(this, newText, changeRanges.ToImmutable());
}
else
{
return this;
}
}
finally
{
segments.Free();
changeRanges.Free();
}
}
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// <exception cref="ArgumentException">If any changes are not in bounds of this <see cref="SourceText"/>.</exception>
/// <exception cref="ArgumentException">If any changes overlap other changes.</exception>
/// </summary>
/// <remarks>
/// Changes do not have to be in sorted order. However, <see cref="WithChanges(IEnumerable{TextChange})"/> will
/// perform better if they are.
/// </remarks>
public SourceText WithChanges(params TextChange[] changes)
{
return this.WithChanges((IEnumerable<TextChange>)changes);
}
/// <summary>
/// Returns a new SourceText with the specified span of characters replaced by the new text.
/// </summary>
public SourceText Replace(TextSpan span, string newText)
{
return this.WithChanges(new TextChange(span, newText));
}
/// <summary>
/// Returns a new SourceText with the specified range of characters replaced by the new text.
/// </summary>
public SourceText Replace(int start, int length, string newText)
{
return this.Replace(new TextSpan(start, length), newText);
}
/// <summary>
/// Gets the set of <see cref="TextChangeRange"/> that describe how the text changed
/// between this text an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChangeRange> GetChangeRanges(SourceText oldText)
{
if (oldText == null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (oldText == this)
{
return TextChangeRange.NoChanges;
}
else
{
return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), this.Length));
}
}
/// <summary>
/// Gets the set of <see cref="TextChange"/> that describe how the text changed
/// between this text and an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChange> GetTextChanges(SourceText oldText)
{
int newPosDelta = 0;
var ranges = this.GetChangeRanges(oldText).ToList();
var textChanges = new List<TextChange>(ranges.Count);
foreach (var range in ranges)
{
var newPos = range.Span.Start + newPosDelta;
// determine where in the newText this text exists
string newt;
if (range.NewLength > 0)
{
var span = new TextSpan(newPos, range.NewLength);
newt = this.ToString(span);
}
else
{
newt = string.Empty;
}
textChanges.Add(new TextChange(range.Span, newt));
newPosDelta += range.NewLength - range.Span.Length;
}
return textChanges.ToImmutableArrayOrEmpty();
}
#endregion
#region Lines
/// <summary>
/// The collection of individual text lines.
/// </summary>
public TextLineCollection Lines
{
get
{
var info = _lazyLineInfo;
return info ?? Interlocked.CompareExchange(ref _lazyLineInfo, info = GetLinesCore(), null) ?? info;
}
}
internal bool TryGetLines([NotNullWhen(returnValue: true)] out TextLineCollection? lines)
{
lines = _lazyLineInfo;
return lines != null;
}
/// <summary>
/// Called from <see cref="Lines"/> to initialize the <see cref="TextLineCollection"/>. Thereafter,
/// the collection is cached.
/// </summary>
/// <returns>A new <see cref="TextLineCollection"/> representing the individual text lines.</returns>
protected virtual TextLineCollection GetLinesCore()
{
return new LineInfo(this, ParseLineStarts());
}
internal sealed class LineInfo : TextLineCollection
{
private readonly SourceText _text;
private readonly int[] _lineStarts;
private int _lastLineNumber;
public LineInfo(SourceText text, int[] lineStarts)
{
_text = text;
_lineStarts = lineStarts;
}
public override int Count => _lineStarts.Length;
public override TextLine this[int index]
{
get
{
if (index < 0 || index >= _lineStarts.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
int start = _lineStarts[index];
if (index == _lineStarts.Length - 1)
{
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, _text.Length));
}
else
{
int end = _lineStarts[index + 1];
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, end));
}
}
}
public override int IndexOf(int position)
{
if (position < 0 || position > _text.Length)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
int lineNumber;
// it is common to ask about position on the same line
// as before or on the next couple lines
var lastLineNumber = _lastLineNumber;
if (position >= _lineStarts[lastLineNumber])
{
var limit = Math.Min(_lineStarts.Length, lastLineNumber + 4);
for (int i = lastLineNumber; i < limit; i++)
{
if (position < _lineStarts[i])
{
lineNumber = i - 1;
_lastLineNumber = lineNumber;
return lineNumber;
}
}
}
// Binary search to find the right line
// if no lines start exactly at position, round to the left
// EoF position will map to the last line.
lineNumber = _lineStarts.BinarySearch(position);
if (lineNumber < 0)
{
lineNumber = (~lineNumber) - 1;
}
_lastLineNumber = lineNumber;
return lineNumber;
}
public override TextLine GetLineFromPosition(int position)
{
return this[IndexOf(position)];
}
}
private void EnumerateChars(Action<int, char[], int> action)
{
var position = 0;
var buffer = s_charArrayPool.Allocate();
var length = this.Length;
while (position < length)
{
var contentLength = Math.Min(length - position, buffer.Length);
this.CopyTo(position, buffer, 0, contentLength);
action(position, buffer, contentLength);
position += contentLength;
}
// once more with zero length to signal the end
action(position, buffer, 0);
s_charArrayPool.Free(buffer);
}
private int[] ParseLineStarts()
{
// Corner case check
if (0 == this.Length)
{
return new[] { 0 };
}
var lineStarts = ArrayBuilder<int>.GetInstance();
lineStarts.Add(0); // there is always the first line
var lastWasCR = false;
// The following loop goes through every character in the text. It is highly
// performance critical, and thus inlines knowledge about common line breaks
// and non-line breaks.
EnumerateChars((int position, char[] buffer, int length) =>
{
var index = 0;
if (lastWasCR)
{
if (length > 0 && buffer[0] == '\n')
{
index++;
}
lineStarts.Add(position + index);
lastWasCR = false;
}
while (index < length)
{
char c = buffer[index];
index++;
// Common case - ASCII & not a line break
// if (c > '\r' && c <= 127)
// if (c >= ('\r'+1) && c <= 127)
const uint bias = '\r' + 1;
if (unchecked(c - bias) <= (127 - bias))
{
continue;
}
// Assumes that the only 2-char line break sequence is CR+LF
if (c == '\r')
{
if (index < length && buffer[index] == '\n')
{
index++;
}
else if (index >= length)
{
lastWasCR = true;
continue;
}
}
else if (!TextUtilities.IsAnyLineBreakCharacter(c))
{
continue;
}
// next line starts at index
lineStarts.Add(position + index);
}
});
return lineStarts.ToArrayAndFree();
}
#endregion
/// <summary>
/// Compares the content with content of another <see cref="SourceText"/>.
/// </summary>
public bool ContentEquals(SourceText other)
{
if (ReferenceEquals(this, other))
{
return true;
}
// Checksum may be provided by a subclass, which is thus responsible for passing us a true hash.
ImmutableArray<byte> leftChecksum = _lazyChecksum;
ImmutableArray<byte> rightChecksum = other._lazyChecksum;
if (!leftChecksum.IsDefault && !rightChecksum.IsDefault && this.Encoding == other.Encoding && this.ChecksumAlgorithm == other.ChecksumAlgorithm)
{
return leftChecksum.SequenceEqual(rightChecksum);
}
return ContentEqualsImpl(other);
}
/// <summary>
/// Implements equality comparison of the content of two different instances of <see cref="SourceText"/>.
/// </summary>
protected virtual bool ContentEqualsImpl(SourceText other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (this.Length != other.Length)
{
return false;
}
var buffer1 = s_charArrayPool.Allocate();
var buffer2 = s_charArrayPool.Allocate();
try
{
int position = 0;
while (position < this.Length)
{
int n = Math.Min(this.Length - position, buffer1.Length);
this.CopyTo(position, buffer1, 0, n);
other.CopyTo(position, buffer2, 0, n);
for (int i = 0; i < n; i++)
{
if (buffer1[i] != buffer2[i])
{
return false;
}
}
position += n;
}
return true;
}
finally
{
s_charArrayPool.Free(buffer2);
s_charArrayPool.Free(buffer1);
}
}
/// <summary>
/// Detect an encoding by looking for byte order marks.
/// </summary>
/// <param name="source">A buffer containing the encoded text.</param>
/// <param name="length">The length of valid data in the buffer.</param>
/// <param name="preambleLength">The length of any detected byte order marks.</param>
/// <returns>The detected encoding or null if no recognized byte order mark was present.</returns>
internal static Encoding? TryReadByteOrderMark(byte[] source, int length, out int preambleLength)
{
RoslynDebug.Assert(source != null);
Debug.Assert(length <= source.Length);
if (length >= 2)
{
switch (source[0])
{
case 0xFE:
if (source[1] == 0xFF)
{
preambleLength = 2;
return Encoding.BigEndianUnicode;
}
break;
case 0xFF:
if (source[1] == 0xFE)
{
preambleLength = 2;
return Encoding.Unicode;
}
break;
case 0xEF:
if (source[1] == 0xBB && length >= 3 && source[2] == 0xBF)
{
preambleLength = 3;
return Encoding.UTF8;
}
break;
}
}
preambleLength = 0;
return null;
}
private class StaticContainer : SourceTextContainer
{
private readonly SourceText _text;
public StaticContainer(SourceText text)
{
_text = text;
}
public override SourceText CurrentText => _text;
public override event EventHandler<TextChangeEventArgs> TextChanged
{
add
{
// do nothing
}
remove
{
// do nothing
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// An abstraction of source text.
/// </summary>
public abstract class SourceText
{
private const int CharBufferSize = 32 * 1024;
private const int CharBufferCount = 5;
internal const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB
private static readonly ObjectPool<char[]> s_charArrayPool = new ObjectPool<char[]>(() => new char[CharBufferSize], CharBufferCount);
private readonly SourceHashAlgorithm _checksumAlgorithm;
private SourceTextContainer? _lazyContainer;
private TextLineCollection? _lazyLineInfo;
private ImmutableArray<byte> _lazyChecksum;
private ImmutableArray<byte> _precomputedEmbeddedTextBlob;
private static readonly Encoding s_utf8EncodingWithNoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);
protected SourceText(ImmutableArray<byte> checksum = default(ImmutableArray<byte>), SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, SourceTextContainer? container = null)
{
ValidateChecksumAlgorithm(checksumAlgorithm);
if (!checksum.IsDefault && checksum.Length != CryptographicHashProvider.GetHashSize(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.InvalidHash, nameof(checksum));
}
_checksumAlgorithm = checksumAlgorithm;
_lazyChecksum = checksum;
_lazyContainer = container;
}
internal SourceText(ImmutableArray<byte> checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray<byte> embeddedTextBlob)
: this(checksum, checksumAlgorithm, container: null)
{
// We should never have precomputed the embedded text blob without precomputing the checksum.
Debug.Assert(embeddedTextBlob.IsDefault || !checksum.IsDefault);
if (!checksum.IsDefault && embeddedTextBlob.IsDefault)
{
// We can't compute the embedded text blob lazily if we're given a precomputed checksum.
// This happens when source bytes/stream were given, but canBeEmbedded=true was not passed.
_precomputedEmbeddedTextBlob = ImmutableArray<byte>.Empty;
}
else
{
_precomputedEmbeddedTextBlob = embeddedTextBlob;
}
}
internal static void ValidateChecksumAlgorithm(SourceHashAlgorithm checksumAlgorithm)
{
if (!SourceHashAlgorithms.IsSupportedAlgorithm(checksumAlgorithm))
{
throw new ArgumentException(CodeAnalysisResources.UnsupportedHashAlgorithm, nameof(checksumAlgorithm));
}
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="text">Text.</param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="text"/> was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// If the encoding is not specified the resulting <see cref="SourceText"/> isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="text"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(string text, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
return new StringText(text, encoding, checksumAlgorithm: checksumAlgorithm);
}
/// <summary>
/// Constructs a <see cref="SourceText"/> from text in a string.
/// </summary>
/// <param name="reader">TextReader</param>
/// <param name="length">length of content from <paramref name="reader"/></param>
/// <param name="encoding">
/// Encoding of the file that the <paramref name="reader"/> was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// If the encoding is not specified the resulting <see cref="SourceText"/> isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
public static SourceText From(
TextReader reader,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (length >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(reader, length, encoding, checksumAlgorithm);
}
string text = reader.ReadToEnd();
return From(text, encoding, checksumAlgorithm);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(Stream stream, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from stream content.
/// </summary>
/// <param name="stream">Stream. The stream must be seekable.</param>
/// <param name="encoding">
/// Data encoding to use if the stream doesn't start with Byte Order Mark specifying the encoding.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="stream"/> doesn't support reading or seeking.
/// <paramref name="checksumAlgorithm"/> is not supported.
/// </exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <remarks>Reads from the beginning of the stream. Leaves the stream open.</remarks>
public static SourceText From(
Stream stream,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(stream));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
encoding = encoding ?? s_utf8EncodingWithNoBOM;
if (stream.CanSeek)
{
// If the resulting string would end up on the large object heap, then use LargeEncodedText.
if (encoding.GetMaxCharCountOrThrowIfHuge(stream) >= LargeObjectHeapLimitInChars)
{
return LargeText.Decode(stream, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
}
}
string text = Decode(stream, encoding, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(stream, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
// 1.0 BACKCOMPAT OVERLOAD - DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static SourceText From(byte[] buffer, int length, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
=> From(buffer, length, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded: false);
/// <summary>
/// Constructs a <see cref="SourceText"/> from a byte array.
/// </summary>
/// <param name="buffer">The encoded source buffer.</param>
/// <param name="length">The number of bytes to read from the buffer.</param>
/// <param name="encoding">
/// Data encoding to use if the encoded buffer doesn't start with Byte Order Mark.
/// <see cref="Encoding.UTF8"/> if not specified.
/// </param>
/// <param name="checksumAlgorithm">
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </param>
/// <param name="throwIfBinaryDetected">If the decoded text contains at least two consecutive NUL
/// characters, then an <see cref="InvalidDataException"/> is thrown.</param>
/// <returns>The decoded text.</returns>
/// <param name="canBeEmbedded">True if the text can be passed to <see cref="EmbeddedText.FromSource"/> and be embedded in a PDB.</param>
/// <exception cref="ArgumentNullException">The <paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="length"/> is negative or longer than the <paramref name="buffer"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="checksumAlgorithm"/> is not supported.</exception>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
/// <exception cref="InvalidDataException">Two consecutive NUL characters were detected in the decoded text and <paramref name="throwIfBinaryDetected"/> was true.</exception>
public static SourceText From(
byte[] buffer,
int length,
Encoding? encoding = null,
SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1,
bool throwIfBinaryDetected = false,
bool canBeEmbedded = false)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (length < 0 || length > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
ValidateChecksumAlgorithm(checksumAlgorithm);
string text = Decode(buffer, length, encoding ?? s_utf8EncodingWithNoBOM, out encoding);
if (throwIfBinaryDetected && IsBinary(text))
{
throw new InvalidDataException();
}
// We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
// We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
var checksum = CalculateChecksum(buffer, 0, length, checksumAlgorithm);
var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(new ArraySegment<byte>(buffer, 0, length)) : default(ImmutableArray<byte>);
return new StringText(text, encoding, checksum, checksumAlgorithm, embeddedTextBlob);
}
/// <summary>
/// Decode text from a stream.
/// </summary>
/// <param name="stream">The stream containing encoded text.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(Stream stream, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(stream != null);
RoslynDebug.Assert(encoding != null);
const int maxBufferSize = 4096;
int bufferSize = maxBufferSize;
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
int length = (int)stream.Length;
if (length == 0)
{
actualEncoding = encoding;
return string.Empty;
}
bufferSize = Math.Min(maxBufferSize, length);
}
// Note: We are setting the buffer size to 4KB instead of the default 1KB. That's
// because we can reach this code path for FileStreams and, to avoid FileStream
// buffer allocations for small files, we may intentionally be using a FileStream
// with a very small (1 byte) buffer. Using 4KB here matches the default buffer
// size for FileStream and means we'll still be doing file I/O in 4KB chunks.
using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: bufferSize, leaveOpen: true))
{
string text = reader.ReadToEnd();
actualEncoding = reader.CurrentEncoding;
return text;
}
}
/// <summary>
/// Decode text from a byte array.
/// </summary>
/// <param name="buffer">The byte array containing encoded text.</param>
/// <param name="length">The count of valid bytes in <paramref name="buffer"/>.</param>
/// <param name="encoding">The encoding to use if an encoding cannot be determined from the byte order mark.</param>
/// <param name="actualEncoding">The actual encoding used.</param>
/// <returns>The decoded text.</returns>
/// <exception cref="DecoderFallbackException">If the given encoding is set to use a throwing decoder as a fallback</exception>
private static string Decode(byte[] buffer, int length, Encoding encoding, out Encoding actualEncoding)
{
RoslynDebug.Assert(buffer != null);
RoslynDebug.Assert(encoding != null);
int preambleLength;
actualEncoding = TryReadByteOrderMark(buffer, length, out preambleLength) ?? encoding;
return actualEncoding.GetString(buffer, preambleLength, length - preambleLength);
}
/// <summary>
/// Check for occurrence of two consecutive NUL (U+0000) characters.
/// This is unlikely to appear in genuine text, so it's a good heuristic
/// to detect binary files.
/// </summary>
/// <remarks>
/// internal for unit testing
/// </remarks>
internal static bool IsBinary(string text)
{
// PERF: We can advance two chars at a time unless we find a NUL.
for (int i = 1; i < text.Length;)
{
if (text[i] == '\0')
{
if (text[i - 1] == '\0')
{
return true;
}
i += 1;
}
else
{
i += 2;
}
}
return false;
}
/// <summary>
/// Hash algorithm to use to calculate checksum of the text that's saved to PDB.
/// </summary>
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
/// <summary>
/// Encoding of the file that the text was read from or is going to be saved to.
/// <c>null</c> if the encoding is unspecified.
/// </summary>
/// <remarks>
/// If the encoding is not specified the source isn't debuggable.
/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
/// </remarks>
public abstract Encoding? Encoding { get; }
/// <summary>
/// The length of the text in characters.
/// </summary>
public abstract int Length { get; }
/// <summary>
/// The size of the storage representation of the text (in characters).
/// This can differ from length when storage buffers are reused to represent fragments/subtext.
/// </summary>
internal virtual int StorageSize
{
get { return this.Length; }
}
internal virtual ImmutableArray<SourceText> Segments
{
get { return ImmutableArray<SourceText>.Empty; }
}
internal virtual SourceText StorageKey
{
get { return this; }
}
/// <summary>
/// Indicates whether this source text can be embedded in the PDB.
/// </summary>
/// <remarks>
/// If this text was constructed via <see cref="From(byte[], int, Encoding, SourceHashAlgorithm, bool, bool)"/> or
/// <see cref="From(Stream, Encoding, SourceHashAlgorithm, bool, bool)"/>, then the canBeEmbedded arg must have
/// been true.
///
/// Otherwise, <see cref="Encoding" /> must be non-null.
/// </remarks>
public bool CanBeEmbedded
{
get
{
if (_precomputedEmbeddedTextBlob.IsDefault)
{
// If we didn't precompute the embedded text blob from bytes/stream,
// we can only support embedding if we have an encoding with which
// to encode the text in the PDB.
return Encoding != null;
}
// We use a sentinel empty blob to indicate that embedding has been disallowed.
return !_precomputedEmbeddedTextBlob.IsEmpty;
}
}
/// <summary>
/// If the text was created from a stream or byte[] and canBeEmbedded argument was true,
/// this provides the embedded text blob that was precomputed using the original stream
/// or byte[]. The precomputation was required in that case so that the bytes written to
/// the PDB match the original bytes exactly (and match the checksum of the original
/// bytes).
/// </summary>
internal ImmutableArray<byte> PrecomputedEmbeddedTextBlob => _precomputedEmbeddedTextBlob;
/// <summary>
/// Returns a character at given position.
/// </summary>
/// <param name="position">The position to get the character from.</param>
/// <returns>The character.</returns>
/// <exception cref="ArgumentOutOfRangeException">When position is negative or
/// greater than <see cref="Length"/>.</exception>
public abstract char this[int position] { get; }
/// <summary>
/// Copy a range of characters from this SourceText to a destination array.
/// </summary>
public abstract void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
/// <summary>
/// The container of this <see cref="SourceText"/>.
/// </summary>
public virtual SourceTextContainer Container
{
get
{
if (_lazyContainer == null)
{
Interlocked.CompareExchange(ref _lazyContainer, new StaticContainer(this), null);
}
return _lazyContainer;
}
}
internal void CheckSubSpan(TextSpan span)
{
Debug.Assert(0 <= span.Start && span.Start <= span.End);
if (span.End > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(span));
}
}
/// <summary>
/// Gets a <see cref="SourceText"/> that contains the characters in the specified span of this text.
/// </summary>
public virtual SourceText GetSubText(TextSpan span)
{
CheckSubSpan(span);
int spanLength = span.Length;
if (spanLength == 0)
{
return SourceText.From(string.Empty, this.Encoding, this.ChecksumAlgorithm);
}
else if (spanLength == this.Length && span.Start == 0)
{
return this;
}
else
{
return new SubText(this, span);
}
}
/// <summary>
/// Returns a <see cref="SourceText"/> that has the contents of this text including and after the start position.
/// </summary>
public SourceText GetSubText(int start)
{
if (start < 0 || start > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (start == 0)
{
return this;
}
else
{
return this.GetSubText(new TextSpan(start, this.Length - start));
}
}
/// <summary>
/// Write this <see cref="SourceText"/> to a text writer.
/// </summary>
public void Write(TextWriter textWriter, CancellationToken cancellationToken = default(CancellationToken))
{
this.Write(textWriter, new TextSpan(0, this.Length), cancellationToken);
}
/// <summary>
/// Write a span of text to a text writer.
/// </summary>
public virtual void Write(TextWriter writer, TextSpan span, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSubSpan(span);
var buffer = s_charArrayPool.Allocate();
try
{
int offset = span.Start;
int end = span.End;
while (offset < end)
{
cancellationToken.ThrowIfCancellationRequested();
int count = Math.Min(buffer.Length, end - offset);
this.CopyTo(offset, buffer, 0, count);
writer.Write(buffer, 0, count);
offset += count;
}
}
finally
{
s_charArrayPool.Free(buffer);
}
}
public ImmutableArray<byte> GetChecksum()
{
if (_lazyChecksum.IsDefault)
{
using (var stream = new SourceTextStream(this, useDefaultEncodingIfNull: true))
{
ImmutableInterlocked.InterlockedInitialize(ref _lazyChecksum, CalculateChecksum(stream, _checksumAlgorithm));
}
}
return _lazyChecksum;
}
internal static ImmutableArray<byte> CalculateChecksum(byte[] buffer, int offset, int count, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
return ImmutableArray.Create(algorithm.ComputeHash(buffer, offset, count));
}
}
internal static ImmutableArray<byte> CalculateChecksum(Stream stream, SourceHashAlgorithm algorithmId)
{
using (var algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
{
RoslynDebug.Assert(algorithm != null);
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
return ImmutableArray.Create(algorithm.ComputeHash(stream));
}
}
/// <summary>
/// Provides a string representation of the SourceText.
/// </summary>
public override string ToString()
{
return ToString(new TextSpan(0, this.Length));
}
/// <summary>
/// Gets a string containing the characters in specified span.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception>
public virtual string ToString(TextSpan span)
{
CheckSubSpan(span);
// default implementation constructs text using CopyTo
var builder = new StringBuilder();
var buffer = new char[Math.Min(span.Length, 1024)];
int position = Math.Max(Math.Min(span.Start, this.Length), 0);
int length = Math.Min(span.End, this.Length) - position;
while (position < this.Length && length > 0)
{
int copyLength = Math.Min(buffer.Length, length);
this.CopyTo(position, buffer, 0, copyLength);
builder.Append(buffer, 0, copyLength);
length -= copyLength;
position += copyLength;
}
return builder.ToString();
}
#region Changes
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// </summary>
public virtual SourceText WithChanges(IEnumerable<TextChange> changes)
{
if (changes == null)
{
throw new ArgumentNullException(nameof(changes));
}
if (!changes.Any())
{
return this;
}
var segments = ArrayBuilder<SourceText>.GetInstance();
var changeRanges = ArrayBuilder<TextChangeRange>.GetInstance();
try
{
int position = 0;
foreach (var change in changes)
{
if (change.Span.End > this.Length)
throw new ArgumentException(CodeAnalysisResources.ChangesMustBeWithinBoundsOfSourceText, nameof(changes));
// there can be no overlapping changes
if (change.Span.Start < position)
{
// Handle the case of unordered changes by sorting the input and retrying. This is inefficient, but
// downstream consumers have been known to hit this case in the past and we want to avoid crashes.
// https://github.com/dotnet/roslyn/pull/26339
if (change.Span.End <= changeRanges.Last().Span.Start)
{
changes = (from c in changes
where !c.Span.IsEmpty || c.NewText?.Length > 0
orderby c.Span
select c).ToList();
return WithChanges(changes);
}
throw new ArgumentException(CodeAnalysisResources.ChangesMustNotOverlap, nameof(changes));
}
var newTextLength = change.NewText?.Length ?? 0;
// ignore changes that don't change anything
if (change.Span.Length == 0 && newTextLength == 0)
continue;
// if we've skipped a range, add
if (change.Span.Start > position)
{
var subText = this.GetSubText(new TextSpan(position, change.Span.Start - position));
CompositeText.AddSegments(segments, subText);
}
if (newTextLength > 0)
{
var segment = SourceText.From(change.NewText!, this.Encoding, this.ChecksumAlgorithm);
CompositeText.AddSegments(segments, segment);
}
position = change.Span.End;
changeRanges.Add(new TextChangeRange(change.Span, newTextLength));
}
// no changes actually happened?
if (position == 0 && segments.Count == 0)
{
return this;
}
if (position < this.Length)
{
var subText = this.GetSubText(new TextSpan(position, this.Length - position));
CompositeText.AddSegments(segments, subText);
}
var newText = CompositeText.ToSourceText(segments, this, adjustSegments: true);
if (newText != this)
{
return new ChangedText(this, newText, changeRanges.ToImmutable());
}
else
{
return this;
}
}
finally
{
segments.Free();
changeRanges.Free();
}
}
/// <summary>
/// Constructs a new SourceText from this text with the specified changes.
/// <exception cref="ArgumentException">If any changes are not in bounds of this <see cref="SourceText"/>.</exception>
/// <exception cref="ArgumentException">If any changes overlap other changes.</exception>
/// </summary>
/// <remarks>
/// Changes do not have to be in sorted order. However, <see cref="WithChanges(IEnumerable{TextChange})"/> will
/// perform better if they are.
/// </remarks>
public SourceText WithChanges(params TextChange[] changes)
{
return this.WithChanges((IEnumerable<TextChange>)changes);
}
/// <summary>
/// Returns a new SourceText with the specified span of characters replaced by the new text.
/// </summary>
public SourceText Replace(TextSpan span, string newText)
{
return this.WithChanges(new TextChange(span, newText));
}
/// <summary>
/// Returns a new SourceText with the specified range of characters replaced by the new text.
/// </summary>
public SourceText Replace(int start, int length, string newText)
{
return this.Replace(new TextSpan(start, length), newText);
}
/// <summary>
/// Gets the set of <see cref="TextChangeRange"/> that describe how the text changed
/// between this text an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChangeRange> GetChangeRanges(SourceText oldText)
{
if (oldText == null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (oldText == this)
{
return TextChangeRange.NoChanges;
}
else
{
return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), this.Length));
}
}
/// <summary>
/// Gets the set of <see cref="TextChange"/> that describe how the text changed
/// between this text and an older version. This may be multiple detailed changes
/// or a single change encompassing the entire text.
/// </summary>
public virtual IReadOnlyList<TextChange> GetTextChanges(SourceText oldText)
{
int newPosDelta = 0;
var ranges = this.GetChangeRanges(oldText).ToList();
var textChanges = new List<TextChange>(ranges.Count);
foreach (var range in ranges)
{
var newPos = range.Span.Start + newPosDelta;
// determine where in the newText this text exists
string newt;
if (range.NewLength > 0)
{
var span = new TextSpan(newPos, range.NewLength);
newt = this.ToString(span);
}
else
{
newt = string.Empty;
}
textChanges.Add(new TextChange(range.Span, newt));
newPosDelta += range.NewLength - range.Span.Length;
}
return textChanges.ToImmutableArrayOrEmpty();
}
#endregion
#region Lines
/// <summary>
/// The collection of individual text lines.
/// </summary>
public TextLineCollection Lines
{
get
{
var info = _lazyLineInfo;
return info ?? Interlocked.CompareExchange(ref _lazyLineInfo, info = GetLinesCore(), null) ?? info;
}
}
internal bool TryGetLines([NotNullWhen(returnValue: true)] out TextLineCollection? lines)
{
lines = _lazyLineInfo;
return lines != null;
}
/// <summary>
/// Called from <see cref="Lines"/> to initialize the <see cref="TextLineCollection"/>. Thereafter,
/// the collection is cached.
/// </summary>
/// <returns>A new <see cref="TextLineCollection"/> representing the individual text lines.</returns>
protected virtual TextLineCollection GetLinesCore()
{
return new LineInfo(this, ParseLineStarts());
}
internal sealed class LineInfo : TextLineCollection
{
private readonly SourceText _text;
private readonly int[] _lineStarts;
private int _lastLineNumber;
public LineInfo(SourceText text, int[] lineStarts)
{
_text = text;
_lineStarts = lineStarts;
}
public override int Count => _lineStarts.Length;
public override TextLine this[int index]
{
get
{
if (index < 0 || index >= _lineStarts.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
int start = _lineStarts[index];
if (index == _lineStarts.Length - 1)
{
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, _text.Length));
}
else
{
int end = _lineStarts[index + 1];
return TextLine.FromSpan(_text, TextSpan.FromBounds(start, end));
}
}
}
public override int IndexOf(int position)
{
if (position < 0 || position > _text.Length)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
int lineNumber;
// it is common to ask about position on the same line
// as before or on the next couple lines
var lastLineNumber = _lastLineNumber;
if (position >= _lineStarts[lastLineNumber])
{
var limit = Math.Min(_lineStarts.Length, lastLineNumber + 4);
for (int i = lastLineNumber; i < limit; i++)
{
if (position < _lineStarts[i])
{
lineNumber = i - 1;
_lastLineNumber = lineNumber;
return lineNumber;
}
}
}
// Binary search to find the right line
// if no lines start exactly at position, round to the left
// EoF position will map to the last line.
lineNumber = _lineStarts.BinarySearch(position);
if (lineNumber < 0)
{
lineNumber = (~lineNumber) - 1;
}
_lastLineNumber = lineNumber;
return lineNumber;
}
public override TextLine GetLineFromPosition(int position)
{
return this[IndexOf(position)];
}
}
private void EnumerateChars(Action<int, char[], int> action)
{
var position = 0;
var buffer = s_charArrayPool.Allocate();
var length = this.Length;
while (position < length)
{
var contentLength = Math.Min(length - position, buffer.Length);
this.CopyTo(position, buffer, 0, contentLength);
action(position, buffer, contentLength);
position += contentLength;
}
// once more with zero length to signal the end
action(position, buffer, 0);
s_charArrayPool.Free(buffer);
}
private int[] ParseLineStarts()
{
// Corner case check
if (0 == this.Length)
{
return new[] { 0 };
}
var lineStarts = ArrayBuilder<int>.GetInstance();
lineStarts.Add(0); // there is always the first line
var lastWasCR = false;
// The following loop goes through every character in the text. It is highly
// performance critical, and thus inlines knowledge about common line breaks
// and non-line breaks.
EnumerateChars((int position, char[] buffer, int length) =>
{
var index = 0;
if (lastWasCR)
{
if (length > 0 && buffer[0] == '\n')
{
index++;
}
lineStarts.Add(position + index);
lastWasCR = false;
}
while (index < length)
{
char c = buffer[index];
index++;
// Common case - ASCII & not a line break
// if (c > '\r' && c <= 127)
// if (c >= ('\r'+1) && c <= 127)
const uint bias = '\r' + 1;
if (unchecked(c - bias) <= (127 - bias))
{
continue;
}
// Assumes that the only 2-char line break sequence is CR+LF
if (c == '\r')
{
if (index < length && buffer[index] == '\n')
{
index++;
}
else if (index >= length)
{
lastWasCR = true;
continue;
}
}
else if (!TextUtilities.IsAnyLineBreakCharacter(c))
{
continue;
}
// next line starts at index
lineStarts.Add(position + index);
}
});
return lineStarts.ToArrayAndFree();
}
#endregion
/// <summary>
/// Compares the content with content of another <see cref="SourceText"/>.
/// </summary>
public bool ContentEquals(SourceText other)
{
if (ReferenceEquals(this, other))
{
return true;
}
// Checksum may be provided by a subclass, which is thus responsible for passing us a true hash.
ImmutableArray<byte> leftChecksum = _lazyChecksum;
ImmutableArray<byte> rightChecksum = other._lazyChecksum;
if (!leftChecksum.IsDefault && !rightChecksum.IsDefault && this.Encoding == other.Encoding && this.ChecksumAlgorithm == other.ChecksumAlgorithm)
{
return leftChecksum.SequenceEqual(rightChecksum);
}
return ContentEqualsImpl(other);
}
/// <summary>
/// Implements equality comparison of the content of two different instances of <see cref="SourceText"/>.
/// </summary>
protected virtual bool ContentEqualsImpl(SourceText other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (this.Length != other.Length)
{
return false;
}
var buffer1 = s_charArrayPool.Allocate();
var buffer2 = s_charArrayPool.Allocate();
try
{
int position = 0;
while (position < this.Length)
{
int n = Math.Min(this.Length - position, buffer1.Length);
this.CopyTo(position, buffer1, 0, n);
other.CopyTo(position, buffer2, 0, n);
for (int i = 0; i < n; i++)
{
if (buffer1[i] != buffer2[i])
{
return false;
}
}
position += n;
}
return true;
}
finally
{
s_charArrayPool.Free(buffer2);
s_charArrayPool.Free(buffer1);
}
}
/// <summary>
/// Detect an encoding by looking for byte order marks.
/// </summary>
/// <param name="source">A buffer containing the encoded text.</param>
/// <param name="length">The length of valid data in the buffer.</param>
/// <param name="preambleLength">The length of any detected byte order marks.</param>
/// <returns>The detected encoding or null if no recognized byte order mark was present.</returns>
internal static Encoding? TryReadByteOrderMark(byte[] source, int length, out int preambleLength)
{
RoslynDebug.Assert(source != null);
Debug.Assert(length <= source.Length);
if (length >= 2)
{
switch (source[0])
{
case 0xFE:
if (source[1] == 0xFF)
{
preambleLength = 2;
return Encoding.BigEndianUnicode;
}
break;
case 0xFF:
if (source[1] == 0xFE)
{
preambleLength = 2;
return Encoding.Unicode;
}
break;
case 0xEF:
if (source[1] == 0xBB && length >= 3 && source[2] == 0xBF)
{
preambleLength = 3;
return Encoding.UTF8;
}
break;
}
}
preambleLength = 0;
return null;
}
private class StaticContainer : SourceTextContainer
{
private readonly SourceText _text;
public StaticContainer(SourceText text)
{
_text = text;
}
public override SourceText CurrentText => _text;
public override event EventHandler<TextChangeEventArgs> TextChanged
{
add
{
// do nothing
}
remove
{
// do nothing
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationResultCategory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.Debugger.Evaluation
{
public enum DkmEvaluationResultCategory
{
Other,
Data,
Method,
Event,
Property,
Class,
Interface,
BaseClass,
InnerClass,
MostDerivedClass
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.Debugger.Evaluation
{
public enum DkmEvaluationResultCategory
{
Other,
Data,
Method,
Event,
Property,
Class,
Interface,
BaseClass,
InnerClass,
MostDerivedClass
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/Portable/Compilation/SemanticModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Allows asking semantic questions about a tree of syntax nodes in a Compilation. Typically,
/// an instance is obtained by a call to GetBinding on a Compilation or Compilation.
/// </summary>
/// <remarks>
/// <para>An instance of SemanticModel caches local symbols and semantic information. Thus, it
/// is much more efficient to use a single instance of SemanticModel when asking multiple
/// questions about a syntax tree, because information from the first question may be reused.
/// This also means that holding onto an instance of SemanticModel for a long time may keep a
/// significant amount of memory from being garbage collected.
/// </para>
/// <para>
/// When an answer is a named symbol that is reachable by traversing from the root of the symbol
/// table, (that is, from an AssemblySymbol of the Compilation), that symbol will be returned
/// (i.e. the returned value will be reference-equal to one reachable from the root of the
/// symbol table). Symbols representing entities without names (e.g. array-of-int) may or may
/// not exhibit reference equality. However, some named symbols (such as local variables) are
/// not reachable from the root. These symbols are visible as answers to semantic questions.
/// When the same SemanticModel object is used, the answers exhibit reference-equality.
/// </para>
/// </remarks>
public abstract class SemanticModel
{
/// <summary>
/// Gets the source language ("C#" or "Visual Basic").
/// </summary>
public abstract string Language { get; }
/// <summary>
/// The compilation this model was obtained from.
/// </summary>
public Compilation Compilation
{
get { return CompilationCore; }
}
/// <summary>
/// The compilation this model was obtained from.
/// </summary>
protected abstract Compilation CompilationCore { get; }
/// <summary>
/// The syntax tree this model was obtained from.
/// </summary>
public SyntaxTree SyntaxTree
{
get { return SyntaxTreeCore; }
}
/// <summary>
/// The syntax tree this model was obtained from.
/// </summary>
protected abstract SyntaxTree SyntaxTreeCore { get; }
/// <summary>
/// Gets the operation corresponding to the expression or statement syntax node.
/// </summary>
/// <param name="node">The expression or statement syntax node.</param>
/// <param name="cancellationToken">An optional cancellation token.</param>
/// <returns></returns>
public IOperation? GetOperation(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
return GetOperationCore(node, cancellationToken);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
// Log a Non-fatal-watson and then ignore the crash in the attempt of getting operation
Debug.Assert(false, "\n" + e.ToString());
}
return null;
}
protected abstract IOperation? GetOperationCore(SyntaxNode node, CancellationToken cancellationToken);
/// <summary>
/// Returns true if this is a SemanticModel that ignores accessibility rules when answering semantic questions.
/// </summary>
public virtual bool IgnoresAccessibility
{
get { return false; }
}
/// <summary>
/// Gets symbol information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
internal SymbolInfo GetSymbolInfo(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetSymbolInfoCore(node, cancellationToken);
}
/// <summary>
/// Gets symbol information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
protected abstract SymbolInfo GetSymbolInfoCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
internal SymbolInfo GetSpeculativeSymbolInfo(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption)
{
return GetSpeculativeSymbolInfoCore(position, expression, bindingOption);
}
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
protected abstract SymbolInfo GetSpeculativeSymbolInfoCore(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption);
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
internal TypeInfo GetSpeculativeTypeInfo(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption)
{
return GetSpeculativeTypeInfoCore(position, expression, bindingOption);
}
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
protected abstract TypeInfo GetSpeculativeTypeInfoCore(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption);
/// <summary>
/// Gets type information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
internal TypeInfo GetTypeInfo(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetTypeInfoCore(node, cancellationToken);
}
/// <summary>
/// Gets type information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
protected abstract TypeInfo GetTypeInfoCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// If "nameSyntax" resolves to an alias name, return the IAliasSymbol corresponding
/// to A. Otherwise return null.
/// </summary>
/// <param name="nameSyntax">Name to get alias info for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the alias information.</param>
internal IAliasSymbol? GetAliasInfo(SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
return GetAliasInfoCore(nameSyntax, cancellationToken);
}
/// <summary>
/// If "nameSyntax" resolves to an alias name, return the IAliasSymbol corresponding
/// to A. Otherwise return null.
/// </summary>
/// <param name="nameSyntax">Name to get alias info for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the alias information.</param>
protected abstract IAliasSymbol? GetAliasInfoCore(SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns true if this is a speculative semantic model created with any of the TryGetSpeculativeSemanticModel methods.
/// </summary>
[MemberNotNullWhen(true, nameof(ParentModel))]
public abstract bool IsSpeculativeSemanticModel
{
get;
}
/// <summary>
/// If this is a speculative semantic model, returns the original position at which the speculative model was created.
/// Otherwise, returns 0.
/// </summary>
public abstract int OriginalPositionForSpeculation
{
get;
}
/// <summary>
/// If this is a speculative semantic model, then returns its parent semantic model.
/// Otherwise, returns null.
/// </summary>
public SemanticModel? ParentModel
{
get { return this.ParentModelCore; }
}
/// <summary>
/// If this is a speculative semantic model, then returns its parent semantic model.
/// Otherwise, returns null.
/// </summary>
protected abstract SemanticModel? ParentModelCore
{
get;
}
/// <summary>
/// If this is a non-speculative member semantic model, then returns the containing semantic model for the entire tree.
/// Otherwise, returns this instance of the semantic model.
/// </summary>
internal abstract SemanticModel ContainingModelOrSelf
{
get;
}
/// <summary>
/// Binds the name in the context of the specified location and sees if it resolves to an
/// alias name. If it does, return the AliasSymbol corresponding to it. Otherwise, return null.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="nameSyntax">A syntax node that represents a name. This syntax
/// node need not and typically does not appear in the source code referred to by the
/// SemanticModel instance.</param>
/// <param name="bindingOption">Indicates whether to binding the name as a full expression,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <remarks>The passed in name is interpreted as a stand-alone name, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
internal IAliasSymbol? GetSpeculativeAliasInfo(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption)
{
return GetSpeculativeAliasInfoCore(position, nameSyntax, bindingOption);
}
/// <summary>
/// Binds the name in the context of the specified location and sees if it resolves to an
/// alias name. If it does, return the AliasSymbol corresponding to it. Otherwise, return null.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="nameSyntax">A syntax node that represents a name. This syntax
/// node need not and typically does not appear in the source code referred to by the
/// SemanticModel instance.</param>
/// <param name="bindingOption">Indicates whether to binding the name as a full expression,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <remarks>The passed in name is interpreted as a stand-alone name, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
protected abstract IAliasSymbol? GetSpeculativeAliasInfoCore(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption);
/// <summary>
/// Get all of the syntax errors within the syntax tree associated with this
/// object. Does not get errors involving declarations or compiling method bodies or initializers.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
public abstract ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all of the declaration errors within the syntax tree associated with this
/// object. Does not get errors involving incorrect syntax, compiling method bodies or initializers.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
/// <remarks>The declaration errors for a syntax tree are cached. The first time this method
/// is called, all declarations are analyzed for diagnostics. Calling this a second time
/// will return the cached diagnostics.
/// </remarks>
public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all of the method body and initializer errors within the syntax tree associated with this
/// object. Does not get errors involving incorrect syntax or declarations.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
/// <remarks>The method body errors for a syntax tree are not cached. The first time this method
/// is called, all method bodies are analyzed for diagnostics. Calling this a second time
/// will repeat this work.
/// </remarks>
public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all the errors within the syntax tree associated with this object. Includes errors
/// involving compiling method bodies or initializers, in addition to the errors returned by
/// GetDeclarationDiagnostics.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
/// <remarks>
/// Because this method must semantically bind all method bodies and initializers to check
/// for diagnostics, it may take a significant amount of time. Unlike
/// GetDeclarationDiagnostics, diagnostics for method bodies and initializers are not
/// cached, any semantic information used to obtain the diagnostics is discarded.
/// </remarks>
public abstract ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the symbol associated with a declaration syntax node.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbol declared by the node or null if the node is not a declaration.</returns>
internal ISymbol? GetDeclaredSymbolForNode(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken))
{
return GetDeclaredSymbolCore(declaration, cancellationToken);
}
/// <summary>
/// Gets the symbol associated with a declaration syntax node.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbol declared by the node or null if the node is not a declaration.</returns>
protected abstract ISymbol? GetDeclaredSymbolCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the symbol associated with a declaration syntax node. Unlike <see cref="GetDeclaredSymbolForNode(SyntaxNode, CancellationToken)"/>,
/// this method returns all symbols declared by a given declaration syntax node. Specifically, in the case of field declaration syntax nodes,
/// which can declare multiple symbols, this method returns all declared symbols.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbols declared by the node.</returns>
internal ImmutableArray<ISymbol> GetDeclaredSymbolsForNode(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken))
{
return GetDeclaredSymbolsCore(declaration, cancellationToken);
}
/// <summary>
/// Gets the symbol associated with a declaration syntax node. Unlike <see cref="GetDeclaredSymbolForNode(SyntaxNode, CancellationToken)"/>,
/// this method returns all symbols declared by a given declaration syntax node. Specifically, in the case of field declaration syntax nodes,
/// which can declare multiple symbols, this method returns all declared symbols.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbols declared by the node.</returns>
protected abstract ImmutableArray<ISymbol> GetDeclaredSymbolsCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the available named symbols in the context of the specified location and optional container. Only
/// symbols that are accessible and visible from the given location are returned.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="container">The container to search for symbols within. If null then the enclosing declaration
/// scope around position is used.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <param name="includeReducedExtensionMethods">Consider (reduced) extension methods.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
///
/// Labels are not considered (see <see cref="LookupLabels"/>).
///
/// Non-reduced extension methods are considered regardless of the value of <paramref name="includeReducedExtensionMethods"/>.
/// </remarks>
public ImmutableArray<ISymbol> LookupSymbols(
int position,
INamespaceOrTypeSymbol? container = null,
string? name = null,
bool includeReducedExtensionMethods = false)
{
return LookupSymbolsCore(position, container, name, includeReducedExtensionMethods);
}
/// <summary>
/// Backing implementation of <see cref="LookupSymbols"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupSymbolsCore(
int position,
INamespaceOrTypeSymbol? container,
string? name,
bool includeReducedExtensionMethods);
/// <summary>
/// Gets the available base type members in the context of the specified location. Akin to
/// calling <see cref="LookupSymbols"/> with the container set to the immediate base type of
/// the type in which <paramref name="position"/> occurs. However, the accessibility rules
/// are different: protected members of the base type will be visible.
///
/// Consider the following example:
///
/// public class Base
/// {
/// protected void M() { }
/// }
///
/// public class Derived : Base
/// {
/// void Test(Base b)
/// {
/// b.M(); // Error - cannot access protected member.
/// base.M();
/// }
/// }
///
/// Protected members of an instance of another type are only accessible if the instance is known
/// to be "this" instance (as indicated by the "base" keyword).
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible.
///
/// Non-reduced extension methods are considered, but reduced extension methods are not.
/// </remarks>
public ImmutableArray<ISymbol> LookupBaseMembers(
int position,
string? name = null)
{
return LookupBaseMembersCore(position, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupBaseMembers"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupBaseMembersCore(
int position,
string? name);
/// <summary>
/// Gets the available named static member symbols in the context of the specified location and optional container.
/// Only members that are accessible and visible from the given location are returned.
///
/// Non-reduced extension methods are considered, since they are static methods.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="container">The container to search for symbols within. If null then the enclosing declaration
/// scope around position is used.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
///
/// Essentially the same as filtering instance members out of the results of an analogous <see cref="LookupSymbols"/> call.
/// </remarks>
public ImmutableArray<ISymbol> LookupStaticMembers(
int position,
INamespaceOrTypeSymbol? container = null,
string? name = null)
{
return LookupStaticMembersCore(position, container, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupStaticMembers"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupStaticMembersCore(
int position,
INamespaceOrTypeSymbol? container,
string? name);
/// <summary>
/// Gets the available named namespace and type symbols in the context of the specified location and optional container.
/// Only members that are accessible and visible from the given location are returned.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="container">The container to search for symbols within. If null then the enclosing declaration
/// scope around position is used.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
///
/// Does not return INamespaceOrTypeSymbol, because there could be aliases.
/// </remarks>
public ImmutableArray<ISymbol> LookupNamespacesAndTypes(
int position,
INamespaceOrTypeSymbol? container = null,
string? name = null)
{
return LookupNamespacesAndTypesCore(position, container, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupNamespacesAndTypes"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupNamespacesAndTypesCore(
int position,
INamespaceOrTypeSymbol? container,
string? name);
/// <summary>
/// Gets the available named label symbols in the context of the specified location and optional container.
/// Only members that are accessible and visible from the given location are returned.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
/// </remarks>
public ImmutableArray<ISymbol> LookupLabels(
int position,
string? name = null)
{
return LookupLabelsCore(position, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupLabels"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupLabelsCore(
int position,
string? name);
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
internal ControlFlowAnalysis AnalyzeControlFlow(SyntaxNode firstStatement, SyntaxNode lastStatement)
{
return AnalyzeControlFlowCore(firstStatement, lastStatement);
}
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
protected abstract ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement);
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="statement">The statement to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The statement must be fully inside the same method body.
/// </remarks>
internal ControlFlowAnalysis AnalyzeControlFlow(SyntaxNode statement)
{
return AnalyzeControlFlowCore(statement);
}
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="statement">The statement to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The statement must be fully inside the same method body.
/// </remarks>
protected abstract ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode statement);
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode firstStatement, SyntaxNode lastStatement)
{
return AnalyzeDataFlowCore(firstStatement, lastStatement);
}
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement);
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="statementOrExpression">The statement or expression to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The statement or expression is not with a method
/// body or field or property initializer.</exception>
/// <remarks>
/// The statement or expression must be fully inside a method body.
/// </remarks>
internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode statementOrExpression)
{
return AnalyzeDataFlowCore(statementOrExpression);
}
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="statementOrExpression">The statement or expression to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The statement or expression is not with a method
/// body or field or property initializer.</exception>
/// <remarks>
/// The statement or expression must be fully inside a method body.
/// </remarks>
protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode statementOrExpression);
/// <summary>
/// If the node provided has a constant value an Optional value will be returned with
/// HasValue set to true and with Value set to the constant. If the node does not have an
/// constant value, an Optional will be returned with HasValue set to false.
/// </summary>
public Optional<object?> GetConstantValue(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetConstantValueCore(node, cancellationToken);
}
/// <summary>
/// If the node provided has a constant value an Optional value will be returned with
/// HasValue set to true and with Value set to the constant. If the node does not have an
/// constant value, an Optional will be returned with HasValue set to false.
/// </summary>
protected abstract Optional<object?> GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// When getting information for a symbol that resolves to a method group or property group,
/// from which a method is then chosen; the chosen method or property is present in Symbol;
/// all methods in the group that was consulted are placed in this property.
/// </summary>
internal ImmutableArray<ISymbol> GetMemberGroup(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMemberGroupCore(node, cancellationToken);
}
/// <summary>
/// When getting information for a symbol that resolves to a method group or property group,
/// from which a method is then chosen; the chosen method or property is present in Symbol;
/// all methods in the group that was consulted are placed in this property.
/// </summary>
protected abstract ImmutableArray<ISymbol> GetMemberGroupCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Given a position in the SyntaxTree for this SemanticModel returns the innermost Symbol
/// that the position is considered inside of.
/// </summary>
public ISymbol? GetEnclosingSymbol(int position, CancellationToken cancellationToken = default(CancellationToken))
{
return GetEnclosingSymbolCore(position, cancellationToken);
}
/// <summary>
/// Given a position in the SyntaxTree for this SemanticModel returns the innermost Symbol
/// that the position is considered inside of.
/// </summary>
protected abstract ISymbol? GetEnclosingSymbolCore(int position, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Determines if the symbol is accessible from the specified location.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="symbol">The symbol that we are checking to see if it accessible.</param>
/// <returns>
/// True if "symbol is accessible, false otherwise.</returns>
/// <remarks>
/// This method only checks accessibility from the point of view of the accessibility
/// modifiers on symbol and its containing types. Even if true is returned, the given symbol
/// may not be able to be referenced for other reasons, such as name hiding.
/// </remarks>
public bool IsAccessible(int position, ISymbol symbol)
{
return IsAccessibleCore(position, symbol);
}
/// <summary>
/// Determines if the symbol is accessible from the specified location.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="symbol">The symbol that we are checking to see if it accessible.</param>
/// <returns>
/// True if "symbol is accessible, false otherwise.</returns>
/// <remarks>
/// This method only checks accessibility from the point of view of the accessibility
/// modifiers on symbol and its containing types. Even if true is returned, the given symbol
/// may not be able to be referenced for other reasons, such as name hiding.
/// </remarks>
protected abstract bool IsAccessibleCore(int position, ISymbol symbol);
/// <summary>
/// Field-like events can be used as fields in types that can access private
/// members of the declaring type of the event.
/// </summary>
/// <remarks>
/// Always false for VB events.
/// </remarks>
public bool IsEventUsableAsField(int position, IEventSymbol eventSymbol)
{
return IsEventUsableAsFieldCore(position, eventSymbol);
}
/// <summary>
/// Field-like events can be used as fields in types that can access private
/// members of the declaring type of the event.
/// </summary>
/// <remarks>
/// Always false for VB events.
/// </remarks>
protected abstract bool IsEventUsableAsFieldCore(int position, IEventSymbol eventSymbol);
/// <summary>
/// If <paramref name="nameSyntax"/> is an identifier name syntax node, return the <see cref="PreprocessingSymbolInfo"/> corresponding
/// to it.
/// </summary>
/// <param name="nameSyntax">The nameSyntax node to get semantic information for.</param>
public PreprocessingSymbolInfo GetPreprocessingSymbolInfo(SyntaxNode nameSyntax)
{
return GetPreprocessingSymbolInfoCore(nameSyntax);
}
/// <summary>
/// If <paramref name="nameSyntax"/> is an identifier name syntax node, return the <see cref="PreprocessingSymbolInfo"/> corresponding
/// to it.
/// </summary>
/// <param name="nameSyntax">The nameSyntax node to get semantic information for.</param>
protected abstract PreprocessingSymbolInfo GetPreprocessingSymbolInfoCore(SyntaxNode nameSyntax);
/// <summary>
/// Gets the <see cref="DeclarationInfo"/> for all the declarations whose span overlaps with the given <paramref name="span"/>.
/// </summary>
/// <param name="span">Span to get declarations.</param>
/// <param name="getSymbol">Flag indicating whether <see cref="DeclarationInfo.DeclaredSymbol"/> should be computed for the returned declaration infos.
/// If false, then <see cref="DeclarationInfo.DeclaredSymbol"/> is always null.</param>
/// <param name="builder">Builder to add declarations.</param>
/// <param name="cancellationToken">Cancellation token.</param>
internal abstract void ComputeDeclarationsInSpan(TextSpan span, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken);
/// <summary>
/// Takes a node and returns a set of declarations that overlap the node's span.
/// </summary>
internal abstract void ComputeDeclarationsInNode(SyntaxNode node, ISymbol associatedSymbol, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken, int? levelsToCompute = null);
internal virtual Func<SyntaxNode, bool>? GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) => null;
/// <summary>
/// Takes a Symbol and syntax for one of its declaring syntax reference and returns the topmost syntax node to be used by syntax analyzer.
/// </summary>
protected internal virtual SyntaxNode GetTopmostNodeForDiagnosticAnalysis(ISymbol symbol, SyntaxNode declaringSyntax)
{
return declaringSyntax;
}
/// <summary>
/// Root of this semantic model
/// </summary>
internal SyntaxNode Root => RootCore;
/// <summary>
/// Root of this semantic model
/// </summary>
protected abstract SyntaxNode RootCore { get; }
/// <summary>
/// Gets the <see cref="NullableContext"/> at a position in the file.
/// </summary>
/// <param name="position">The position to get the context for.</param>
public abstract NullableContext GetNullableContext(int position);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Allows asking semantic questions about a tree of syntax nodes in a Compilation. Typically,
/// an instance is obtained by a call to GetBinding on a Compilation or Compilation.
/// </summary>
/// <remarks>
/// <para>An instance of SemanticModel caches local symbols and semantic information. Thus, it
/// is much more efficient to use a single instance of SemanticModel when asking multiple
/// questions about a syntax tree, because information from the first question may be reused.
/// This also means that holding onto an instance of SemanticModel for a long time may keep a
/// significant amount of memory from being garbage collected.
/// </para>
/// <para>
/// When an answer is a named symbol that is reachable by traversing from the root of the symbol
/// table, (that is, from an AssemblySymbol of the Compilation), that symbol will be returned
/// (i.e. the returned value will be reference-equal to one reachable from the root of the
/// symbol table). Symbols representing entities without names (e.g. array-of-int) may or may
/// not exhibit reference equality. However, some named symbols (such as local variables) are
/// not reachable from the root. These symbols are visible as answers to semantic questions.
/// When the same SemanticModel object is used, the answers exhibit reference-equality.
/// </para>
/// </remarks>
public abstract class SemanticModel
{
/// <summary>
/// Gets the source language ("C#" or "Visual Basic").
/// </summary>
public abstract string Language { get; }
/// <summary>
/// The compilation this model was obtained from.
/// </summary>
public Compilation Compilation
{
get { return CompilationCore; }
}
/// <summary>
/// The compilation this model was obtained from.
/// </summary>
protected abstract Compilation CompilationCore { get; }
/// <summary>
/// The syntax tree this model was obtained from.
/// </summary>
public SyntaxTree SyntaxTree
{
get { return SyntaxTreeCore; }
}
/// <summary>
/// The syntax tree this model was obtained from.
/// </summary>
protected abstract SyntaxTree SyntaxTreeCore { get; }
/// <summary>
/// Gets the operation corresponding to the expression or statement syntax node.
/// </summary>
/// <param name="node">The expression or statement syntax node.</param>
/// <param name="cancellationToken">An optional cancellation token.</param>
/// <returns></returns>
public IOperation? GetOperation(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
return GetOperationCore(node, cancellationToken);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
// Log a Non-fatal-watson and then ignore the crash in the attempt of getting operation
Debug.Assert(false, "\n" + e.ToString());
}
return null;
}
protected abstract IOperation? GetOperationCore(SyntaxNode node, CancellationToken cancellationToken);
/// <summary>
/// Returns true if this is a SemanticModel that ignores accessibility rules when answering semantic questions.
/// </summary>
public virtual bool IgnoresAccessibility
{
get { return false; }
}
/// <summary>
/// Gets symbol information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
internal SymbolInfo GetSymbolInfo(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetSymbolInfoCore(node, cancellationToken);
}
/// <summary>
/// Gets symbol information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
protected abstract SymbolInfo GetSymbolInfoCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
internal SymbolInfo GetSpeculativeSymbolInfo(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption)
{
return GetSpeculativeSymbolInfoCore(position, expression, bindingOption);
}
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
protected abstract SymbolInfo GetSpeculativeSymbolInfoCore(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption);
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
internal TypeInfo GetSpeculativeTypeInfo(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption)
{
return GetSpeculativeTypeInfoCore(position, expression, bindingOption);
}
/// <summary>
/// Binds the node in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information
/// about an expression that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to SemanticModel
/// instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The semantic information for the topmost node of the expression.</returns>
/// <remarks>The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
protected abstract TypeInfo GetSpeculativeTypeInfoCore(int position, SyntaxNode expression, SpeculativeBindingOption bindingOption);
/// <summary>
/// Gets type information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
internal TypeInfo GetTypeInfo(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetTypeInfoCore(node, cancellationToken);
}
/// <summary>
/// Gets type information about a syntax node.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the semantic info.</param>
protected abstract TypeInfo GetTypeInfoCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// If "nameSyntax" resolves to an alias name, return the IAliasSymbol corresponding
/// to A. Otherwise return null.
/// </summary>
/// <param name="nameSyntax">Name to get alias info for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the alias information.</param>
internal IAliasSymbol? GetAliasInfo(SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
return GetAliasInfoCore(nameSyntax, cancellationToken);
}
/// <summary>
/// If "nameSyntax" resolves to an alias name, return the IAliasSymbol corresponding
/// to A. Otherwise return null.
/// </summary>
/// <param name="nameSyntax">Name to get alias info for.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the alias information.</param>
protected abstract IAliasSymbol? GetAliasInfoCore(SyntaxNode nameSyntax, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns true if this is a speculative semantic model created with any of the TryGetSpeculativeSemanticModel methods.
/// </summary>
[MemberNotNullWhen(true, nameof(ParentModel))]
public abstract bool IsSpeculativeSemanticModel
{
get;
}
/// <summary>
/// If this is a speculative semantic model, returns the original position at which the speculative model was created.
/// Otherwise, returns 0.
/// </summary>
public abstract int OriginalPositionForSpeculation
{
get;
}
/// <summary>
/// If this is a speculative semantic model, then returns its parent semantic model.
/// Otherwise, returns null.
/// </summary>
public SemanticModel? ParentModel
{
get { return this.ParentModelCore; }
}
/// <summary>
/// If this is a speculative semantic model, then returns its parent semantic model.
/// Otherwise, returns null.
/// </summary>
protected abstract SemanticModel? ParentModelCore
{
get;
}
/// <summary>
/// If this is a non-speculative member semantic model, then returns the containing semantic model for the entire tree.
/// Otherwise, returns this instance of the semantic model.
/// </summary>
internal abstract SemanticModel ContainingModelOrSelf
{
get;
}
/// <summary>
/// Binds the name in the context of the specified location and sees if it resolves to an
/// alias name. If it does, return the AliasSymbol corresponding to it. Otherwise, return null.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="nameSyntax">A syntax node that represents a name. This syntax
/// node need not and typically does not appear in the source code referred to by the
/// SemanticModel instance.</param>
/// <param name="bindingOption">Indicates whether to binding the name as a full expression,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <remarks>The passed in name is interpreted as a stand-alone name, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
internal IAliasSymbol? GetSpeculativeAliasInfo(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption)
{
return GetSpeculativeAliasInfoCore(position, nameSyntax, bindingOption);
}
/// <summary>
/// Binds the name in the context of the specified location and sees if it resolves to an
/// alias name. If it does, return the AliasSymbol corresponding to it. Otherwise, return null.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="nameSyntax">A syntax node that represents a name. This syntax
/// node need not and typically does not appear in the source code referred to by the
/// SemanticModel instance.</param>
/// <param name="bindingOption">Indicates whether to binding the name as a full expression,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <remarks>The passed in name is interpreted as a stand-alone name, as if it
/// appeared by itself somewhere within the scope that encloses "position".</remarks>
protected abstract IAliasSymbol? GetSpeculativeAliasInfoCore(int position, SyntaxNode nameSyntax, SpeculativeBindingOption bindingOption);
/// <summary>
/// Get all of the syntax errors within the syntax tree associated with this
/// object. Does not get errors involving declarations or compiling method bodies or initializers.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
public abstract ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all of the declaration errors within the syntax tree associated with this
/// object. Does not get errors involving incorrect syntax, compiling method bodies or initializers.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
/// <remarks>The declaration errors for a syntax tree are cached. The first time this method
/// is called, all declarations are analyzed for diagnostics. Calling this a second time
/// will return the cached diagnostics.
/// </remarks>
public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all of the method body and initializer errors within the syntax tree associated with this
/// object. Does not get errors involving incorrect syntax or declarations.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
/// <remarks>The method body errors for a syntax tree are not cached. The first time this method
/// is called, all method bodies are analyzed for diagnostics. Calling this a second time
/// will repeat this work.
/// </remarks>
public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all the errors within the syntax tree associated with this object. Includes errors
/// involving compiling method bodies or initializers, in addition to the errors returned by
/// GetDeclarationDiagnostics.
/// </summary>
/// <param name="span">Optional span within the syntax tree for which to get diagnostics.
/// If no argument is specified, then diagnostics for the entire tree are returned.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the
/// process of obtaining the diagnostics.</param>
/// <remarks>
/// Because this method must semantically bind all method bodies and initializers to check
/// for diagnostics, it may take a significant amount of time. Unlike
/// GetDeclarationDiagnostics, diagnostics for method bodies and initializers are not
/// cached, any semantic information used to obtain the diagnostics is discarded.
/// </remarks>
public abstract ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the symbol associated with a declaration syntax node.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbol declared by the node or null if the node is not a declaration.</returns>
internal ISymbol? GetDeclaredSymbolForNode(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken))
{
return GetDeclaredSymbolCore(declaration, cancellationToken);
}
/// <summary>
/// Gets the symbol associated with a declaration syntax node.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbol declared by the node or null if the node is not a declaration.</returns>
protected abstract ISymbol? GetDeclaredSymbolCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the symbol associated with a declaration syntax node. Unlike <see cref="GetDeclaredSymbolForNode(SyntaxNode, CancellationToken)"/>,
/// this method returns all symbols declared by a given declaration syntax node. Specifically, in the case of field declaration syntax nodes,
/// which can declare multiple symbols, this method returns all declared symbols.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbols declared by the node.</returns>
internal ImmutableArray<ISymbol> GetDeclaredSymbolsForNode(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken))
{
return GetDeclaredSymbolsCore(declaration, cancellationToken);
}
/// <summary>
/// Gets the symbol associated with a declaration syntax node. Unlike <see cref="GetDeclaredSymbolForNode(SyntaxNode, CancellationToken)"/>,
/// this method returns all symbols declared by a given declaration syntax node. Specifically, in the case of field declaration syntax nodes,
/// which can declare multiple symbols, this method returns all declared symbols.
/// </summary>
/// <param name="declaration">A syntax node that is a declaration. This can be any type
/// derived from MemberDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax,
/// NamespaceDeclarationSyntax, ParameterSyntax, TypeParameterSyntax, or the alias part of a
/// UsingDirectiveSyntax</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The symbols declared by the node.</returns>
protected abstract ImmutableArray<ISymbol> GetDeclaredSymbolsCore(SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the available named symbols in the context of the specified location and optional container. Only
/// symbols that are accessible and visible from the given location are returned.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="container">The container to search for symbols within. If null then the enclosing declaration
/// scope around position is used.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <param name="includeReducedExtensionMethods">Consider (reduced) extension methods.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
///
/// Labels are not considered (see <see cref="LookupLabels"/>).
///
/// Non-reduced extension methods are considered regardless of the value of <paramref name="includeReducedExtensionMethods"/>.
/// </remarks>
public ImmutableArray<ISymbol> LookupSymbols(
int position,
INamespaceOrTypeSymbol? container = null,
string? name = null,
bool includeReducedExtensionMethods = false)
{
return LookupSymbolsCore(position, container, name, includeReducedExtensionMethods);
}
/// <summary>
/// Backing implementation of <see cref="LookupSymbols"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupSymbolsCore(
int position,
INamespaceOrTypeSymbol? container,
string? name,
bool includeReducedExtensionMethods);
/// <summary>
/// Gets the available base type members in the context of the specified location. Akin to
/// calling <see cref="LookupSymbols"/> with the container set to the immediate base type of
/// the type in which <paramref name="position"/> occurs. However, the accessibility rules
/// are different: protected members of the base type will be visible.
///
/// Consider the following example:
///
/// public class Base
/// {
/// protected void M() { }
/// }
///
/// public class Derived : Base
/// {
/// void Test(Base b)
/// {
/// b.M(); // Error - cannot access protected member.
/// base.M();
/// }
/// }
///
/// Protected members of an instance of another type are only accessible if the instance is known
/// to be "this" instance (as indicated by the "base" keyword).
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible.
///
/// Non-reduced extension methods are considered, but reduced extension methods are not.
/// </remarks>
public ImmutableArray<ISymbol> LookupBaseMembers(
int position,
string? name = null)
{
return LookupBaseMembersCore(position, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupBaseMembers"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupBaseMembersCore(
int position,
string? name);
/// <summary>
/// Gets the available named static member symbols in the context of the specified location and optional container.
/// Only members that are accessible and visible from the given location are returned.
///
/// Non-reduced extension methods are considered, since they are static methods.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="container">The container to search for symbols within. If null then the enclosing declaration
/// scope around position is used.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
///
/// Essentially the same as filtering instance members out of the results of an analogous <see cref="LookupSymbols"/> call.
/// </remarks>
public ImmutableArray<ISymbol> LookupStaticMembers(
int position,
INamespaceOrTypeSymbol? container = null,
string? name = null)
{
return LookupStaticMembersCore(position, container, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupStaticMembers"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupStaticMembersCore(
int position,
INamespaceOrTypeSymbol? container,
string? name);
/// <summary>
/// Gets the available named namespace and type symbols in the context of the specified location and optional container.
/// Only members that are accessible and visible from the given location are returned.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="container">The container to search for symbols within. If null then the enclosing declaration
/// scope around position is used.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
///
/// Does not return INamespaceOrTypeSymbol, because there could be aliases.
/// </remarks>
public ImmutableArray<ISymbol> LookupNamespacesAndTypes(
int position,
INamespaceOrTypeSymbol? container = null,
string? name = null)
{
return LookupNamespacesAndTypesCore(position, container, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupNamespacesAndTypes"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupNamespacesAndTypesCore(
int position,
INamespaceOrTypeSymbol? container,
string? name);
/// <summary>
/// Gets the available named label symbols in the context of the specified location and optional container.
/// Only members that are accessible and visible from the given location are returned.
/// </summary>
/// <param name="position">The character position for determining the enclosing declaration scope and
/// accessibility.</param>
/// <param name="name">The name of the symbol to find. If null is specified then symbols
/// with any names are returned.</param>
/// <returns>A list of symbols that were found. If no symbols were found, an empty list is returned.</returns>
/// <remarks>
/// The "position" is used to determine what variables are visible and accessible. Even if "container" is
/// specified, the "position" location is significant for determining which members of "containing" are
/// accessible.
/// </remarks>
public ImmutableArray<ISymbol> LookupLabels(
int position,
string? name = null)
{
return LookupLabelsCore(position, name);
}
/// <summary>
/// Backing implementation of <see cref="LookupLabels"/>.
/// </summary>
protected abstract ImmutableArray<ISymbol> LookupLabelsCore(
int position,
string? name);
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
internal ControlFlowAnalysis AnalyzeControlFlow(SyntaxNode firstStatement, SyntaxNode lastStatement)
{
return AnalyzeControlFlowCore(firstStatement, lastStatement);
}
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
protected abstract ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement);
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="statement">The statement to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The statement must be fully inside the same method body.
/// </remarks>
internal ControlFlowAnalysis AnalyzeControlFlow(SyntaxNode statement)
{
return AnalyzeControlFlowCore(statement);
}
/// <summary>
/// Analyze control-flow within a part of a method body.
/// </summary>
/// <param name="statement">The statement to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The statement must be fully inside the same method body.
/// </remarks>
protected abstract ControlFlowAnalysis AnalyzeControlFlowCore(SyntaxNode statement);
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode firstStatement, SyntaxNode lastStatement)
{
return AnalyzeDataFlowCore(firstStatement, lastStatement);
}
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="firstStatement">The first node to be included within the analysis.</param>
/// <param name="lastStatement">The last node to be included within the analysis.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The span is not with a method
/// body.</exception>
/// <remarks>
/// The first and last nodes must be fully inside the same method body.
/// </remarks>
protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode firstStatement, SyntaxNode lastStatement);
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="statementOrExpression">The statement or expression to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The statement or expression is not with a method
/// body or field or property initializer.</exception>
/// <remarks>
/// The statement or expression must be fully inside a method body.
/// </remarks>
internal DataFlowAnalysis AnalyzeDataFlow(SyntaxNode statementOrExpression)
{
return AnalyzeDataFlowCore(statementOrExpression);
}
/// <summary>
/// Analyze data-flow within a part of a method body.
/// </summary>
/// <param name="statementOrExpression">The statement or expression to be analyzed.</param>
/// <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
/// <exception cref="System.ArgumentException">The statement or expression is not with a method
/// body or field or property initializer.</exception>
/// <remarks>
/// The statement or expression must be fully inside a method body.
/// </remarks>
protected abstract DataFlowAnalysis AnalyzeDataFlowCore(SyntaxNode statementOrExpression);
/// <summary>
/// If the node provided has a constant value an Optional value will be returned with
/// HasValue set to true and with Value set to the constant. If the node does not have an
/// constant value, an Optional will be returned with HasValue set to false.
/// </summary>
public Optional<object?> GetConstantValue(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetConstantValueCore(node, cancellationToken);
}
/// <summary>
/// If the node provided has a constant value an Optional value will be returned with
/// HasValue set to true and with Value set to the constant. If the node does not have an
/// constant value, an Optional will be returned with HasValue set to false.
/// </summary>
protected abstract Optional<object?> GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// When getting information for a symbol that resolves to a method group or property group,
/// from which a method is then chosen; the chosen method or property is present in Symbol;
/// all methods in the group that was consulted are placed in this property.
/// </summary>
internal ImmutableArray<ISymbol> GetMemberGroup(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
return GetMemberGroupCore(node, cancellationToken);
}
/// <summary>
/// When getting information for a symbol that resolves to a method group or property group,
/// from which a method is then chosen; the chosen method or property is present in Symbol;
/// all methods in the group that was consulted are placed in this property.
/// </summary>
protected abstract ImmutableArray<ISymbol> GetMemberGroupCore(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Given a position in the SyntaxTree for this SemanticModel returns the innermost Symbol
/// that the position is considered inside of.
/// </summary>
public ISymbol? GetEnclosingSymbol(int position, CancellationToken cancellationToken = default(CancellationToken))
{
return GetEnclosingSymbolCore(position, cancellationToken);
}
/// <summary>
/// Given a position in the SyntaxTree for this SemanticModel returns the innermost Symbol
/// that the position is considered inside of.
/// </summary>
protected abstract ISymbol? GetEnclosingSymbolCore(int position, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Determines if the symbol is accessible from the specified location.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="symbol">The symbol that we are checking to see if it accessible.</param>
/// <returns>
/// True if "symbol is accessible, false otherwise.</returns>
/// <remarks>
/// This method only checks accessibility from the point of view of the accessibility
/// modifiers on symbol and its containing types. Even if true is returned, the given symbol
/// may not be able to be referenced for other reasons, such as name hiding.
/// </remarks>
public bool IsAccessible(int position, ISymbol symbol)
{
return IsAccessibleCore(position, symbol);
}
/// <summary>
/// Determines if the symbol is accessible from the specified location.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="symbol">The symbol that we are checking to see if it accessible.</param>
/// <returns>
/// True if "symbol is accessible, false otherwise.</returns>
/// <remarks>
/// This method only checks accessibility from the point of view of the accessibility
/// modifiers on symbol and its containing types. Even if true is returned, the given symbol
/// may not be able to be referenced for other reasons, such as name hiding.
/// </remarks>
protected abstract bool IsAccessibleCore(int position, ISymbol symbol);
/// <summary>
/// Field-like events can be used as fields in types that can access private
/// members of the declaring type of the event.
/// </summary>
/// <remarks>
/// Always false for VB events.
/// </remarks>
public bool IsEventUsableAsField(int position, IEventSymbol eventSymbol)
{
return IsEventUsableAsFieldCore(position, eventSymbol);
}
/// <summary>
/// Field-like events can be used as fields in types that can access private
/// members of the declaring type of the event.
/// </summary>
/// <remarks>
/// Always false for VB events.
/// </remarks>
protected abstract bool IsEventUsableAsFieldCore(int position, IEventSymbol eventSymbol);
/// <summary>
/// If <paramref name="nameSyntax"/> is an identifier name syntax node, return the <see cref="PreprocessingSymbolInfo"/> corresponding
/// to it.
/// </summary>
/// <param name="nameSyntax">The nameSyntax node to get semantic information for.</param>
public PreprocessingSymbolInfo GetPreprocessingSymbolInfo(SyntaxNode nameSyntax)
{
return GetPreprocessingSymbolInfoCore(nameSyntax);
}
/// <summary>
/// If <paramref name="nameSyntax"/> is an identifier name syntax node, return the <see cref="PreprocessingSymbolInfo"/> corresponding
/// to it.
/// </summary>
/// <param name="nameSyntax">The nameSyntax node to get semantic information for.</param>
protected abstract PreprocessingSymbolInfo GetPreprocessingSymbolInfoCore(SyntaxNode nameSyntax);
/// <summary>
/// Gets the <see cref="DeclarationInfo"/> for all the declarations whose span overlaps with the given <paramref name="span"/>.
/// </summary>
/// <param name="span">Span to get declarations.</param>
/// <param name="getSymbol">Flag indicating whether <see cref="DeclarationInfo.DeclaredSymbol"/> should be computed for the returned declaration infos.
/// If false, then <see cref="DeclarationInfo.DeclaredSymbol"/> is always null.</param>
/// <param name="builder">Builder to add declarations.</param>
/// <param name="cancellationToken">Cancellation token.</param>
internal abstract void ComputeDeclarationsInSpan(TextSpan span, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken);
/// <summary>
/// Takes a node and returns a set of declarations that overlap the node's span.
/// </summary>
internal abstract void ComputeDeclarationsInNode(SyntaxNode node, ISymbol associatedSymbol, bool getSymbol, ArrayBuilder<DeclarationInfo> builder, CancellationToken cancellationToken, int? levelsToCompute = null);
internal virtual Func<SyntaxNode, bool>? GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) => null;
/// <summary>
/// Takes a Symbol and syntax for one of its declaring syntax reference and returns the topmost syntax node to be used by syntax analyzer.
/// </summary>
protected internal virtual SyntaxNode GetTopmostNodeForDiagnosticAnalysis(ISymbol symbol, SyntaxNode declaringSyntax)
{
return declaringSyntax;
}
/// <summary>
/// Root of this semantic model
/// </summary>
internal SyntaxNode Root => RootCore;
/// <summary>
/// Root of this semantic model
/// </summary>
protected abstract SyntaxNode RootCore { get; }
/// <summary>
/// Gets the <see cref="NullableContext"/> at a position in the file.
/// </summary>
/// <param name="position">The position to get the context for.</param>
public abstract NullableContext GetNullableContext(int position);
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Packaging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddPackage
{
internal class InstallPackageDirectlyCodeAction : CodeAction
{
private readonly CodeActionOperation _installPackageOperation;
public override string Title { get; }
public InstallPackageDirectlyCodeAction(
IPackageInstallerService installerService,
Document document,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
bool isLocal)
{
Title = versionOpt == null
? FeaturesResources.Find_and_install_latest_version
: isLocal
? string.Format(FeaturesResources.Use_local_version_0, versionOpt)
: string.Format(FeaturesResources.Install_version_0, versionOpt);
_installPackageOperation = new InstallPackageDirectlyCodeActionOperation(
installerService, document, source, packageName,
versionOpt, includePrerelease, isLocal);
}
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> Task.FromResult(SpecializedCollections.SingletonEnumerable(_installPackageOperation));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Packaging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddPackage
{
internal class InstallPackageDirectlyCodeAction : CodeAction
{
private readonly CodeActionOperation _installPackageOperation;
public override string Title { get; }
public InstallPackageDirectlyCodeAction(
IPackageInstallerService installerService,
Document document,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
bool isLocal)
{
Title = versionOpt == null
? FeaturesResources.Find_and_install_latest_version
: isLocal
? string.Format(FeaturesResources.Use_local_version_0, versionOpt)
: string.Format(FeaturesResources.Install_version_0, versionOpt);
_installPackageOperation = new InstallPackageDirectlyCodeActionOperation(
installerService, document, source, packageName,
versionOpt, includePrerelease, isLocal);
}
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> Task.FromResult(SpecializedCollections.SingletonEnumerable(_installPackageOperation));
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/CodeStyle/NotificationOption2_operators.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal sealed partial class NotificationOption2
{
[return: NotNullIfNotNull("notificationOption")]
public static explicit operator NotificationOption2?(NotificationOption? notificationOption)
{
if (notificationOption is null)
{
return null;
}
return notificationOption.Severity switch
{
ReportDiagnostic.Suppress => None,
ReportDiagnostic.Hidden => Silent,
ReportDiagnostic.Info => Suggestion,
ReportDiagnostic.Warn => Warning,
ReportDiagnostic.Error => Error,
_ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity),
};
}
[return: NotNullIfNotNull("notificationOption")]
public static explicit operator NotificationOption?(NotificationOption2? notificationOption)
{
if (notificationOption is null)
{
return null;
}
return notificationOption.Severity switch
{
ReportDiagnostic.Suppress => NotificationOption.None,
ReportDiagnostic.Hidden => NotificationOption.Silent,
ReportDiagnostic.Info => NotificationOption.Suggestion,
ReportDiagnostic.Warn => NotificationOption.Warning,
ReportDiagnostic.Error => NotificationOption.Error,
_ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity),
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal sealed partial class NotificationOption2
{
[return: NotNullIfNotNull("notificationOption")]
public static explicit operator NotificationOption2?(NotificationOption? notificationOption)
{
if (notificationOption is null)
{
return null;
}
return notificationOption.Severity switch
{
ReportDiagnostic.Suppress => None,
ReportDiagnostic.Hidden => Silent,
ReportDiagnostic.Info => Suggestion,
ReportDiagnostic.Warn => Warning,
ReportDiagnostic.Error => Error,
_ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity),
};
}
[return: NotNullIfNotNull("notificationOption")]
public static explicit operator NotificationOption?(NotificationOption2? notificationOption)
{
if (notificationOption is null)
{
return null;
}
return notificationOption.Severity switch
{
ReportDiagnostic.Suppress => NotificationOption.None,
ReportDiagnostic.Hidden => NotificationOption.Silent,
ReportDiagnostic.Info => NotificationOption.Suggestion,
ReportDiagnostic.Warn => NotificationOption.Warning,
ReportDiagnostic.Error => NotificationOption.Error,
_ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity),
};
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SyntaxGeneratorExtensions
{
public static IMethodSymbol CreateBaseDelegatingConstructor(
this SyntaxGenerator factory,
IMethodSymbol constructor,
string typeName)
{
// Create a constructor that calls the base constructor. Note: if there are no
// parameters then don't bother writing out "base()" it's automatically implied.
return CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
typeName: typeName,
parameters: constructor.Parameters,
statements: default,
baseConstructorArguments: constructor.Parameters.Length == 0
? default
: factory.CreateArguments(constructor.Parameters));
}
public static ImmutableArray<ISymbol> CreateMemberDelegatingConstructor(
this SyntaxGenerator factory,
SemanticModel semanticModel,
string typeName,
INamedTypeSymbol containingTypeOpt,
ImmutableArray<IParameterSymbol> parameters,
ImmutableDictionary<string, ISymbol> parameterToExistingMemberMap,
ImmutableDictionary<string, string> parameterToNewMemberMap,
bool addNullChecks,
bool preferThrowExpression,
bool generateProperties,
bool isContainedInUnsafeType)
{
var newMembers = generateProperties
? CreatePropertiesForParameters(parameters, parameterToNewMemberMap, isContainedInUnsafeType)
: CreateFieldsForParameters(parameters, parameterToNewMemberMap, isContainedInUnsafeType);
var statements = factory.CreateAssignmentStatements(
semanticModel, parameters, parameterToExistingMemberMap, parameterToNewMemberMap,
addNullChecks, preferThrowExpression).SelectAsArray(
s => s.WithAdditionalAnnotations(Simplifier.Annotation));
var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: containingTypeOpt.IsAbstractClass() ? Accessibility.Protected : Accessibility.Public,
modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameters.Any(p => p.RequiresUnsafeModifier())),
typeName: typeName,
parameters: parameters,
statements: statements,
thisConstructorArguments: ShouldGenerateThisConstructorCall(containingTypeOpt, parameterToExistingMemberMap)
? ImmutableArray<SyntaxNode>.Empty
: default);
return newMembers.Concat(constructor);
}
private static bool ShouldGenerateThisConstructorCall(
INamedTypeSymbol containingTypeOpt,
IDictionary<string, ISymbol> parameterToExistingFieldMap)
{
if (containingTypeOpt != null && containingTypeOpt.TypeKind == TypeKind.Struct)
{
// Special case. If we're generating a struct constructor, then we'll need
// to initialize all fields in the struct, not just the ones we're creating.
// If there is any field or auto-property not being set by a parameter, we
// call the default constructor.
return containingTypeOpt.GetMembers()
.OfType<IFieldSymbol>()
.Where(field => !field.IsStatic)
.Select(field => field.AssociatedSymbol ?? field)
.Except(parameterToExistingFieldMap.Values)
.Any();
}
return false;
}
public static ImmutableArray<ISymbol> CreateFieldsForParameters(
ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterToNewFieldMap, bool isContainedInUnsafeType)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var result);
foreach (var parameter in parameters)
{
// For non-out parameters, create a field and assign the parameter to it.
if (parameter.RefKind != RefKind.Out &&
TryGetValue(parameterToNewFieldMap, parameter.Name, out var fieldName))
{
result.Add(CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default,
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameter.RequiresUnsafeModifier()),
type: parameter.Type,
name: fieldName));
}
}
return result.ToImmutable();
}
public static ImmutableArray<ISymbol> CreatePropertiesForParameters(
ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterToNewPropertyMap, bool isContainedInUnsafeType)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var result);
foreach (var parameter in parameters)
{
// For non-out parameters, create a property and assign the parameter to it.
if (parameter.RefKind != RefKind.Out &&
TryGetValue(parameterToNewPropertyMap, parameter.Name, out var propertyName))
{
result.Add(CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameter.RequiresUnsafeModifier()),
type: parameter.Type,
refKind: RefKind.None,
explicitInterfaceImplementations: ImmutableArray<IPropertySymbol>.Empty,
name: propertyName,
parameters: ImmutableArray<IParameterSymbol>.Empty,
getMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default,
accessibility: default,
statements: default),
setMethod: null));
}
}
return result.ToImmutable();
}
private static bool TryGetValue(IDictionary<string, string> dictionary, string key, out string value)
{
value = null;
return
dictionary != null &&
dictionary.TryGetValue(key, out value);
}
private static bool TryGetValue(IDictionary<string, ISymbol> dictionary, string key, out string value)
{
value = null;
if (dictionary != null && dictionary.TryGetValue(key, out var symbol))
{
value = symbol.Name;
return true;
}
return false;
}
public static SyntaxNode CreateThrowArgumentNullExpression(this SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter)
=> factory.ThrowExpression(CreateNewArgumentNullException(factory, compilation, parameter));
private static SyntaxNode CreateNewArgumentNullException(SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter)
=> factory.ObjectCreationExpression(
compilation.GetTypeByMetadataName(typeof(ArgumentNullException).FullName),
factory.NameOfExpression(
factory.IdentifierName(parameter.Name))).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);
public static SyntaxNode CreateNullCheckAndThrowStatement(
this SyntaxGenerator factory,
SemanticModel semanticModel,
IParameterSymbol parameter)
{
var condition = factory.CreateNullCheckExpression(semanticModel, parameter.Name);
var throwStatement = factory.CreateThrowArgumentNullExceptionStatement(semanticModel.Compilation, parameter);
// generates: if (s is null) { throw new ArgumentNullException(nameof(s)); }
return factory.IfStatement(
condition,
SpecializedCollections.SingletonEnumerable(throwStatement));
}
public static SyntaxNode CreateThrowArgumentNullExceptionStatement(this SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter)
=> factory.ThrowStatement(CreateNewArgumentNullException(factory, compilation, parameter));
public static SyntaxNode CreateNullCheckExpression(this SyntaxGenerator factory, SemanticModel semanticModel, string identifierName)
{
var identifier = factory.IdentifierName(identifierName);
var nullExpr = factory.NullLiteralExpression();
var condition = factory.SyntaxGeneratorInternal.SupportsPatterns(semanticModel.SyntaxTree.Options)
? factory.SyntaxGeneratorInternal.IsPatternExpression(identifier, factory.SyntaxGeneratorInternal.ConstantPattern(nullExpr))
: factory.ReferenceEqualsExpression(identifier, nullExpr);
return condition;
}
public static ImmutableArray<SyntaxNode> CreateAssignmentStatements(
this SyntaxGenerator factory,
SemanticModel semanticModel,
ImmutableArray<IParameterSymbol> parameters,
IDictionary<string, ISymbol> parameterToExistingFieldMap,
IDictionary<string, string> parameterToNewFieldMap,
bool addNullChecks,
bool preferThrowExpression)
{
var nullCheckStatements = ArrayBuilder<SyntaxNode>.GetInstance();
var assignStatements = ArrayBuilder<SyntaxNode>.GetInstance();
foreach (var parameter in parameters)
{
var refKind = parameter.RefKind;
var parameterType = parameter.Type;
var parameterName = parameter.Name;
if (refKind == RefKind.Out)
{
// If it's an out param, then don't create a field for it. Instead, assign
// the default value for that type (i.e. "default(...)") to it.
var assignExpression = factory.AssignmentStatement(
factory.IdentifierName(parameterName),
factory.DefaultExpression(parameterType));
var statement = factory.ExpressionStatement(assignExpression);
assignStatements.Add(statement);
}
else
{
// For non-out parameters, create a field and assign the parameter to it.
// TODO: I'm not sure that's what we really want for ref parameters.
if (TryGetValue(parameterToExistingFieldMap, parameterName, out var fieldName) ||
TryGetValue(parameterToNewFieldMap, parameterName, out fieldName))
{
var fieldAccess = factory.MemberAccessExpression(factory.ThisExpression(), factory.IdentifierName(fieldName))
.WithAdditionalAnnotations(Simplifier.Annotation);
factory.AddAssignmentStatements(
semanticModel, parameter, fieldAccess,
addNullChecks, preferThrowExpression,
nullCheckStatements, assignStatements);
}
}
}
return nullCheckStatements.ToImmutableAndFree().Concat(assignStatements.ToImmutableAndFree());
}
public static void AddAssignmentStatements(
this SyntaxGenerator factory,
SemanticModel semanticModel,
IParameterSymbol parameter,
SyntaxNode fieldAccess,
bool addNullChecks,
bool preferThrowExpression,
ArrayBuilder<SyntaxNode> nullCheckStatements,
ArrayBuilder<SyntaxNode> assignStatements)
{
// Don't want to add a null check for something of the form `int?`. The type was
// already declared as nullable to indicate that null is ok. Adding a null check
// just disallows something that should be allowed.
var shouldAddNullCheck = addNullChecks && parameter.Type.CanAddNullCheck() && !parameter.Type.IsNullable();
if (shouldAddNullCheck && preferThrowExpression && factory.SupportsThrowExpression())
{
// Generate: this.x = x ?? throw ...
assignStatements.Add(CreateAssignWithNullCheckStatement(
factory, semanticModel.Compilation, parameter, fieldAccess));
}
else
{
if (shouldAddNullCheck)
{
// generate: if (x == null) throw ...
nullCheckStatements.Add(
factory.CreateNullCheckAndThrowStatement(semanticModel, parameter));
}
// generate: this.x = x;
assignStatements.Add(
factory.ExpressionStatement(
factory.AssignmentStatement(
fieldAccess,
factory.IdentifierName(parameter.Name))));
}
}
public static SyntaxNode CreateAssignWithNullCheckStatement(
this SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter, SyntaxNode fieldAccess)
{
return factory.ExpressionStatement(factory.AssignmentStatement(
fieldAccess,
factory.CoalesceExpression(
factory.IdentifierName(parameter.Name),
factory.CreateThrowArgumentNullExpression(compilation, parameter))));
}
public static async Task<IPropertySymbol> OverridePropertyAsync(
this SyntaxGenerator codeFactory,
IPropertySymbol overriddenProperty,
DeclarationModifiers modifiers,
INamedTypeSymbol containingType,
Document document,
CancellationToken cancellationToken)
{
var getAccessibility = overriddenProperty.GetMethod.ComputeResultantAccessibility(containingType);
var setAccessibility = overriddenProperty.SetMethod.ComputeResultantAccessibility(containingType);
SyntaxNode getBody;
SyntaxNode setBody;
// Implement an abstract property by throwing not implemented in accessors.
if (overriddenProperty.IsAbstract)
{
var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var statement = codeFactory.CreateThrowNotImplementedStatement(compilation);
getBody = statement;
setBody = statement;
}
else if (overriddenProperty.IsIndexer() && document.Project.Language == LanguageNames.CSharp)
{
// Indexer: return or set base[]. Only in C#, since VB must refer to these by name.
getBody = codeFactory.ReturnStatement(
WrapWithRefIfNecessary(codeFactory, overriddenProperty,
codeFactory.ElementAccessExpression(
codeFactory.BaseExpression(),
codeFactory.CreateArguments(overriddenProperty.Parameters))));
setBody = codeFactory.ExpressionStatement(
codeFactory.AssignmentStatement(
codeFactory.ElementAccessExpression(
codeFactory.BaseExpression(),
codeFactory.CreateArguments(overriddenProperty.Parameters)),
codeFactory.IdentifierName("value")));
}
else if (overriddenProperty.GetParameters().Any())
{
// Call accessors directly if C# overriding VB
if (document.Project.Language == LanguageNames.CSharp
&& (await SymbolFinder.FindSourceDefinitionAsync(overriddenProperty, document.Project.Solution, cancellationToken).ConfigureAwait(false))
.Language == LanguageNames.VisualBasic)
{
var getName = overriddenProperty.GetMethod?.Name;
var setName = overriddenProperty.SetMethod?.Name;
getBody = getName == null
? null
: codeFactory.ReturnStatement(
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(getName)),
codeFactory.CreateArguments(overriddenProperty.Parameters)));
setBody = setName == null
? null
: codeFactory.ExpressionStatement(
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(setName)),
codeFactory.CreateArguments(overriddenProperty.SetMethod.GetParameters())));
}
else
{
getBody = codeFactory.ReturnStatement(
WrapWithRefIfNecessary(codeFactory, overriddenProperty,
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name)), codeFactory.CreateArguments(overriddenProperty.Parameters))));
setBody = codeFactory.ExpressionStatement(
codeFactory.AssignmentStatement(
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name)), codeFactory.CreateArguments(overriddenProperty.Parameters)),
codeFactory.IdentifierName("value")));
}
}
else
{
// Regular property: return or set the base property
getBody = codeFactory.ReturnStatement(
WrapWithRefIfNecessary(codeFactory, overriddenProperty,
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name))));
setBody = codeFactory.ExpressionStatement(
codeFactory.AssignmentStatement(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name)),
codeFactory.IdentifierName("value")));
}
// Only generate a getter if the base getter is accessible.
IMethodSymbol accessorGet = null;
if (overriddenProperty.GetMethod != null && overriddenProperty.GetMethod.IsAccessibleWithin(containingType))
{
accessorGet = CodeGenerationSymbolFactory.CreateMethodSymbol(
overriddenProperty.GetMethod,
accessibility: getAccessibility,
statements: ImmutableArray.Create(getBody),
modifiers: modifiers);
}
// Only generate a setter if the base setter is accessible.
IMethodSymbol accessorSet = null;
if (overriddenProperty.SetMethod != null &&
overriddenProperty.SetMethod.IsAccessibleWithin(containingType) &&
overriddenProperty.SetMethod.DeclaredAccessibility != Accessibility.Private)
{
accessorSet = CodeGenerationSymbolFactory.CreateMethodSymbol(
overriddenProperty.SetMethod,
accessibility: setAccessibility,
statements: ImmutableArray.Create(setBody),
modifiers: modifiers);
}
return CodeGenerationSymbolFactory.CreatePropertySymbol(
overriddenProperty,
accessibility: overriddenProperty.ComputeResultantAccessibility(containingType),
modifiers: modifiers,
name: overriddenProperty.Name,
parameters: overriddenProperty.RemoveInaccessibleAttributesAndAttributesOfTypes(containingType).Parameters,
isIndexer: overriddenProperty.IsIndexer(),
getMethod: accessorGet,
setMethod: accessorSet);
}
private static SyntaxNode WrapWithRefIfNecessary(SyntaxGenerator codeFactory, IPropertySymbol overriddenProperty, SyntaxNode body)
=> overriddenProperty.ReturnsByRef
? codeFactory.RefExpression(body)
: body;
public static IEventSymbol OverrideEvent(
IEventSymbol overriddenEvent,
DeclarationModifiers modifiers,
INamedTypeSymbol newContainingType)
{
return CodeGenerationSymbolFactory.CreateEventSymbol(
overriddenEvent,
attributes: default,
accessibility: overriddenEvent.ComputeResultantAccessibility(newContainingType),
modifiers: modifiers,
explicitInterfaceImplementations: default,
name: overriddenEvent.Name);
}
public static async Task<ISymbol> OverrideAsync(
this SyntaxGenerator generator,
ISymbol symbol,
INamedTypeSymbol containingType,
Document document,
DeclarationModifiers? modifiersOpt = null,
CancellationToken cancellationToken = default)
{
var modifiers = modifiersOpt ?? GetOverrideModifiers(symbol);
if (symbol is IMethodSymbol method)
{
return await generator.OverrideMethodAsync(method,
modifiers, containingType, document, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol property)
{
return await generator.OverridePropertyAsync(property,
modifiers, containingType, document, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IEventSymbol ev)
{
return OverrideEvent(ev, modifiers, containingType);
}
else
{
throw ExceptionUtilities.Unreachable;
}
}
private static DeclarationModifiers GetOverrideModifiers(ISymbol symbol)
=> symbol.GetSymbolModifiers()
.WithIsOverride(true)
.WithIsAbstract(false)
.WithIsVirtual(false);
private static async Task<IMethodSymbol> OverrideMethodAsync(
this SyntaxGenerator codeFactory,
IMethodSymbol overriddenMethod,
DeclarationModifiers modifiers,
INamedTypeSymbol newContainingType,
Document newDocument,
CancellationToken cancellationToken)
{
// Abstract: Throw not implemented
if (overriddenMethod.IsAbstract)
{
var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var statement = codeFactory.CreateThrowNotImplementedStatement(compilation);
return CodeGenerationSymbolFactory.CreateMethodSymbol(
overriddenMethod,
accessibility: overriddenMethod.ComputeResultantAccessibility(newContainingType),
modifiers: modifiers,
statements: ImmutableArray.Create(statement));
}
else
{
// Otherwise, call the base method with the same parameters
var typeParams = overriddenMethod.GetTypeArguments();
var body = codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(codeFactory.BaseExpression(),
typeParams.IsDefaultOrEmpty
? codeFactory.IdentifierName(overriddenMethod.Name)
: codeFactory.GenericName(overriddenMethod.Name, typeParams)),
codeFactory.CreateArguments(overriddenMethod.GetParameters()));
if (overriddenMethod.ReturnsByRef)
{
body = codeFactory.RefExpression(body);
}
return CodeGenerationSymbolFactory.CreateMethodSymbol(
method: overriddenMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(newContainingType),
accessibility: overriddenMethod.ComputeResultantAccessibility(newContainingType),
modifiers: modifiers,
statements: overriddenMethod.ReturnsVoid
? ImmutableArray.Create(codeFactory.ExpressionStatement(body))
: ImmutableArray.Create(codeFactory.ReturnStatement(body)));
}
}
/// <summary>
/// Generates a call to a method *through* an existing field or property symbol.
/// </summary>
/// <returns></returns>
public static SyntaxNode GenerateDelegateThroughMemberStatement(
this SyntaxGenerator generator, IMethodSymbol method, ISymbol throughMember)
{
var through = CreateDelegateThroughExpression(generator, method, throughMember);
var memberName = method.IsGenericMethod
? generator.GenericName(method.Name, method.TypeArguments)
: generator.IdentifierName(method.Name);
through = generator.MemberAccessExpression(through, memberName);
var arguments = generator.CreateArguments(method.Parameters.As<IParameterSymbol>());
var invocationExpression = generator.InvocationExpression(through, arguments);
return method.ReturnsVoid
? generator.ExpressionStatement(invocationExpression)
: generator.ReturnStatement(invocationExpression);
}
public static SyntaxNode CreateDelegateThroughExpression(
this SyntaxGenerator generator, ISymbol member, ISymbol throughMember)
{
var through = throughMember.IsStatic
? GenerateContainerName(generator, throughMember)
: generator.ThisExpression();
through = generator.MemberAccessExpression(
through, generator.IdentifierName(throughMember.Name));
var throughMemberType = throughMember.GetMemberType();
if (member.ContainingType.IsInterfaceType() && throughMemberType != null)
{
// In the case of 'implement interface through field / property', we need to know what
// interface we are implementing so that we can insert casts to this interface on every
// usage of the field in the generated code. Without these casts we would end up generating
// code that fails compilation in certain situations.
//
// For example consider the following code.
// class C : IReadOnlyList<int> { int[] field; }
// When applying the 'implement interface through field' code fix in the above example,
// we need to generate the following code to implement the Count property on IReadOnlyList<int>
// class C : IReadOnlyList<int> { int[] field; int Count { get { ((IReadOnlyList<int>)field).Count; } ...}
// as opposed to the following code which will fail to compile (because the array field
// doesn't have a property named .Count) -
// class C : IReadOnlyList<int> { int[] field; int Count { get { field.Count; } ...}
//
// The 'InterfaceTypes' property on the state object always contains only one item
// in the case of C# i.e. it will contain exactly the interface we are trying to implement.
// This is also the case most of the time in the case of VB, except in certain error conditions
// (recursive / circular cases) where the span of the squiggle for the corresponding
// diagnostic (BC30149) changes and 'InterfaceTypes' ends up including all interfaces
// in the Implements clause. For the purposes of inserting the above cast, we ignore the
// uncommon case and optimize for the common one - in other words, we only apply the cast
// in cases where we can unambiguously figure out which interface we are trying to implement.
var interfaceBeingImplemented = member.ContainingType;
if (!throughMemberType.Equals(interfaceBeingImplemented))
{
through = generator.CastExpression(interfaceBeingImplemented,
through.WithAdditionalAnnotations(Simplifier.Annotation));
}
else if (!throughMember.IsStatic &&
throughMember is IPropertySymbol throughMemberProperty &&
throughMemberProperty.ExplicitInterfaceImplementations.Any())
{
// If we are implementing through an explicitly implemented property, we need to cast 'this' to
// the explicitly implemented interface type before calling the member, as in:
// ((IA)this).Prop.Member();
//
var explicitlyImplementedProperty = throughMemberProperty.ExplicitInterfaceImplementations[0];
var explicitImplementationCast = generator.CastExpression(
explicitlyImplementedProperty.ContainingType,
generator.ThisExpression());
through = generator.MemberAccessExpression(explicitImplementationCast,
generator.IdentifierName(explicitlyImplementedProperty.Name));
through = through.WithAdditionalAnnotations(Simplifier.Annotation);
}
}
return through.WithAdditionalAnnotations(Simplifier.Annotation);
// local functions
static SyntaxNode GenerateContainerName(SyntaxGenerator factory, ISymbol throughMember)
{
var classOrStructType = throughMember.ContainingType;
return classOrStructType.IsGenericType
? factory.GenericName(classOrStructType.Name, classOrStructType.TypeArguments)
: factory.IdentifierName(classOrStructType.Name);
}
}
public static ImmutableArray<SyntaxNode> GetGetAccessorStatements(
this SyntaxGenerator generator, Compilation compilation,
IPropertySymbol property, ISymbol throughMember, bool preferAutoProperties)
{
if (throughMember != null)
{
var throughExpression = CreateDelegateThroughExpression(generator, property, throughMember);
var expression = property.IsIndexer
? throughExpression
: generator.MemberAccessExpression(
throughExpression, generator.IdentifierName(property.Name));
if (property.Parameters.Length > 0)
{
var arguments = generator.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = generator.ElementAccessExpression(expression, arguments);
}
return ImmutableArray.Create(generator.ReturnStatement(expression));
}
return preferAutoProperties ? default : generator.CreateThrowNotImplementedStatementBlock(compilation);
}
public static ImmutableArray<SyntaxNode> GetSetAccessorStatements(
this SyntaxGenerator generator, Compilation compilation,
IPropertySymbol property, ISymbol throughMember, bool preferAutoProperties)
{
if (throughMember != null)
{
var throughExpression = CreateDelegateThroughExpression(generator, property, throughMember);
var expression = property.IsIndexer
? throughExpression
: generator.MemberAccessExpression(
throughExpression, generator.IdentifierName(property.Name));
if (property.Parameters.Length > 0)
{
var arguments = generator.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = generator.ElementAccessExpression(expression, arguments);
}
expression = generator.AssignmentStatement(expression, generator.IdentifierName("value"));
return ImmutableArray.Create(generator.ExpressionStatement(expression));
}
return preferAutoProperties
? default
: generator.CreateThrowNotImplementedStatementBlock(compilation);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SyntaxGeneratorExtensions
{
public static IMethodSymbol CreateBaseDelegatingConstructor(
this SyntaxGenerator factory,
IMethodSymbol constructor,
string typeName)
{
// Create a constructor that calls the base constructor. Note: if there are no
// parameters then don't bother writing out "base()" it's automatically implied.
return CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
typeName: typeName,
parameters: constructor.Parameters,
statements: default,
baseConstructorArguments: constructor.Parameters.Length == 0
? default
: factory.CreateArguments(constructor.Parameters));
}
public static ImmutableArray<ISymbol> CreateMemberDelegatingConstructor(
this SyntaxGenerator factory,
SemanticModel semanticModel,
string typeName,
INamedTypeSymbol containingTypeOpt,
ImmutableArray<IParameterSymbol> parameters,
ImmutableDictionary<string, ISymbol> parameterToExistingMemberMap,
ImmutableDictionary<string, string> parameterToNewMemberMap,
bool addNullChecks,
bool preferThrowExpression,
bool generateProperties,
bool isContainedInUnsafeType)
{
var newMembers = generateProperties
? CreatePropertiesForParameters(parameters, parameterToNewMemberMap, isContainedInUnsafeType)
: CreateFieldsForParameters(parameters, parameterToNewMemberMap, isContainedInUnsafeType);
var statements = factory.CreateAssignmentStatements(
semanticModel, parameters, parameterToExistingMemberMap, parameterToNewMemberMap,
addNullChecks, preferThrowExpression).SelectAsArray(
s => s.WithAdditionalAnnotations(Simplifier.Annotation));
var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: containingTypeOpt.IsAbstractClass() ? Accessibility.Protected : Accessibility.Public,
modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameters.Any(p => p.RequiresUnsafeModifier())),
typeName: typeName,
parameters: parameters,
statements: statements,
thisConstructorArguments: ShouldGenerateThisConstructorCall(containingTypeOpt, parameterToExistingMemberMap)
? ImmutableArray<SyntaxNode>.Empty
: default);
return newMembers.Concat(constructor);
}
private static bool ShouldGenerateThisConstructorCall(
INamedTypeSymbol containingTypeOpt,
IDictionary<string, ISymbol> parameterToExistingFieldMap)
{
if (containingTypeOpt != null && containingTypeOpt.TypeKind == TypeKind.Struct)
{
// Special case. If we're generating a struct constructor, then we'll need
// to initialize all fields in the struct, not just the ones we're creating.
// If there is any field or auto-property not being set by a parameter, we
// call the default constructor.
return containingTypeOpt.GetMembers()
.OfType<IFieldSymbol>()
.Where(field => !field.IsStatic)
.Select(field => field.AssociatedSymbol ?? field)
.Except(parameterToExistingFieldMap.Values)
.Any();
}
return false;
}
public static ImmutableArray<ISymbol> CreateFieldsForParameters(
ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterToNewFieldMap, bool isContainedInUnsafeType)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var result);
foreach (var parameter in parameters)
{
// For non-out parameters, create a field and assign the parameter to it.
if (parameter.RefKind != RefKind.Out &&
TryGetValue(parameterToNewFieldMap, parameter.Name, out var fieldName))
{
result.Add(CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default,
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameter.RequiresUnsafeModifier()),
type: parameter.Type,
name: fieldName));
}
}
return result.ToImmutable();
}
public static ImmutableArray<ISymbol> CreatePropertiesForParameters(
ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterToNewPropertyMap, bool isContainedInUnsafeType)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var result);
foreach (var parameter in parameters)
{
// For non-out parameters, create a property and assign the parameter to it.
if (parameter.RefKind != RefKind.Out &&
TryGetValue(parameterToNewPropertyMap, parameter.Name, out var propertyName))
{
result.Add(CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isUnsafe: !isContainedInUnsafeType && parameter.RequiresUnsafeModifier()),
type: parameter.Type,
refKind: RefKind.None,
explicitInterfaceImplementations: ImmutableArray<IPropertySymbol>.Empty,
name: propertyName,
parameters: ImmutableArray<IParameterSymbol>.Empty,
getMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default,
accessibility: default,
statements: default),
setMethod: null));
}
}
return result.ToImmutable();
}
private static bool TryGetValue(IDictionary<string, string> dictionary, string key, out string value)
{
value = null;
return
dictionary != null &&
dictionary.TryGetValue(key, out value);
}
private static bool TryGetValue(IDictionary<string, ISymbol> dictionary, string key, out string value)
{
value = null;
if (dictionary != null && dictionary.TryGetValue(key, out var symbol))
{
value = symbol.Name;
return true;
}
return false;
}
public static SyntaxNode CreateThrowArgumentNullExpression(this SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter)
=> factory.ThrowExpression(CreateNewArgumentNullException(factory, compilation, parameter));
private static SyntaxNode CreateNewArgumentNullException(SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter)
=> factory.ObjectCreationExpression(
compilation.GetTypeByMetadataName(typeof(ArgumentNullException).FullName),
factory.NameOfExpression(
factory.IdentifierName(parameter.Name))).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);
public static SyntaxNode CreateNullCheckAndThrowStatement(
this SyntaxGenerator factory,
SemanticModel semanticModel,
IParameterSymbol parameter)
{
var condition = factory.CreateNullCheckExpression(semanticModel, parameter.Name);
var throwStatement = factory.CreateThrowArgumentNullExceptionStatement(semanticModel.Compilation, parameter);
// generates: if (s is null) { throw new ArgumentNullException(nameof(s)); }
return factory.IfStatement(
condition,
SpecializedCollections.SingletonEnumerable(throwStatement));
}
public static SyntaxNode CreateThrowArgumentNullExceptionStatement(this SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter)
=> factory.ThrowStatement(CreateNewArgumentNullException(factory, compilation, parameter));
public static SyntaxNode CreateNullCheckExpression(this SyntaxGenerator factory, SemanticModel semanticModel, string identifierName)
{
var identifier = factory.IdentifierName(identifierName);
var nullExpr = factory.NullLiteralExpression();
var condition = factory.SyntaxGeneratorInternal.SupportsPatterns(semanticModel.SyntaxTree.Options)
? factory.SyntaxGeneratorInternal.IsPatternExpression(identifier, factory.SyntaxGeneratorInternal.ConstantPattern(nullExpr))
: factory.ReferenceEqualsExpression(identifier, nullExpr);
return condition;
}
public static ImmutableArray<SyntaxNode> CreateAssignmentStatements(
this SyntaxGenerator factory,
SemanticModel semanticModel,
ImmutableArray<IParameterSymbol> parameters,
IDictionary<string, ISymbol> parameterToExistingFieldMap,
IDictionary<string, string> parameterToNewFieldMap,
bool addNullChecks,
bool preferThrowExpression)
{
var nullCheckStatements = ArrayBuilder<SyntaxNode>.GetInstance();
var assignStatements = ArrayBuilder<SyntaxNode>.GetInstance();
foreach (var parameter in parameters)
{
var refKind = parameter.RefKind;
var parameterType = parameter.Type;
var parameterName = parameter.Name;
if (refKind == RefKind.Out)
{
// If it's an out param, then don't create a field for it. Instead, assign
// the default value for that type (i.e. "default(...)") to it.
var assignExpression = factory.AssignmentStatement(
factory.IdentifierName(parameterName),
factory.DefaultExpression(parameterType));
var statement = factory.ExpressionStatement(assignExpression);
assignStatements.Add(statement);
}
else
{
// For non-out parameters, create a field and assign the parameter to it.
// TODO: I'm not sure that's what we really want for ref parameters.
if (TryGetValue(parameterToExistingFieldMap, parameterName, out var fieldName) ||
TryGetValue(parameterToNewFieldMap, parameterName, out fieldName))
{
var fieldAccess = factory.MemberAccessExpression(factory.ThisExpression(), factory.IdentifierName(fieldName))
.WithAdditionalAnnotations(Simplifier.Annotation);
factory.AddAssignmentStatements(
semanticModel, parameter, fieldAccess,
addNullChecks, preferThrowExpression,
nullCheckStatements, assignStatements);
}
}
}
return nullCheckStatements.ToImmutableAndFree().Concat(assignStatements.ToImmutableAndFree());
}
public static void AddAssignmentStatements(
this SyntaxGenerator factory,
SemanticModel semanticModel,
IParameterSymbol parameter,
SyntaxNode fieldAccess,
bool addNullChecks,
bool preferThrowExpression,
ArrayBuilder<SyntaxNode> nullCheckStatements,
ArrayBuilder<SyntaxNode> assignStatements)
{
// Don't want to add a null check for something of the form `int?`. The type was
// already declared as nullable to indicate that null is ok. Adding a null check
// just disallows something that should be allowed.
var shouldAddNullCheck = addNullChecks && parameter.Type.CanAddNullCheck() && !parameter.Type.IsNullable();
if (shouldAddNullCheck && preferThrowExpression && factory.SupportsThrowExpression())
{
// Generate: this.x = x ?? throw ...
assignStatements.Add(CreateAssignWithNullCheckStatement(
factory, semanticModel.Compilation, parameter, fieldAccess));
}
else
{
if (shouldAddNullCheck)
{
// generate: if (x == null) throw ...
nullCheckStatements.Add(
factory.CreateNullCheckAndThrowStatement(semanticModel, parameter));
}
// generate: this.x = x;
assignStatements.Add(
factory.ExpressionStatement(
factory.AssignmentStatement(
fieldAccess,
factory.IdentifierName(parameter.Name))));
}
}
public static SyntaxNode CreateAssignWithNullCheckStatement(
this SyntaxGenerator factory, Compilation compilation, IParameterSymbol parameter, SyntaxNode fieldAccess)
{
return factory.ExpressionStatement(factory.AssignmentStatement(
fieldAccess,
factory.CoalesceExpression(
factory.IdentifierName(parameter.Name),
factory.CreateThrowArgumentNullExpression(compilation, parameter))));
}
public static async Task<IPropertySymbol> OverridePropertyAsync(
this SyntaxGenerator codeFactory,
IPropertySymbol overriddenProperty,
DeclarationModifiers modifiers,
INamedTypeSymbol containingType,
Document document,
CancellationToken cancellationToken)
{
var getAccessibility = overriddenProperty.GetMethod.ComputeResultantAccessibility(containingType);
var setAccessibility = overriddenProperty.SetMethod.ComputeResultantAccessibility(containingType);
SyntaxNode getBody;
SyntaxNode setBody;
// Implement an abstract property by throwing not implemented in accessors.
if (overriddenProperty.IsAbstract)
{
var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var statement = codeFactory.CreateThrowNotImplementedStatement(compilation);
getBody = statement;
setBody = statement;
}
else if (overriddenProperty.IsIndexer() && document.Project.Language == LanguageNames.CSharp)
{
// Indexer: return or set base[]. Only in C#, since VB must refer to these by name.
getBody = codeFactory.ReturnStatement(
WrapWithRefIfNecessary(codeFactory, overriddenProperty,
codeFactory.ElementAccessExpression(
codeFactory.BaseExpression(),
codeFactory.CreateArguments(overriddenProperty.Parameters))));
setBody = codeFactory.ExpressionStatement(
codeFactory.AssignmentStatement(
codeFactory.ElementAccessExpression(
codeFactory.BaseExpression(),
codeFactory.CreateArguments(overriddenProperty.Parameters)),
codeFactory.IdentifierName("value")));
}
else if (overriddenProperty.GetParameters().Any())
{
// Call accessors directly if C# overriding VB
if (document.Project.Language == LanguageNames.CSharp
&& (await SymbolFinder.FindSourceDefinitionAsync(overriddenProperty, document.Project.Solution, cancellationToken).ConfigureAwait(false))
.Language == LanguageNames.VisualBasic)
{
var getName = overriddenProperty.GetMethod?.Name;
var setName = overriddenProperty.SetMethod?.Name;
getBody = getName == null
? null
: codeFactory.ReturnStatement(
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(getName)),
codeFactory.CreateArguments(overriddenProperty.Parameters)));
setBody = setName == null
? null
: codeFactory.ExpressionStatement(
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(setName)),
codeFactory.CreateArguments(overriddenProperty.SetMethod.GetParameters())));
}
else
{
getBody = codeFactory.ReturnStatement(
WrapWithRefIfNecessary(codeFactory, overriddenProperty,
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name)), codeFactory.CreateArguments(overriddenProperty.Parameters))));
setBody = codeFactory.ExpressionStatement(
codeFactory.AssignmentStatement(
codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name)), codeFactory.CreateArguments(overriddenProperty.Parameters)),
codeFactory.IdentifierName("value")));
}
}
else
{
// Regular property: return or set the base property
getBody = codeFactory.ReturnStatement(
WrapWithRefIfNecessary(codeFactory, overriddenProperty,
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name))));
setBody = codeFactory.ExpressionStatement(
codeFactory.AssignmentStatement(
codeFactory.MemberAccessExpression(
codeFactory.BaseExpression(),
codeFactory.IdentifierName(overriddenProperty.Name)),
codeFactory.IdentifierName("value")));
}
// Only generate a getter if the base getter is accessible.
IMethodSymbol accessorGet = null;
if (overriddenProperty.GetMethod != null && overriddenProperty.GetMethod.IsAccessibleWithin(containingType))
{
accessorGet = CodeGenerationSymbolFactory.CreateMethodSymbol(
overriddenProperty.GetMethod,
accessibility: getAccessibility,
statements: ImmutableArray.Create(getBody),
modifiers: modifiers);
}
// Only generate a setter if the base setter is accessible.
IMethodSymbol accessorSet = null;
if (overriddenProperty.SetMethod != null &&
overriddenProperty.SetMethod.IsAccessibleWithin(containingType) &&
overriddenProperty.SetMethod.DeclaredAccessibility != Accessibility.Private)
{
accessorSet = CodeGenerationSymbolFactory.CreateMethodSymbol(
overriddenProperty.SetMethod,
accessibility: setAccessibility,
statements: ImmutableArray.Create(setBody),
modifiers: modifiers);
}
return CodeGenerationSymbolFactory.CreatePropertySymbol(
overriddenProperty,
accessibility: overriddenProperty.ComputeResultantAccessibility(containingType),
modifiers: modifiers,
name: overriddenProperty.Name,
parameters: overriddenProperty.RemoveInaccessibleAttributesAndAttributesOfTypes(containingType).Parameters,
isIndexer: overriddenProperty.IsIndexer(),
getMethod: accessorGet,
setMethod: accessorSet);
}
private static SyntaxNode WrapWithRefIfNecessary(SyntaxGenerator codeFactory, IPropertySymbol overriddenProperty, SyntaxNode body)
=> overriddenProperty.ReturnsByRef
? codeFactory.RefExpression(body)
: body;
public static IEventSymbol OverrideEvent(
IEventSymbol overriddenEvent,
DeclarationModifiers modifiers,
INamedTypeSymbol newContainingType)
{
return CodeGenerationSymbolFactory.CreateEventSymbol(
overriddenEvent,
attributes: default,
accessibility: overriddenEvent.ComputeResultantAccessibility(newContainingType),
modifiers: modifiers,
explicitInterfaceImplementations: default,
name: overriddenEvent.Name);
}
public static async Task<ISymbol> OverrideAsync(
this SyntaxGenerator generator,
ISymbol symbol,
INamedTypeSymbol containingType,
Document document,
DeclarationModifiers? modifiersOpt = null,
CancellationToken cancellationToken = default)
{
var modifiers = modifiersOpt ?? GetOverrideModifiers(symbol);
if (symbol is IMethodSymbol method)
{
return await generator.OverrideMethodAsync(method,
modifiers, containingType, document, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol property)
{
return await generator.OverridePropertyAsync(property,
modifiers, containingType, document, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IEventSymbol ev)
{
return OverrideEvent(ev, modifiers, containingType);
}
else
{
throw ExceptionUtilities.Unreachable;
}
}
private static DeclarationModifiers GetOverrideModifiers(ISymbol symbol)
=> symbol.GetSymbolModifiers()
.WithIsOverride(true)
.WithIsAbstract(false)
.WithIsVirtual(false);
private static async Task<IMethodSymbol> OverrideMethodAsync(
this SyntaxGenerator codeFactory,
IMethodSymbol overriddenMethod,
DeclarationModifiers modifiers,
INamedTypeSymbol newContainingType,
Document newDocument,
CancellationToken cancellationToken)
{
// Abstract: Throw not implemented
if (overriddenMethod.IsAbstract)
{
var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var statement = codeFactory.CreateThrowNotImplementedStatement(compilation);
return CodeGenerationSymbolFactory.CreateMethodSymbol(
overriddenMethod,
accessibility: overriddenMethod.ComputeResultantAccessibility(newContainingType),
modifiers: modifiers,
statements: ImmutableArray.Create(statement));
}
else
{
// Otherwise, call the base method with the same parameters
var typeParams = overriddenMethod.GetTypeArguments();
var body = codeFactory.InvocationExpression(
codeFactory.MemberAccessExpression(codeFactory.BaseExpression(),
typeParams.IsDefaultOrEmpty
? codeFactory.IdentifierName(overriddenMethod.Name)
: codeFactory.GenericName(overriddenMethod.Name, typeParams)),
codeFactory.CreateArguments(overriddenMethod.GetParameters()));
if (overriddenMethod.ReturnsByRef)
{
body = codeFactory.RefExpression(body);
}
return CodeGenerationSymbolFactory.CreateMethodSymbol(
method: overriddenMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(newContainingType),
accessibility: overriddenMethod.ComputeResultantAccessibility(newContainingType),
modifiers: modifiers,
statements: overriddenMethod.ReturnsVoid
? ImmutableArray.Create(codeFactory.ExpressionStatement(body))
: ImmutableArray.Create(codeFactory.ReturnStatement(body)));
}
}
/// <summary>
/// Generates a call to a method *through* an existing field or property symbol.
/// </summary>
/// <returns></returns>
public static SyntaxNode GenerateDelegateThroughMemberStatement(
this SyntaxGenerator generator, IMethodSymbol method, ISymbol throughMember)
{
var through = CreateDelegateThroughExpression(generator, method, throughMember);
var memberName = method.IsGenericMethod
? generator.GenericName(method.Name, method.TypeArguments)
: generator.IdentifierName(method.Name);
through = generator.MemberAccessExpression(through, memberName);
var arguments = generator.CreateArguments(method.Parameters.As<IParameterSymbol>());
var invocationExpression = generator.InvocationExpression(through, arguments);
return method.ReturnsVoid
? generator.ExpressionStatement(invocationExpression)
: generator.ReturnStatement(invocationExpression);
}
public static SyntaxNode CreateDelegateThroughExpression(
this SyntaxGenerator generator, ISymbol member, ISymbol throughMember)
{
var through = throughMember.IsStatic
? GenerateContainerName(generator, throughMember)
: generator.ThisExpression();
through = generator.MemberAccessExpression(
through, generator.IdentifierName(throughMember.Name));
var throughMemberType = throughMember.GetMemberType();
if (member.ContainingType.IsInterfaceType() && throughMemberType != null)
{
// In the case of 'implement interface through field / property', we need to know what
// interface we are implementing so that we can insert casts to this interface on every
// usage of the field in the generated code. Without these casts we would end up generating
// code that fails compilation in certain situations.
//
// For example consider the following code.
// class C : IReadOnlyList<int> { int[] field; }
// When applying the 'implement interface through field' code fix in the above example,
// we need to generate the following code to implement the Count property on IReadOnlyList<int>
// class C : IReadOnlyList<int> { int[] field; int Count { get { ((IReadOnlyList<int>)field).Count; } ...}
// as opposed to the following code which will fail to compile (because the array field
// doesn't have a property named .Count) -
// class C : IReadOnlyList<int> { int[] field; int Count { get { field.Count; } ...}
//
// The 'InterfaceTypes' property on the state object always contains only one item
// in the case of C# i.e. it will contain exactly the interface we are trying to implement.
// This is also the case most of the time in the case of VB, except in certain error conditions
// (recursive / circular cases) where the span of the squiggle for the corresponding
// diagnostic (BC30149) changes and 'InterfaceTypes' ends up including all interfaces
// in the Implements clause. For the purposes of inserting the above cast, we ignore the
// uncommon case and optimize for the common one - in other words, we only apply the cast
// in cases where we can unambiguously figure out which interface we are trying to implement.
var interfaceBeingImplemented = member.ContainingType;
if (!throughMemberType.Equals(interfaceBeingImplemented))
{
through = generator.CastExpression(interfaceBeingImplemented,
through.WithAdditionalAnnotations(Simplifier.Annotation));
}
else if (!throughMember.IsStatic &&
throughMember is IPropertySymbol throughMemberProperty &&
throughMemberProperty.ExplicitInterfaceImplementations.Any())
{
// If we are implementing through an explicitly implemented property, we need to cast 'this' to
// the explicitly implemented interface type before calling the member, as in:
// ((IA)this).Prop.Member();
//
var explicitlyImplementedProperty = throughMemberProperty.ExplicitInterfaceImplementations[0];
var explicitImplementationCast = generator.CastExpression(
explicitlyImplementedProperty.ContainingType,
generator.ThisExpression());
through = generator.MemberAccessExpression(explicitImplementationCast,
generator.IdentifierName(explicitlyImplementedProperty.Name));
through = through.WithAdditionalAnnotations(Simplifier.Annotation);
}
}
return through.WithAdditionalAnnotations(Simplifier.Annotation);
// local functions
static SyntaxNode GenerateContainerName(SyntaxGenerator factory, ISymbol throughMember)
{
var classOrStructType = throughMember.ContainingType;
return classOrStructType.IsGenericType
? factory.GenericName(classOrStructType.Name, classOrStructType.TypeArguments)
: factory.IdentifierName(classOrStructType.Name);
}
}
public static ImmutableArray<SyntaxNode> GetGetAccessorStatements(
this SyntaxGenerator generator, Compilation compilation,
IPropertySymbol property, ISymbol throughMember, bool preferAutoProperties)
{
if (throughMember != null)
{
var throughExpression = CreateDelegateThroughExpression(generator, property, throughMember);
var expression = property.IsIndexer
? throughExpression
: generator.MemberAccessExpression(
throughExpression, generator.IdentifierName(property.Name));
if (property.Parameters.Length > 0)
{
var arguments = generator.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = generator.ElementAccessExpression(expression, arguments);
}
return ImmutableArray.Create(generator.ReturnStatement(expression));
}
return preferAutoProperties ? default : generator.CreateThrowNotImplementedStatementBlock(compilation);
}
public static ImmutableArray<SyntaxNode> GetSetAccessorStatements(
this SyntaxGenerator generator, Compilation compilation,
IPropertySymbol property, ISymbol throughMember, bool preferAutoProperties)
{
if (throughMember != null)
{
var throughExpression = CreateDelegateThroughExpression(generator, property, throughMember);
var expression = property.IsIndexer
? throughExpression
: generator.MemberAccessExpression(
throughExpression, generator.IdentifierName(property.Name));
if (property.Parameters.Length > 0)
{
var arguments = generator.CreateArguments(property.Parameters.As<IParameterSymbol>());
expression = generator.ElementAccessExpression(expression, arguments);
}
expression = generator.AssignmentStatement(expression, generator.IdentifierName("value"));
return ImmutableArray.Create(generator.ExpressionStatement(expression));
}
return preferAutoProperties
? default
: generator.CreateThrowNotImplementedStatementBlock(compilation);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Operations/VisualBasicOperationFactory_QueryLambdaRewriter.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.BoundTreeVisitor
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.Operations
Partial Friend NotInheritable Class VisualBasicOperationFactory
Private Shared Function RewriteQueryLambda(node As BoundQueryLambda) As BoundNode
' We rewrite query lambda into regular lambda with 2 passes.
' Pass 1 uses helper methods from LocalRewriter to do the lowering. This introduces large number of DAGs.
' Pass 2 walks over the lowered tree and replaces duplicate bound nodes in the tree with their clones - this is a requirement for the Operation tree.
' Note that the rewriter also rewrites all the query lambdas inside the body of this query lambda.
Dim pass1Rewriter As New QueryLambdaRewriterPass1
Dim rewrittenLambda As BoundLambda = DirectCast(pass1Rewriter.VisitQueryLambda(node), BoundLambda)
Dim pass2Rewriter As New QueryLambdaRewriterPass2
Return pass2Rewriter.VisitLambda(rewrittenLambda)
End Function
Private NotInheritable Class QueryLambdaRewriterPass1
Inherits BoundTreeRewriterWithStackGuard
Private _rangeVariableMap As Dictionary(Of RangeVariableSymbol, BoundExpression)
Public Sub New()
_rangeVariableMap = Nothing
End Sub
Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean
' We can reach this code path from a public API (SemanticModel.GetOperation),
' hence we prefer to throw the CLR InsufficientExecutionStackException instead of our internal CancelledByStackGuardException
Return False
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
LocalRewriter.PopulateRangeVariableMapForQueryLambdaRewrite(node, _rangeVariableMap, inExpressionLambda:=True)
Dim rewrittenBody As BoundExpression = VisitExpressionWithStackGuard(node.Expression)
Dim rewrittenStatement As BoundStatement = LocalRewriter.CreateReturnStatementForQueryLambdaBody(rewrittenBody, node, hasErrors:=node.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate)
LocalRewriter.RemoveRangeVariables(node, _rangeVariableMap)
Return LocalRewriter.RewriteQueryLambda(rewrittenStatement, node)
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Dim expression As BoundExpression = Nothing
If Not _rangeVariableMap.TryGetValue(node.RangeVariable, expression) Then
' _rangeVariableMap might not contain an entry for the range variable for error cases.
Return node
End If
' Range variable reference should be rewritten to a parameter reference or a property access.
' We clone these bound nodes in QueryLambdaRewriterPass2 to avoid dag in the generated bound tree.
' If the LocalRewriter is changed to generate more kind of bound nodes for range variables, we should handle these in QueryLambdaRewriterPass2.
' Below assert helps us to stay in sync with the LocalRewriter.
Select Case expression.Kind
Case BoundKind.Parameter
Dim parameter = DirectCast(expression, BoundParameter)
expression = New BoundParameter(node.Syntax, parameter.ParameterSymbol, parameter.IsLValue, parameter.SuppressVirtualCalls, parameter.Type, parameter.HasErrors)
Case BoundKind.PropertyAccess
Dim access = DirectCast(expression, BoundPropertyAccess)
expression = New BoundPropertyAccess(node.Syntax, access.PropertySymbol, access.PropertyGroupOpt, access.AccessKind,
access.IsWriteable, access.IsWriteable, access.ReceiverOpt, access.Arguments,
access.DefaultArguments, access.Type, access.HasErrors)
Case Else
Debug.Fail($"Unexpected bound kind '{expression.Kind}' generated for range variable rewrite by method '{NameOf(LocalRewriter.PopulateRangeVariableMapForQueryLambdaRewrite)}'")
End Select
If node.WasCompilerGenerated Then
expression.SetWasCompilerGenerated()
End If
Return expression
End Function
End Class
Private NotInheritable Class QueryLambdaRewriterPass2
Inherits BoundTreeRewriterWithStackGuard
Private ReadOnly _uniqueNodes As New HashSet(Of BoundParameter)
Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean
' We can reach this code path from a public API (SemanticModel.GetOperation),
' hence we prefer to throw the CLR InsufficientExecutionStackException instead of our internal CancelledByStackGuardException
Return False
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
If If(node.ParameterSymbol?.ContainingSymbol.IsQueryLambdaMethod, False) AndAlso Not _uniqueNodes.Add(node) Then
Dim wasCompilerGenerated As Boolean = node.WasCompilerGenerated
node = New BoundParameter(node.Syntax, node.ParameterSymbol, node.IsLValue, node.SuppressVirtualCalls, node.Type, node.HasErrors)
If wasCompilerGenerated Then
node.MakeCompilerGenerated()
End If
End If
Return node
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.BoundTreeVisitor
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.Operations
Partial Friend NotInheritable Class VisualBasicOperationFactory
Private Shared Function RewriteQueryLambda(node As BoundQueryLambda) As BoundNode
' We rewrite query lambda into regular lambda with 2 passes.
' Pass 1 uses helper methods from LocalRewriter to do the lowering. This introduces large number of DAGs.
' Pass 2 walks over the lowered tree and replaces duplicate bound nodes in the tree with their clones - this is a requirement for the Operation tree.
' Note that the rewriter also rewrites all the query lambdas inside the body of this query lambda.
Dim pass1Rewriter As New QueryLambdaRewriterPass1
Dim rewrittenLambda As BoundLambda = DirectCast(pass1Rewriter.VisitQueryLambda(node), BoundLambda)
Dim pass2Rewriter As New QueryLambdaRewriterPass2
Return pass2Rewriter.VisitLambda(rewrittenLambda)
End Function
Private NotInheritable Class QueryLambdaRewriterPass1
Inherits BoundTreeRewriterWithStackGuard
Private _rangeVariableMap As Dictionary(Of RangeVariableSymbol, BoundExpression)
Public Sub New()
_rangeVariableMap = Nothing
End Sub
Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean
' We can reach this code path from a public API (SemanticModel.GetOperation),
' hence we prefer to throw the CLR InsufficientExecutionStackException instead of our internal CancelledByStackGuardException
Return False
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
LocalRewriter.PopulateRangeVariableMapForQueryLambdaRewrite(node, _rangeVariableMap, inExpressionLambda:=True)
Dim rewrittenBody As BoundExpression = VisitExpressionWithStackGuard(node.Expression)
Dim rewrittenStatement As BoundStatement = LocalRewriter.CreateReturnStatementForQueryLambdaBody(rewrittenBody, node, hasErrors:=node.LambdaSymbol.ReturnType Is LambdaSymbol.ReturnTypePendingDelegate)
LocalRewriter.RemoveRangeVariables(node, _rangeVariableMap)
Return LocalRewriter.RewriteQueryLambda(rewrittenStatement, node)
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Dim expression As BoundExpression = Nothing
If Not _rangeVariableMap.TryGetValue(node.RangeVariable, expression) Then
' _rangeVariableMap might not contain an entry for the range variable for error cases.
Return node
End If
' Range variable reference should be rewritten to a parameter reference or a property access.
' We clone these bound nodes in QueryLambdaRewriterPass2 to avoid dag in the generated bound tree.
' If the LocalRewriter is changed to generate more kind of bound nodes for range variables, we should handle these in QueryLambdaRewriterPass2.
' Below assert helps us to stay in sync with the LocalRewriter.
Select Case expression.Kind
Case BoundKind.Parameter
Dim parameter = DirectCast(expression, BoundParameter)
expression = New BoundParameter(node.Syntax, parameter.ParameterSymbol, parameter.IsLValue, parameter.SuppressVirtualCalls, parameter.Type, parameter.HasErrors)
Case BoundKind.PropertyAccess
Dim access = DirectCast(expression, BoundPropertyAccess)
expression = New BoundPropertyAccess(node.Syntax, access.PropertySymbol, access.PropertyGroupOpt, access.AccessKind,
access.IsWriteable, access.IsWriteable, access.ReceiverOpt, access.Arguments,
access.DefaultArguments, access.Type, access.HasErrors)
Case Else
Debug.Fail($"Unexpected bound kind '{expression.Kind}' generated for range variable rewrite by method '{NameOf(LocalRewriter.PopulateRangeVariableMapForQueryLambdaRewrite)}'")
End Select
If node.WasCompilerGenerated Then
expression.SetWasCompilerGenerated()
End If
Return expression
End Function
End Class
Private NotInheritable Class QueryLambdaRewriterPass2
Inherits BoundTreeRewriterWithStackGuard
Private ReadOnly _uniqueNodes As New HashSet(Of BoundParameter)
Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean
' We can reach this code path from a public API (SemanticModel.GetOperation),
' hence we prefer to throw the CLR InsufficientExecutionStackException instead of our internal CancelledByStackGuardException
Return False
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
If If(node.ParameterSymbol?.ContainingSymbol.IsQueryLambdaMethod, False) AndAlso Not _uniqueNodes.Add(node) Then
Dim wasCompilerGenerated As Boolean = node.WasCompilerGenerated
node = New BoundParameter(node.Syntax, node.ParameterSymbol, node.IsLValue, node.SuppressVirtualCalls, node.Type, node.HasErrors)
If wasCompilerGenerated Then
node.MakeCompilerGenerated()
End If
End If
Return node
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/TestUtilities/EditorTestCompositions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive;
using Microsoft.CodeAnalysis.Editor.Implementation.Notification;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Fakes;
using Microsoft.CodeAnalysis.UnitTests.Remote;
using Microsoft.VisualStudio.InteractiveWindow;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
public static class EditorTestCompositions
{
public static readonly TestComposition Editor = TestComposition.Empty
.AddAssemblies(
// Microsoft.VisualStudio.Platform.VSEditor.dll:
Assembly.LoadFrom("Microsoft.VisualStudio.Platform.VSEditor.dll"),
// Microsoft.VisualStudio.Text.Logic.dll:
// Must include this because several editor options are actually stored as exported information
// on this DLL. Including most importantly, the tab size information.
typeof(VisualStudio.Text.Editor.DefaultOptions).Assembly,
// Microsoft.VisualStudio.Text.UI.dll:
// Include this DLL to get several more EditorOptions including WordWrapStyle.
typeof(VisualStudio.Text.Editor.WordWrapStyle).Assembly,
// Microsoft.VisualStudio.Text.UI.Wpf.dll:
// Include this DLL to get more EditorOptions values.
typeof(VisualStudio.Text.Editor.HighlightCurrentLineOption).Assembly,
// BasicUndo.dll:
// Include this DLL to satisfy ITextUndoHistoryRegistry
typeof(BasicUndo.IBasicUndoHistory).Assembly,
// Microsoft.VisualStudio.Language.StandardClassification.dll:
typeof(VisualStudio.Language.StandardClassification.PredefinedClassificationTypeNames).Assembly,
// Microsoft.VisualStudio.Language
typeof(VisualStudio.Language.Intellisense.AsyncCompletion.IAsyncCompletionBroker).Assembly,
// Microsoft.VisualStudio.CoreUtility
typeof(VisualStudio.Utilities.IFeatureServiceFactory).Assembly,
// Microsoft.VisualStudio.Text.Internal
typeof(VisualStudio.Text.Utilities.IExperimentationServiceInternal).Assembly)
.AddParts(
typeof(TestSerializerService.Factory),
typeof(TestExportJoinableTaskContext),
typeof(StubStreamingFindUsagesPresenter), // actual implementation is in VS layer
typeof(EditorNotificationServiceFactory), // TODO: use mock INotificationService instead (https://github.com/dotnet/roslyn/issues/46045)
typeof(TestObscuringTipManager)); // TODO: https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569
public static readonly TestComposition EditorFeatures = FeaturesTestCompositions.Features
.Add(Editor)
.AddAssemblies(
typeof(TextEditorResources).Assembly,
typeof(EditorFeaturesResources).Assembly,
typeof(CSharp.CSharpEditorResources).Assembly,
typeof(VisualBasic.VBEditorResources).Assembly);
public static readonly TestComposition EditorFeaturesWpf = EditorFeatures
.AddAssemblies(
typeof(EditorFeaturesWpfResources).Assembly);
public static readonly TestComposition InteractiveWindow = EditorFeaturesWpf
.AddAssemblies(
typeof(IInteractiveWindow).Assembly)
.AddParts(
typeof(TestInteractiveWindowEditorFactoryService));
public static readonly TestComposition LanguageServerProtocol = EditorFeatures
.AddAssemblies(
typeof(LanguageServerResources).Assembly);
public static readonly TestComposition LanguageServerProtocolWpf = EditorFeaturesWpf
.AddAssemblies(LanguageServerProtocol.Assemblies);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive;
using Microsoft.CodeAnalysis.Editor.Implementation.Notification;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests.Fakes;
using Microsoft.CodeAnalysis.UnitTests.Remote;
using Microsoft.VisualStudio.InteractiveWindow;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
public static class EditorTestCompositions
{
public static readonly TestComposition Editor = TestComposition.Empty
.AddAssemblies(
// Microsoft.VisualStudio.Platform.VSEditor.dll:
Assembly.LoadFrom("Microsoft.VisualStudio.Platform.VSEditor.dll"),
// Microsoft.VisualStudio.Text.Logic.dll:
// Must include this because several editor options are actually stored as exported information
// on this DLL. Including most importantly, the tab size information.
typeof(VisualStudio.Text.Editor.DefaultOptions).Assembly,
// Microsoft.VisualStudio.Text.UI.dll:
// Include this DLL to get several more EditorOptions including WordWrapStyle.
typeof(VisualStudio.Text.Editor.WordWrapStyle).Assembly,
// Microsoft.VisualStudio.Text.UI.Wpf.dll:
// Include this DLL to get more EditorOptions values.
typeof(VisualStudio.Text.Editor.HighlightCurrentLineOption).Assembly,
// BasicUndo.dll:
// Include this DLL to satisfy ITextUndoHistoryRegistry
typeof(BasicUndo.IBasicUndoHistory).Assembly,
// Microsoft.VisualStudio.Language.StandardClassification.dll:
typeof(VisualStudio.Language.StandardClassification.PredefinedClassificationTypeNames).Assembly,
// Microsoft.VisualStudio.Language
typeof(VisualStudio.Language.Intellisense.AsyncCompletion.IAsyncCompletionBroker).Assembly,
// Microsoft.VisualStudio.CoreUtility
typeof(VisualStudio.Utilities.IFeatureServiceFactory).Assembly,
// Microsoft.VisualStudio.Text.Internal
typeof(VisualStudio.Text.Utilities.IExperimentationServiceInternal).Assembly)
.AddParts(
typeof(TestSerializerService.Factory),
typeof(TestExportJoinableTaskContext),
typeof(StubStreamingFindUsagesPresenter), // actual implementation is in VS layer
typeof(EditorNotificationServiceFactory), // TODO: use mock INotificationService instead (https://github.com/dotnet/roslyn/issues/46045)
typeof(TestObscuringTipManager)); // TODO: https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569
public static readonly TestComposition EditorFeatures = FeaturesTestCompositions.Features
.Add(Editor)
.AddAssemblies(
typeof(TextEditorResources).Assembly,
typeof(EditorFeaturesResources).Assembly,
typeof(CSharp.CSharpEditorResources).Assembly,
typeof(VisualBasic.VBEditorResources).Assembly);
public static readonly TestComposition EditorFeaturesWpf = EditorFeatures
.AddAssemblies(
typeof(EditorFeaturesWpfResources).Assembly);
public static readonly TestComposition InteractiveWindow = EditorFeaturesWpf
.AddAssemblies(
typeof(IInteractiveWindow).Assembly)
.AddParts(
typeof(TestInteractiveWindowEditorFactoryService));
public static readonly TestComposition LanguageServerProtocol = EditorFeatures
.AddAssemblies(
typeof(LanguageServerResources).Assembly);
public static readonly TestComposition LanguageServerProtocolWpf = EditorFeaturesWpf
.AddAssemblies(LanguageServerProtocol.Assemblies);
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/VisualBasic/Portable/Classification/ClassificationHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification
Friend Module ClassificationHelpers
''' <summary>
''' Return the classification type associated with this token.
''' </summary>
''' <param name="token">The token to be classified.</param>
''' <returns>The classification type for the token</returns>
''' <remarks></remarks>
Public Function GetClassification(token As SyntaxToken) As String
If IsControlKeyword(token) Then
Return ClassificationTypeNames.ControlKeyword
ElseIf SyntaxFacts.IsKeywordKind(token.Kind) Then
Return ClassificationTypeNames.Keyword
ElseIf IsStringToken(token) Then
Return ClassificationTypeNames.StringLiteral
ElseIf SyntaxFacts.IsPunctuation(token.Kind) Then
Return ClassifyPunctuation(token)
ElseIf token.Kind = SyntaxKind.IdentifierToken Then
Return ClassifyIdentifierSyntax(token)
ElseIf token.IsNumericLiteral() Then
Return ClassificationTypeNames.NumericLiteral
ElseIf token.Kind = SyntaxKind.XmlNameToken Then
Return ClassificationTypeNames.XmlLiteralName
ElseIf token.Kind = SyntaxKind.XmlTextLiteralToken Then
Select Case token.Parent.Kind
Case SyntaxKind.XmlString
Return ClassificationTypeNames.XmlLiteralAttributeValue
Case SyntaxKind.XmlProcessingInstruction
Return ClassificationTypeNames.XmlLiteralProcessingInstruction
Case SyntaxKind.XmlComment
Return ClassificationTypeNames.XmlLiteralComment
Case SyntaxKind.XmlCDataSection
Return ClassificationTypeNames.XmlLiteralCDataSection
Case Else
Return ClassificationTypeNames.XmlLiteralText
End Select
ElseIf token.Kind = SyntaxKind.XmlEntityLiteralToken Then
Return ClassificationTypeNames.XmlLiteralEntityReference
ElseIf token.IsKind(SyntaxKind.None, SyntaxKind.BadToken) Then
Return Nothing
Else
throw ExceptionUtilities.UnexpectedValue(token.Kind())
End If
End Function
Private Function IsControlKeyword(token As SyntaxToken) As Boolean
If token.Parent Is Nothing Then
Return False
End If
' For Exit Statments classify everything as a control keyword
If token.Parent.IsKind(
SyntaxKind.ExitFunctionStatement,
SyntaxKind.ExitOperatorStatement,
SyntaxKind.ExitPropertyStatement,
SyntaxKind.ExitSubStatement) Then
Return True
End If
' Control keywords are used in other contexts so check that it is
' being used in a supported context.
Return IsControlKeywordKind(token.Kind) AndAlso
IsControlStatementKind(token.Parent.Kind)
End Function
''' <summary>
''' Determine if the kind represents a control keyword
''' </summary>
Private Function IsControlKeywordKind(kind As SyntaxKind) As Boolean
Select Case kind
Case _
SyntaxKind.CaseKeyword,
SyntaxKind.CatchKeyword,
SyntaxKind.ContinueKeyword,
SyntaxKind.DoKeyword,
SyntaxKind.EachKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.ExitKeyword,
SyntaxKind.FinallyKeyword,
SyntaxKind.ForKeyword,
SyntaxKind.GoToKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.InKeyword,
SyntaxKind.LoopKeyword,
SyntaxKind.NextKeyword,
SyntaxKind.ResumeKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.TryKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.WendKeyword,
SyntaxKind.UntilKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.GosubKeyword,
SyntaxKind.YieldKeyword,
SyntaxKind.ToKeyword
Return True
Case Else
Return False
End Select
End Function
''' <summary>
''' Determine if the kind represents a control statement
''' </summary>
Private Function IsControlStatementKind(kind As SyntaxKind) As Boolean
Select Case kind
Case _
SyntaxKind.CallStatement,
SyntaxKind.CaseElseStatement,
SyntaxKind.CaseStatement,
SyntaxKind.CatchStatement,
SyntaxKind.ContinueDoStatement,
SyntaxKind.ContinueForStatement,
SyntaxKind.ContinueWhileStatement,
SyntaxKind.DoUntilStatement,
SyntaxKind.DoWhileStatement,
SyntaxKind.ElseIfStatement,
SyntaxKind.ElseStatement,
SyntaxKind.EndIfStatement,
SyntaxKind.EndSelectStatement,
SyntaxKind.EndTryStatement,
SyntaxKind.EndWhileStatement,
SyntaxKind.ExitDoStatement,
SyntaxKind.ExitForStatement,
SyntaxKind.ExitSelectStatement,
SyntaxKind.ExitTryStatement,
SyntaxKind.ExitWhileStatement,
SyntaxKind.FinallyStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.ForStatement,
SyntaxKind.GoToStatement,
SyntaxKind.IfStatement,
SyntaxKind.LoopUntilStatement,
SyntaxKind.LoopWhileStatement,
SyntaxKind.NextStatement,
SyntaxKind.ResumeLabelStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ReturnStatement,
SyntaxKind.SelectStatement,
SyntaxKind.SimpleDoStatement,
SyntaxKind.SimpleLoopStatement,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.ThrowStatement,
SyntaxKind.TryStatement,
SyntaxKind.UntilClause,
SyntaxKind.WhileClause,
SyntaxKind.WhileStatement,
SyntaxKind.YieldStatement,
SyntaxKind.TernaryConditionalExpression
Return True
Case Else
Return False
End Select
End Function
Private Function ClassifyPunctuation(token As SyntaxToken) As String
If AllOperators.Contains(token.Kind) Then
' special cases...
Select Case token.Kind
Case SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken
If TypeOf token.Parent Is AttributeListSyntax Then
Return ClassificationTypeNames.Punctuation
End If
End Select
Return ClassificationTypeNames.Operator
Else
Return ClassificationTypeNames.Punctuation
End If
End Function
Private Function ClassifyIdentifierSyntax(identifier As SyntaxToken) As String
'Note: parent might be Nothing, if we are classifying raw tokens.
Dim parent = identifier.Parent
Dim classification As String = Nothing
If TypeOf parent Is IdentifierNameSyntax AndAlso IsNamespaceName(DirectCast(parent, IdentifierNameSyntax)) Then
Return ClassificationTypeNames.NamespaceName
ElseIf TypeOf parent Is TypeStatementSyntax AndAlso DirectCast(parent, TypeStatementSyntax).Identifier = identifier Then
Return ClassifyTypeDeclarationIdentifier(identifier)
ElseIf TypeOf parent Is EnumStatementSyntax AndAlso DirectCast(parent, EnumStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.EnumName
ElseIf TypeOf parent Is DelegateStatementSyntax AndAlso DirectCast(parent, DelegateStatementSyntax).Identifier = identifier AndAlso
(parent.Kind = SyntaxKind.DelegateSubStatement OrElse parent.Kind = SyntaxKind.DelegateFunctionStatement) Then
Return ClassificationTypeNames.DelegateName
ElseIf TypeOf parent Is TypeParameterSyntax AndAlso DirectCast(parent, TypeParameterSyntax).Identifier = identifier Then
Return ClassificationTypeNames.TypeParameterName
ElseIf TypeOf parent Is MethodStatementSyntax AndAlso DirectCast(parent, MethodStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.MethodName
ElseIf TypeOf parent Is DeclareStatementSyntax AndAlso DirectCast(parent, DeclareStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.MethodName
ElseIf TypeOf parent Is PropertyStatementSyntax AndAlso DirectCast(parent, PropertyStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.PropertyName
ElseIf TypeOf parent Is EventStatementSyntax AndAlso DirectCast(parent, EventStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.EventName
ElseIf TypeOf parent Is EnumMemberDeclarationSyntax AndAlso DirectCast(parent, EnumMemberDeclarationSyntax).Identifier = identifier Then
Return ClassificationTypeNames.EnumMemberName
ElseIf TypeOf parent Is LabelStatementSyntax AndAlso DirectCast(parent, LabelStatementSyntax).LabelToken = identifier Then
Return ClassificationTypeNames.LabelName
ElseIf TypeOf parent?.Parent Is CatchStatementSyntax AndAlso DirectCast(parent.Parent, CatchStatementSyntax).IdentifierName.Identifier = identifier Then
Return ClassificationTypeNames.LocalName
ElseIf TryClassifyModifiedIdentifer(parent, identifier, classification) Then
Return classification
ElseIf (identifier.ToString() = "IsTrue" OrElse identifier.ToString() = "IsFalse") AndAlso
TypeOf parent Is OperatorStatementSyntax AndAlso DirectCast(parent, OperatorStatementSyntax).OperatorToken = identifier Then
Return ClassificationTypeNames.Keyword
End If
Return ClassificationTypeNames.Identifier
End Function
Private Function IsNamespaceName(identifierSyntax As IdentifierNameSyntax) As Boolean
Dim parent = identifierSyntax.Parent
While TypeOf parent Is QualifiedNameSyntax
parent = parent.Parent
End While
Return TypeOf parent Is NamespaceStatementSyntax
End Function
Public Function IsStaticallyDeclared(identifier As SyntaxToken) As Boolean
'Note: parent might be Nothing, if we are classifying raw tokens.
Dim parent = identifier.Parent
If parent.IsKind(SyntaxKind.EnumMemberDeclaration) Then
' EnumMembers are not classified as static since there is no
' instance equivalent of the concept and they have their own
' classification type.
Return False
ElseIf parent.IsKind(SyntaxKind.ModifiedIdentifier) Then
parent = parent.Parent?.Parent
' We are specifically looking for field declarations or constants.
If Not parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return False
End If
If parent.GetModifiers().Any(SyntaxKind.ConstKeyword) Then
Return True
End If
End If
Return parent.GetModifiers().Any(SyntaxKind.SharedKeyword)
End Function
Private Function IsStringToken(token As SyntaxToken) As Boolean
If token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.InterpolatedStringTextToken) Then
Return True
End If
Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken) AndAlso
token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression)
End Function
Private Function TryClassifyModifiedIdentifer(node As SyntaxNode, identifier As SyntaxToken, ByRef classification As String) As Boolean
classification = Nothing
If TypeOf node IsNot ModifiedIdentifierSyntax OrElse DirectCast(node, ModifiedIdentifierSyntax).Identifier <> identifier Then
Return False
End If
If TypeOf node.Parent Is ParameterSyntax Then
classification = ClassificationTypeNames.ParameterName
Return True
End If
If TypeOf node.Parent IsNot VariableDeclaratorSyntax Then
Return False
End If
If TypeOf node.Parent.Parent Is LocalDeclarationStatementSyntax Then
Dim localDeclaration = DirectCast(node.Parent.Parent, LocalDeclarationStatementSyntax)
classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.LocalName)
Return True
End If
If TypeOf node.Parent.Parent Is FieldDeclarationSyntax Then
Dim localDeclaration = DirectCast(node.Parent.Parent, FieldDeclarationSyntax)
classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.FieldName)
Return True
End If
Return False
End Function
Private Function ClassifyTypeDeclarationIdentifier(identifier As SyntaxToken) As String
Select Case identifier.Parent.Kind
Case SyntaxKind.ClassStatement
Return ClassificationTypeNames.ClassName
Case SyntaxKind.ModuleStatement
Return ClassificationTypeNames.ModuleName
Case SyntaxKind.InterfaceStatement
Return ClassificationTypeNames.InterfaceName
Case SyntaxKind.StructureStatement
Return ClassificationTypeNames.StructName
Case Else
throw ExceptionUtilities.UnexpectedValue(identifier.Parent.Kind)
End Select
End Function
Friend Sub AddLexicalClassifications(text As SourceText, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken)
Dim text2 = text.ToString(textSpan)
Dim tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition:=textSpan.Start)
Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken)
End Sub
#Disable Warning IDE0060 ' Remove unused parameter - TODO: Do we need to do the same work here that we do in C#?
Friend Function AdjustStaleClassification(text As SourceText, classifiedSpan As ClassifiedSpan) As ClassifiedSpan
#Enable Warning IDE0060 ' Remove unused parameter
Return classifiedSpan
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification
Friend Module ClassificationHelpers
''' <summary>
''' Return the classification type associated with this token.
''' </summary>
''' <param name="token">The token to be classified.</param>
''' <returns>The classification type for the token</returns>
''' <remarks></remarks>
Public Function GetClassification(token As SyntaxToken) As String
If IsControlKeyword(token) Then
Return ClassificationTypeNames.ControlKeyword
ElseIf SyntaxFacts.IsKeywordKind(token.Kind) Then
Return ClassificationTypeNames.Keyword
ElseIf IsStringToken(token) Then
Return ClassificationTypeNames.StringLiteral
ElseIf SyntaxFacts.IsPunctuation(token.Kind) Then
Return ClassifyPunctuation(token)
ElseIf token.Kind = SyntaxKind.IdentifierToken Then
Return ClassifyIdentifierSyntax(token)
ElseIf token.IsNumericLiteral() Then
Return ClassificationTypeNames.NumericLiteral
ElseIf token.Kind = SyntaxKind.XmlNameToken Then
Return ClassificationTypeNames.XmlLiteralName
ElseIf token.Kind = SyntaxKind.XmlTextLiteralToken Then
Select Case token.Parent.Kind
Case SyntaxKind.XmlString
Return ClassificationTypeNames.XmlLiteralAttributeValue
Case SyntaxKind.XmlProcessingInstruction
Return ClassificationTypeNames.XmlLiteralProcessingInstruction
Case SyntaxKind.XmlComment
Return ClassificationTypeNames.XmlLiteralComment
Case SyntaxKind.XmlCDataSection
Return ClassificationTypeNames.XmlLiteralCDataSection
Case Else
Return ClassificationTypeNames.XmlLiteralText
End Select
ElseIf token.Kind = SyntaxKind.XmlEntityLiteralToken Then
Return ClassificationTypeNames.XmlLiteralEntityReference
ElseIf token.IsKind(SyntaxKind.None, SyntaxKind.BadToken) Then
Return Nothing
Else
throw ExceptionUtilities.UnexpectedValue(token.Kind())
End If
End Function
Private Function IsControlKeyword(token As SyntaxToken) As Boolean
If token.Parent Is Nothing Then
Return False
End If
' For Exit Statments classify everything as a control keyword
If token.Parent.IsKind(
SyntaxKind.ExitFunctionStatement,
SyntaxKind.ExitOperatorStatement,
SyntaxKind.ExitPropertyStatement,
SyntaxKind.ExitSubStatement) Then
Return True
End If
' Control keywords are used in other contexts so check that it is
' being used in a supported context.
Return IsControlKeywordKind(token.Kind) AndAlso
IsControlStatementKind(token.Parent.Kind)
End Function
''' <summary>
''' Determine if the kind represents a control keyword
''' </summary>
Private Function IsControlKeywordKind(kind As SyntaxKind) As Boolean
Select Case kind
Case _
SyntaxKind.CaseKeyword,
SyntaxKind.CatchKeyword,
SyntaxKind.ContinueKeyword,
SyntaxKind.DoKeyword,
SyntaxKind.EachKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.ExitKeyword,
SyntaxKind.FinallyKeyword,
SyntaxKind.ForKeyword,
SyntaxKind.GoToKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.InKeyword,
SyntaxKind.LoopKeyword,
SyntaxKind.NextKeyword,
SyntaxKind.ResumeKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.TryKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.WendKeyword,
SyntaxKind.UntilKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.GosubKeyword,
SyntaxKind.YieldKeyword,
SyntaxKind.ToKeyword
Return True
Case Else
Return False
End Select
End Function
''' <summary>
''' Determine if the kind represents a control statement
''' </summary>
Private Function IsControlStatementKind(kind As SyntaxKind) As Boolean
Select Case kind
Case _
SyntaxKind.CallStatement,
SyntaxKind.CaseElseStatement,
SyntaxKind.CaseStatement,
SyntaxKind.CatchStatement,
SyntaxKind.ContinueDoStatement,
SyntaxKind.ContinueForStatement,
SyntaxKind.ContinueWhileStatement,
SyntaxKind.DoUntilStatement,
SyntaxKind.DoWhileStatement,
SyntaxKind.ElseIfStatement,
SyntaxKind.ElseStatement,
SyntaxKind.EndIfStatement,
SyntaxKind.EndSelectStatement,
SyntaxKind.EndTryStatement,
SyntaxKind.EndWhileStatement,
SyntaxKind.ExitDoStatement,
SyntaxKind.ExitForStatement,
SyntaxKind.ExitSelectStatement,
SyntaxKind.ExitTryStatement,
SyntaxKind.ExitWhileStatement,
SyntaxKind.FinallyStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.ForStatement,
SyntaxKind.GoToStatement,
SyntaxKind.IfStatement,
SyntaxKind.LoopUntilStatement,
SyntaxKind.LoopWhileStatement,
SyntaxKind.NextStatement,
SyntaxKind.ResumeLabelStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ReturnStatement,
SyntaxKind.SelectStatement,
SyntaxKind.SimpleDoStatement,
SyntaxKind.SimpleLoopStatement,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.ThrowStatement,
SyntaxKind.TryStatement,
SyntaxKind.UntilClause,
SyntaxKind.WhileClause,
SyntaxKind.WhileStatement,
SyntaxKind.YieldStatement,
SyntaxKind.TernaryConditionalExpression
Return True
Case Else
Return False
End Select
End Function
Private Function ClassifyPunctuation(token As SyntaxToken) As String
If AllOperators.Contains(token.Kind) Then
' special cases...
Select Case token.Kind
Case SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken
If TypeOf token.Parent Is AttributeListSyntax Then
Return ClassificationTypeNames.Punctuation
End If
End Select
Return ClassificationTypeNames.Operator
Else
Return ClassificationTypeNames.Punctuation
End If
End Function
Private Function ClassifyIdentifierSyntax(identifier As SyntaxToken) As String
'Note: parent might be Nothing, if we are classifying raw tokens.
Dim parent = identifier.Parent
Dim classification As String = Nothing
If TypeOf parent Is IdentifierNameSyntax AndAlso IsNamespaceName(DirectCast(parent, IdentifierNameSyntax)) Then
Return ClassificationTypeNames.NamespaceName
ElseIf TypeOf parent Is TypeStatementSyntax AndAlso DirectCast(parent, TypeStatementSyntax).Identifier = identifier Then
Return ClassifyTypeDeclarationIdentifier(identifier)
ElseIf TypeOf parent Is EnumStatementSyntax AndAlso DirectCast(parent, EnumStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.EnumName
ElseIf TypeOf parent Is DelegateStatementSyntax AndAlso DirectCast(parent, DelegateStatementSyntax).Identifier = identifier AndAlso
(parent.Kind = SyntaxKind.DelegateSubStatement OrElse parent.Kind = SyntaxKind.DelegateFunctionStatement) Then
Return ClassificationTypeNames.DelegateName
ElseIf TypeOf parent Is TypeParameterSyntax AndAlso DirectCast(parent, TypeParameterSyntax).Identifier = identifier Then
Return ClassificationTypeNames.TypeParameterName
ElseIf TypeOf parent Is MethodStatementSyntax AndAlso DirectCast(parent, MethodStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.MethodName
ElseIf TypeOf parent Is DeclareStatementSyntax AndAlso DirectCast(parent, DeclareStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.MethodName
ElseIf TypeOf parent Is PropertyStatementSyntax AndAlso DirectCast(parent, PropertyStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.PropertyName
ElseIf TypeOf parent Is EventStatementSyntax AndAlso DirectCast(parent, EventStatementSyntax).Identifier = identifier Then
Return ClassificationTypeNames.EventName
ElseIf TypeOf parent Is EnumMemberDeclarationSyntax AndAlso DirectCast(parent, EnumMemberDeclarationSyntax).Identifier = identifier Then
Return ClassificationTypeNames.EnumMemberName
ElseIf TypeOf parent Is LabelStatementSyntax AndAlso DirectCast(parent, LabelStatementSyntax).LabelToken = identifier Then
Return ClassificationTypeNames.LabelName
ElseIf TypeOf parent?.Parent Is CatchStatementSyntax AndAlso DirectCast(parent.Parent, CatchStatementSyntax).IdentifierName.Identifier = identifier Then
Return ClassificationTypeNames.LocalName
ElseIf TryClassifyModifiedIdentifer(parent, identifier, classification) Then
Return classification
ElseIf (identifier.ToString() = "IsTrue" OrElse identifier.ToString() = "IsFalse") AndAlso
TypeOf parent Is OperatorStatementSyntax AndAlso DirectCast(parent, OperatorStatementSyntax).OperatorToken = identifier Then
Return ClassificationTypeNames.Keyword
End If
Return ClassificationTypeNames.Identifier
End Function
Private Function IsNamespaceName(identifierSyntax As IdentifierNameSyntax) As Boolean
Dim parent = identifierSyntax.Parent
While TypeOf parent Is QualifiedNameSyntax
parent = parent.Parent
End While
Return TypeOf parent Is NamespaceStatementSyntax
End Function
Public Function IsStaticallyDeclared(identifier As SyntaxToken) As Boolean
'Note: parent might be Nothing, if we are classifying raw tokens.
Dim parent = identifier.Parent
If parent.IsKind(SyntaxKind.EnumMemberDeclaration) Then
' EnumMembers are not classified as static since there is no
' instance equivalent of the concept and they have their own
' classification type.
Return False
ElseIf parent.IsKind(SyntaxKind.ModifiedIdentifier) Then
parent = parent.Parent?.Parent
' We are specifically looking for field declarations or constants.
If Not parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return False
End If
If parent.GetModifiers().Any(SyntaxKind.ConstKeyword) Then
Return True
End If
End If
Return parent.GetModifiers().Any(SyntaxKind.SharedKeyword)
End Function
Private Function IsStringToken(token As SyntaxToken) As Boolean
If token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.InterpolatedStringTextToken) Then
Return True
End If
Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken) AndAlso
token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression)
End Function
Private Function TryClassifyModifiedIdentifer(node As SyntaxNode, identifier As SyntaxToken, ByRef classification As String) As Boolean
classification = Nothing
If TypeOf node IsNot ModifiedIdentifierSyntax OrElse DirectCast(node, ModifiedIdentifierSyntax).Identifier <> identifier Then
Return False
End If
If TypeOf node.Parent Is ParameterSyntax Then
classification = ClassificationTypeNames.ParameterName
Return True
End If
If TypeOf node.Parent IsNot VariableDeclaratorSyntax Then
Return False
End If
If TypeOf node.Parent.Parent Is LocalDeclarationStatementSyntax Then
Dim localDeclaration = DirectCast(node.Parent.Parent, LocalDeclarationStatementSyntax)
classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.LocalName)
Return True
End If
If TypeOf node.Parent.Parent Is FieldDeclarationSyntax Then
Dim localDeclaration = DirectCast(node.Parent.Parent, FieldDeclarationSyntax)
classification = If(localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword), ClassificationTypeNames.ConstantName, ClassificationTypeNames.FieldName)
Return True
End If
Return False
End Function
Private Function ClassifyTypeDeclarationIdentifier(identifier As SyntaxToken) As String
Select Case identifier.Parent.Kind
Case SyntaxKind.ClassStatement
Return ClassificationTypeNames.ClassName
Case SyntaxKind.ModuleStatement
Return ClassificationTypeNames.ModuleName
Case SyntaxKind.InterfaceStatement
Return ClassificationTypeNames.InterfaceName
Case SyntaxKind.StructureStatement
Return ClassificationTypeNames.StructName
Case Else
throw ExceptionUtilities.UnexpectedValue(identifier.Parent.Kind)
End Select
End Function
Friend Sub AddLexicalClassifications(text As SourceText, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken)
Dim text2 = text.ToString(textSpan)
Dim tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition:=textSpan.Start)
Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken)
End Sub
#Disable Warning IDE0060 ' Remove unused parameter - TODO: Do we need to do the same work here that we do in C#?
Friend Function AdjustStaleClassification(text As SourceText, classifiedSpan As ClassifiedSpan) As ClassifiedSpan
#Enable Warning IDE0060 ' Remove unused parameter
Return classifiedSpan
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Test/Resources/Core/NetFX/ValueTuple/ValueTuple.cs | // Licensed to the .NET Foundation under one or more 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 System.Numerics.Hashing
{
internal static class HashHelpers
{
public static readonly int RandomSeed = new Random().Next(Int32.MinValue, Int32.MaxValue);
public static int Combine(int h1, int h2)
{
// RyuJIT optimizes this to use the ROL instruction
// Related GitHub pull request: dotnet/coreclr#1830
uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
return ((int)rol5 + h1) ^ h2;
}
}
}
namespace System.Runtime.CompilerServices
{
/// <summary>
/// This interface is required for types that want to be indexed into by dynamic patterns.
/// </summary>
public interface ITuple
{
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int Length { get; }
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object this[int index] { get; }
}
}
namespace System
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using HashHelpers = System.Numerics.Hashing.HashHelpers;
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
internal interface IValueTupleInternal : ITuple
{
int GetHashCode(IEqualityComparer comparer);
string ToStringEnd();
}
/// <summary>
/// The ValueTuple types (from arity 0 to 8) comprise the runtime implementation that underlies tuples in C# and struct tuples in F#.
/// Aside from created via language syntax, they are most easily created via the ValueTuple.Create factory methods.
/// The System.ValueTuple types differ from the System.Tuple types in that:
/// - they are structs rather than classes,
/// - they are mutable rather than readonly, and
/// - their members (such as Item1, Item2, etc) are fields rather than properties.
/// </summary>
[Serializable]
public struct ValueTuple
: IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, IValueTupleInternal, ITuple
{
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="ValueTuple"/>.</returns>
public override bool Equals(object obj)
{
return obj is ValueTuple;
}
/// <summary>Returns a value indicating whether this instance is equal to a specified value.</summary>
/// <param name="other">An instance to compare to this instance.</param>
/// <returns>true if <paramref name="other"/> has the same value as this instance; otherwise, false.</returns>
public bool Equals(ValueTuple other)
{
return true;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
return other is ValueTuple;
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple other)
{
return 0;
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>()</c>.
/// </remarks>
public override string ToString()
{
return "()";
}
string IValueTupleInternal.ToStringEnd()
{
return ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 0;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
throw new IndexOutOfRangeException();
}
}
/// <summary>Creates a new struct 0-tuple.</summary>
/// <returns>A 0-tuple.</returns>
public static ValueTuple Create() =>
new ValueTuple();
/// <summary>Creates a new struct 1-tuple, or singleton.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <returns>A 1-tuple (singleton) whose value is (item1).</returns>
public static ValueTuple<T1> Create<T1>(T1 item1) =>
new ValueTuple<T1>(item1);
/// <summary>Creates a new struct 2-tuple, or pair.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <returns>A 2-tuple (pair) whose value is (item1, item2).</returns>
public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) =>
new ValueTuple<T1, T2>(item1, item2);
/// <summary>Creates a new struct 3-tuple, or triple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <returns>A 3-tuple (triple) whose value is (item1, item2, item3).</returns>
public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) =>
new ValueTuple<T1, T2, T3>(item1, item2, item3);
/// <summary>Creates a new struct 4-tuple, or quadruple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <returns>A 4-tuple (quadruple) whose value is (item1, item2, item3, item4).</returns>
public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) =>
new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4);
/// <summary>Creates a new struct 5-tuple, or quintuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <returns>A 5-tuple (quintuple) whose value is (item1, item2, item3, item4, item5).</returns>
public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) =>
new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
/// <summary>Creates a new struct 6-tuple, or sextuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <returns>A 6-tuple (sextuple) whose value is (item1, item2, item3, item4, item5, item6).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) =>
new ValueTuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
/// <summary>Creates a new struct 7-tuple, or septuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <returns>A 7-tuple (septuple) whose value is (item1, item2, item3, item4, item5, item6, item7).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
/// <summary>Creates a new struct 8-tuple, or octuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <typeparam name="T8">The type of the eighth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <param name="item8">The value of the eighth component of the tuple.</param>
/// <returns>An 8-tuple (octuple) whose value is (item1, item2, item3, item4, item5, item6, item7, item8).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, ValueTuple.Create(item8));
internal static int CombineHashCodes(int h1, int h2)
{
return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
}
internal static int CombineHashCodes(int h1, int h2, int h3)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8);
}
}
/// <summary>Represents a 1-tuple, or singleton, as a value type.</summary>
/// <typeparam name="T1">The type of the tuple's only component.</typeparam>
[Serializable]
public struct ValueTuple<T1>
: IEquatable<ValueTuple<T1>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
public ValueTuple(T1 item1)
{
Item1 = item1;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1> && Equals((ValueTuple<T1>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its field
/// is equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1>)) return false;
var objTuple = (ValueTuple<T1>)other;
return comparer.Equals(Item1, objTuple.Item1);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return Comparer<T1>.Default.Compare(Item1, objTuple.Item1);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1> other)
{
return Comparer<T1>.Default.Compare(Item1, other.Item1);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return comparer.Compare(Item1, objTuple.Item1);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return Item1?.GetHashCode() ?? 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1)</c>,
/// where <c>Item1</c> represents the value of <see cref="Item1"/>. If the field is <see langword="null"/>,
/// it is represented as <see cref="string.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
if (index != 0)
{
throw new IndexOutOfRangeException();
}
return Item1;
}
}
}
/// <summary>
/// Represents a 2-tuple, or pair, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2>
: IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T2 Item2;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2> && Equals((ValueTuple<T1, T2>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified <see cref="ValueTuple{T1, T2}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object based on a specified comparison method.
/// </summary>
/// <param name="other">The object to compare with this instance.</param>
/// <param name="comparer">An object that defines the method to use to evaluate whether the two objects are equal.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// This member is an explicit interface member implementation. It can be used only when the
/// <see cref="ValueTuple{T1, T2}"/> instance is cast to an <see cref="IStructuralEquatable"/> interface.
///
/// The <see cref="IEqualityComparer.Equals"/> implementation is called only if <c>other</c> is not <see langword="null"/>,
/// and if it can be successfully cast (in C#) or converted (in Visual Basic) to a <see cref="ValueTuple{T1, T2}"/>
/// whose components are of the same types as those of the current instance. The IStructuralEquatable.Equals(Object, IEqualityComparer) method
/// first passes the <see cref="Item1"/> values of the <see cref="ValueTuple{T1, T2}"/> objects to be compared to the
/// <see cref="IEqualityComparer.Equals"/> implementation. If this method call returns <see langword="true"/>, the method is
/// called again and passed the <see cref="Item2"/> values of the two <see cref="ValueTuple{T1, T2}"/> instances.
/// </remarks>
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2>)) return false;
var objTuple = (ValueTuple<T1, T2>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
return Comparer<T2>.Default.Compare(Item2, other.Item2);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
return comparer.Compare(Item2, objTuple.Item2);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2)</c>,
/// where <c>Item1</c> and <c>Item2</c> represent the values of the <see cref="Item1"/>
/// and <see cref="Item2"/> fields. If either field value is <see langword="null"/>,
/// it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 2;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 3-tuple, or triple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3>
: IEquatable<ValueTuple<T1, T2, T3>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3> && Equals((ValueTuple<T1, T2, T3>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false;
var objTuple = (ValueTuple<T1, T2, T3>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
return Comparer<T3>.Default.Compare(Item3, other.Item3);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
return comparer.Compare(Item3, objTuple.Item3);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 3;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 4-tuple, or quadruple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4>
: IEquatable<ValueTuple<T1, T2, T3, T4>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4> && Equals((ValueTuple<T1, T2, T3, T4>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
return Comparer<T4>.Default.Compare(Item4, other.Item4);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
return comparer.Compare(Item4, objTuple.Item4);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 4;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 5-tuple, or quintuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5> && Equals((ValueTuple<T1, T2, T3, T4, T5>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
return Comparer<T5>.Default.Compare(Item5, other.Item5);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
return comparer.Compare(Item5, objTuple.Item5);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 5;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 6-tuple, or sixtuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
return Comparer<T6>.Default.Compare(Item6, other.Item6);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
return comparer.Compare(Item6, objTuple.Item6);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 6;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 7-tuple, or sentuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
return Comparer<T7>.Default.Compare(Item7, other.Item7);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
return comparer.Compare(Item7, objTuple.Item7);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 7;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents an 8-tuple, or octuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
/// <typeparam name="TRest">The type of the tuple's eighth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IValueTupleInternal, ITuple
where TRest : struct
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's eighth component.
/// </summary>
public TRest Rest;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
/// <param name="rest">The value of the tuple's eight component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
if (!(rest is IValueTupleInternal))
{
throw new ArgumentException();
}
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
Rest = rest;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7)
&& EqualityComparer<TRest>.Default.Equals(Rest, other.Rest);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7)
&& comparer.Equals(Rest, objTuple.Rest);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
c = Comparer<T7>.Default.Compare(Item7, other.Item7);
if (c != 0) return c;
return Comparer<TRest>.Default.Compare(Rest, other.Rest);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
c = comparer.Compare(Item7, objTuple.Item7);
if (c != 0) return c;
return comparer.Compare(Rest, objTuple.Rest);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 2:
return ValueTuple.CombineHashCodes(Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 3:
return ValueTuple.CombineHashCodes(Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 4:
return ValueTuple.CombineHashCodes(Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 5:
return ValueTuple.CombineHashCodes(Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 6:
return ValueTuple.CombineHashCodes(Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 7:
case 8:
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(comparer); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 2:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 3:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 4:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 5:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 6:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 7:
case 8:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Rest)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
string IValueTupleInternal.ToStringEnd()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length
{
get
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
return rest == null ? 8 : 7 + rest.Length;
}
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
}
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
if (index == 7)
{
return Rest;
}
throw new IndexOutOfRangeException();
}
return rest[index - 7];
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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 System.Numerics.Hashing
{
internal static class HashHelpers
{
public static readonly int RandomSeed = new Random().Next(Int32.MinValue, Int32.MaxValue);
public static int Combine(int h1, int h2)
{
// RyuJIT optimizes this to use the ROL instruction
// Related GitHub pull request: dotnet/coreclr#1830
uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
return ((int)rol5 + h1) ^ h2;
}
}
}
namespace System.Runtime.CompilerServices
{
/// <summary>
/// This interface is required for types that want to be indexed into by dynamic patterns.
/// </summary>
public interface ITuple
{
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int Length { get; }
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object this[int index] { get; }
}
}
namespace System
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using HashHelpers = System.Numerics.Hashing.HashHelpers;
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
internal interface IValueTupleInternal : ITuple
{
int GetHashCode(IEqualityComparer comparer);
string ToStringEnd();
}
/// <summary>
/// The ValueTuple types (from arity 0 to 8) comprise the runtime implementation that underlies tuples in C# and struct tuples in F#.
/// Aside from created via language syntax, they are most easily created via the ValueTuple.Create factory methods.
/// The System.ValueTuple types differ from the System.Tuple types in that:
/// - they are structs rather than classes,
/// - they are mutable rather than readonly, and
/// - their members (such as Item1, Item2, etc) are fields rather than properties.
/// </summary>
[Serializable]
public struct ValueTuple
: IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, IValueTupleInternal, ITuple
{
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="ValueTuple"/>.</returns>
public override bool Equals(object obj)
{
return obj is ValueTuple;
}
/// <summary>Returns a value indicating whether this instance is equal to a specified value.</summary>
/// <param name="other">An instance to compare to this instance.</param>
/// <returns>true if <paramref name="other"/> has the same value as this instance; otherwise, false.</returns>
public bool Equals(ValueTuple other)
{
return true;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
return other is ValueTuple;
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple other)
{
return 0;
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple))
{
throw new ArgumentException();
}
return 0;
}
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return 0;
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>()</c>.
/// </remarks>
public override string ToString()
{
return "()";
}
string IValueTupleInternal.ToStringEnd()
{
return ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 0;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
throw new IndexOutOfRangeException();
}
}
/// <summary>Creates a new struct 0-tuple.</summary>
/// <returns>A 0-tuple.</returns>
public static ValueTuple Create() =>
new ValueTuple();
/// <summary>Creates a new struct 1-tuple, or singleton.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <returns>A 1-tuple (singleton) whose value is (item1).</returns>
public static ValueTuple<T1> Create<T1>(T1 item1) =>
new ValueTuple<T1>(item1);
/// <summary>Creates a new struct 2-tuple, or pair.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <returns>A 2-tuple (pair) whose value is (item1, item2).</returns>
public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) =>
new ValueTuple<T1, T2>(item1, item2);
/// <summary>Creates a new struct 3-tuple, or triple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <returns>A 3-tuple (triple) whose value is (item1, item2, item3).</returns>
public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) =>
new ValueTuple<T1, T2, T3>(item1, item2, item3);
/// <summary>Creates a new struct 4-tuple, or quadruple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <returns>A 4-tuple (quadruple) whose value is (item1, item2, item3, item4).</returns>
public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) =>
new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4);
/// <summary>Creates a new struct 5-tuple, or quintuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <returns>A 5-tuple (quintuple) whose value is (item1, item2, item3, item4, item5).</returns>
public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) =>
new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
/// <summary>Creates a new struct 6-tuple, or sextuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <returns>A 6-tuple (sextuple) whose value is (item1, item2, item3, item4, item5, item6).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) =>
new ValueTuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
/// <summary>Creates a new struct 7-tuple, or septuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <returns>A 7-tuple (septuple) whose value is (item1, item2, item3, item4, item5, item6, item7).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
/// <summary>Creates a new struct 8-tuple, or octuple.</summary>
/// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
/// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
/// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
/// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
/// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
/// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
/// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
/// <typeparam name="T8">The type of the eighth component of the tuple.</typeparam>
/// <param name="item1">The value of the first component of the tuple.</param>
/// <param name="item2">The value of the second component of the tuple.</param>
/// <param name="item3">The value of the third component of the tuple.</param>
/// <param name="item4">The value of the fourth component of the tuple.</param>
/// <param name="item5">The value of the fifth component of the tuple.</param>
/// <param name="item6">The value of the sixth component of the tuple.</param>
/// <param name="item7">The value of the seventh component of the tuple.</param>
/// <param name="item8">The value of the eighth component of the tuple.</param>
/// <returns>An 8-tuple (octuple) whose value is (item1, item2, item3, item4, item5, item6, item7, item8).</returns>
public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) =>
new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, ValueTuple.Create(item8));
internal static int CombineHashCodes(int h1, int h2)
{
return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
}
internal static int CombineHashCodes(int h1, int h2, int h3)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
{
return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8);
}
}
/// <summary>Represents a 1-tuple, or singleton, as a value type.</summary>
/// <typeparam name="T1">The type of the tuple's only component.</typeparam>
[Serializable]
public struct ValueTuple<T1>
: IEquatable<ValueTuple<T1>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
public ValueTuple(T1 item1)
{
Item1 = item1;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1> && Equals((ValueTuple<T1>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its field
/// is equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1>)) return false;
var objTuple = (ValueTuple<T1>)other;
return comparer.Equals(Item1, objTuple.Item1);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return Comparer<T1>.Default.Compare(Item1, objTuple.Item1);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1> other)
{
return Comparer<T1>.Default.Compare(Item1, other.Item1);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1>)other;
return comparer.Compare(Item1, objTuple.Item1);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return Item1?.GetHashCode() ?? 0;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(Item1);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1)</c>,
/// where <c>Item1</c> represents the value of <see cref="Item1"/>. If the field is <see langword="null"/>,
/// it is represented as <see cref="string.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
if (index != 0)
{
throw new IndexOutOfRangeException();
}
return Item1;
}
}
}
/// <summary>
/// Represents a 2-tuple, or pair, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2>
: IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
/// </summary>
public T2 Item2;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2> && Equals((ValueTuple<T1, T2>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified <see cref="ValueTuple{T1, T2}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object based on a specified comparison method.
/// </summary>
/// <param name="other">The object to compare with this instance.</param>
/// <param name="comparer">An object that defines the method to use to evaluate whether the two objects are equal.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
///
/// <remarks>
/// This member is an explicit interface member implementation. It can be used only when the
/// <see cref="ValueTuple{T1, T2}"/> instance is cast to an <see cref="IStructuralEquatable"/> interface.
///
/// The <see cref="IEqualityComparer.Equals"/> implementation is called only if <c>other</c> is not <see langword="null"/>,
/// and if it can be successfully cast (in C#) or converted (in Visual Basic) to a <see cref="ValueTuple{T1, T2}"/>
/// whose components are of the same types as those of the current instance. The IStructuralEquatable.Equals(Object, IEqualityComparer) method
/// first passes the <see cref="Item1"/> values of the <see cref="ValueTuple{T1, T2}"/> objects to be compared to the
/// <see cref="IEqualityComparer.Equals"/> implementation. If this method call returns <see langword="true"/>, the method is
/// called again and passed the <see cref="Item2"/> values of the two <see cref="ValueTuple{T1, T2}"/> instances.
/// </remarks>
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2>)) return false;
var objTuple = (ValueTuple<T1, T2>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
return Comparer<T2>.Default.Compare(Item2, other.Item2);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
return comparer.Compare(Item2, objTuple.Item2);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2)</c>,
/// where <c>Item1</c> and <c>Item2</c> represent the values of the <see cref="Item1"/>
/// and <see cref="Item2"/> fields. If either field value is <see langword="null"/>,
/// it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 2;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 3-tuple, or triple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3>
: IEquatable<ValueTuple<T1, T2, T3>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3> && Equals((ValueTuple<T1, T2, T3>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false;
var objTuple = (ValueTuple<T1, T2, T3>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
return Comparer<T3>.Default.Compare(Item3, other.Item3);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
return comparer.Compare(Item3, objTuple.Item3);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 3;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 4-tuple, or quadruple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4>
: IEquatable<ValueTuple<T1, T2, T3, T4>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4> && Equals((ValueTuple<T1, T2, T3, T4>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
return Comparer<T4>.Default.Compare(Item4, other.Item4);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
return comparer.Compare(Item4, objTuple.Item4);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 4;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 5-tuple, or quintuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5> && Equals((ValueTuple<T1, T2, T3, T4, T5>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
return Comparer<T5>.Default.Compare(Item5, other.Item5);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
return comparer.Compare(Item5, objTuple.Item5);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 5;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 6-tuple, or sixtuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
return Comparer<T6>.Default.Compare(Item6, other.Item6);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
return comparer.Compare(Item6, objTuple.Item6);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 6;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents a 7-tuple, or sentuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IValueTupleInternal, ITuple
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
return Comparer<T7>.Default.Compare(Item7, other.Item7);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
return comparer.Compare(Item7, objTuple.Item7);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
comparer.GetHashCode(Item2),
comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
string IValueTupleInternal.ToStringEnd()
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 7;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
default:
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>
/// Represents an 8-tuple, or octuple, as a value type.
/// </summary>
/// <typeparam name="T1">The type of the tuple's first component.</typeparam>
/// <typeparam name="T2">The type of the tuple's second component.</typeparam>
/// <typeparam name="T3">The type of the tuple's third component.</typeparam>
/// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
/// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
/// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
/// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
/// <typeparam name="TRest">The type of the tuple's eighth component.</typeparam>
[Serializable]
[StructLayout(LayoutKind.Auto)]
public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
: IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IValueTupleInternal, ITuple
where TRest : struct
{
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's first component.
/// </summary>
public T1 Item1;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's second component.
/// </summary>
public T2 Item2;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's third component.
/// </summary>
public T3 Item3;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fourth component.
/// </summary>
public T4 Item4;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fifth component.
/// </summary>
public T5 Item5;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's sixth component.
/// </summary>
public T6 Item6;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's seventh component.
/// </summary>
public T7 Item7;
/// <summary>
/// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's eighth component.
/// </summary>
public TRest Rest;
/// <summary>
/// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.
/// </summary>
/// <param name="item1">The value of the tuple's first component.</param>
/// <param name="item2">The value of the tuple's second component.</param>
/// <param name="item3">The value of the tuple's third component.</param>
/// <param name="item4">The value of the tuple's fourth component.</param>
/// <param name="item5">The value of the tuple's fifth component.</param>
/// <param name="item6">The value of the tuple's sixth component.</param>
/// <param name="item7">The value of the tuple's seventh component.</param>
/// <param name="rest">The value of the tuple's eight component.</param>
public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
if (!(rest is IValueTupleInternal))
{
throw new ArgumentException();
}
Item1 = item1;
Item2 = item2;
Item3 = item3;
Item4 = item4;
Item5 = item5;
Item6 = item6;
Item7 = item7;
Rest = rest;
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
/// <list type="bullet">
/// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.</description></item>
/// <item><description>Its components are of the same types as those of the current instance.</description></item>
/// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
/// </list>
/// </remarks>
public override bool Equals(object obj)
{
return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)obj);
}
/// <summary>
/// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>
/// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>.
/// </summary>
/// <param name="other">The tuple to compare with this instance.</param>
/// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
/// <remarks>
/// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
/// are equal to that of the current instance, using the default comparer for that field's type.
/// </remarks>
public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
&& EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
&& EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
&& EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
&& EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
&& EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
&& EqualityComparer<T7>.Default.Equals(Item7, other.Item7)
&& EqualityComparer<TRest>.Default.Equals(Rest, other.Rest);
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false;
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
return comparer.Equals(Item1, objTuple.Item1)
&& comparer.Equals(Item2, objTuple.Item2)
&& comparer.Equals(Item3, objTuple.Item3)
&& comparer.Equals(Item4, objTuple.Item4)
&& comparer.Equals(Item5, objTuple.Item5)
&& comparer.Equals(Item6, objTuple.Item6)
&& comparer.Equals(Item7, objTuple.Item7)
&& comparer.Equals(Rest, objTuple.Rest);
}
int IComparable.CompareTo(object other)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other);
}
/// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
/// <param name="other">An instance to compare.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and <paramref name="other"/>.
/// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
/// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
/// than <paramref name="other"/>.
/// </returns>
public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
{
int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
if (c != 0) return c;
c = Comparer<T2>.Default.Compare(Item2, other.Item2);
if (c != 0) return c;
c = Comparer<T3>.Default.Compare(Item3, other.Item3);
if (c != 0) return c;
c = Comparer<T4>.Default.Compare(Item4, other.Item4);
if (c != 0) return c;
c = Comparer<T5>.Default.Compare(Item5, other.Item5);
if (c != 0) return c;
c = Comparer<T6>.Default.Compare(Item6, other.Item6);
if (c != 0) return c;
c = Comparer<T7>.Default.Compare(Item7, other.Item7);
if (c != 0) return c;
return Comparer<TRest>.Default.Compare(Rest, other.Rest);
}
int IStructuralComparable.CompareTo(object other, IComparer comparer)
{
if (other == null) return 1;
if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
{
throw new ArgumentException();
}
var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
int c = comparer.Compare(Item1, objTuple.Item1);
if (c != 0) return c;
c = comparer.Compare(Item2, objTuple.Item2);
if (c != 0) return c;
c = comparer.Compare(Item3, objTuple.Item3);
if (c != 0) return c;
c = comparer.Compare(Item4, objTuple.Item4);
if (c != 0) return c;
c = comparer.Compare(Item5, objTuple.Item5);
if (c != 0) return c;
c = comparer.Compare(Item6, objTuple.Item6);
if (c != 0) return c;
c = comparer.Compare(Item7, objTuple.Item7);
if (c != 0) return c;
return comparer.Compare(Rest, objTuple.Rest);
}
/// <summary>
/// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0);
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 2:
return ValueTuple.CombineHashCodes(Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 3:
return ValueTuple.CombineHashCodes(Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 4:
return ValueTuple.CombineHashCodes(Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 5:
return ValueTuple.CombineHashCodes(Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 6:
return ValueTuple.CombineHashCodes(Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
case 7:
case 8:
return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
Item2?.GetHashCode() ?? 0,
Item3?.GetHashCode() ?? 0,
Item4?.GetHashCode() ?? 0,
Item5?.GetHashCode() ?? 0,
Item6?.GetHashCode() ?? 0,
Item7?.GetHashCode() ?? 0,
rest.GetHashCode());
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
private int GetHashCodeCore(IEqualityComparer comparer)
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7));
}
int size = rest.Length;
if (size >= 8) { return rest.GetHashCode(comparer); }
// In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - size;
switch (k)
{
case 1:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 2:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 3:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 4:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 5:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5),
comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
case 6:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4),
comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
rest.GetHashCode(comparer));
case 7:
case 8:
return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
}
Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
return -1;
}
int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
{
return GetHashCodeCore(comparer);
}
/// <summary>
/// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
/// </summary>
/// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.</returns>
/// <remarks>
/// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Rest)</c>.
/// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
/// </remarks>
public override string ToString()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
string IValueTupleInternal.ToStringEnd()
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
}
else
{
return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
}
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length
{
get
{
IValueTupleInternal rest = Rest as IValueTupleInternal;
return rest == null ? 8 : 7 + rest.Length;
}
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
}
IValueTupleInternal rest = Rest as IValueTupleInternal;
if (rest == null)
{
if (index == 7)
{
return Rest;
}
throw new IndexOutOfRangeException();
}
return rest[index - 7];
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/GetXmlNamespaceExpressionDocumentation.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.Utilities.IntrinsicOperators
Friend NotInheritable Class GetXmlNamespaceExpressionDocumentation
Inherits AbstractIntrinsicOperatorDocumentation
Public Overrides Function GetParameterDisplayParts(index As Integer) As IList(Of SymbolDisplayPart)
Select Case index
Case 0
Return {
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "["),
New SymbolDisplayPart(SymbolDisplayPartKind.ParameterName, Nothing, GetParameterName(index)),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "]")
}
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterDocumentation(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterName(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.xmlNamespacePrefix
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 1
End Get
End Property
Public Overrides ReadOnly Property DocumentationText As String
Get
Return VBWorkspaceResources.Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix
End Get
End Property
Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart)
Get
Return {
New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "GetXmlNamespace"),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")
}
End Get
End Property
Public Overrides ReadOnly Property IncludeAsType As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeMetadataName As String
Get
Return "System.Xml.Linq.XNamespace"
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Friend NotInheritable Class GetXmlNamespaceExpressionDocumentation
Inherits AbstractIntrinsicOperatorDocumentation
Public Overrides Function GetParameterDisplayParts(index As Integer) As IList(Of SymbolDisplayPart)
Select Case index
Case 0
Return {
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "["),
New SymbolDisplayPart(SymbolDisplayPartKind.ParameterName, Nothing, GetParameterName(index)),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "]")
}
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterDocumentation(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides Function GetParameterName(index As Integer) As String
Select Case index
Case 0
Return VBWorkspaceResources.xmlNamespacePrefix
Case Else
Throw New ArgumentException(NameOf(index))
End Select
End Function
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return 1
End Get
End Property
Public Overrides ReadOnly Property DocumentationText As String
Get
Return VBWorkspaceResources.Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix
End Get
End Property
Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart)
Get
Return {
New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "GetXmlNamespace"),
New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")
}
End Get
End Property
Public Overrides ReadOnly Property IncludeAsType As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeMetadataName As String
Get
Return "System.Xml.Linq.XNamespace"
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/VisualBasic/Portable/Completion/CompletionProviders/AwaitCompletionProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(AwaitCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(KeywordCompletionProvider))>
<[Shared]>
Friend NotInheritable Class AwaitCompletionProvider
Inherits AbstractAwaitCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CommonTriggerChars
Private Protected Overrides Function GetSpanStart(declaration As SyntaxNode) As Integer
Select Case declaration.Kind()
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, DeclarationStatementSyntax).GetMemberKeywordToken().SpanStart
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, LambdaExpressionSyntax).SubOrFunctionHeader.SubOrFunctionKeyword.SpanStart
End Select
Throw ExceptionUtilities.Unreachable
End Function
Private Protected Overrides Function GetAsyncSupportingDeclaration(token As SyntaxToken) As SyntaxNode
Return token.GetAncestor(Function(node) node.IsAsyncSupportedFunctionSyntax())
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(AwaitCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(KeywordCompletionProvider))>
<[Shared]>
Friend NotInheritable Class AwaitCompletionProvider
Inherits AbstractAwaitCompletionProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CommonTriggerChars
Private Protected Overrides Function GetSpanStart(declaration As SyntaxNode) As Integer
Select Case declaration.Kind()
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, DeclarationStatementSyntax).GetMemberKeywordToken().SpanStart
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, LambdaExpressionSyntax).SubOrFunctionHeader.SubOrFunctionKeyword.SpanStart
End Select
Throw ExceptionUtilities.Unreachable
End Function
Private Protected Overrides Function GetAsyncSupportingDeclaration(token As SyntaxToken) As SyntaxNode
Return token.GetAncestor(Function(node) node.IsAsyncSupportedFunctionSyntax())
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedOptionsProviderFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider
{
internal class CombinedOptionsProviderFactory<T> : ISettingsProviderFactory<T>
{
private ImmutableArray<ISettingsProviderFactory<T>> _factories;
public CombinedOptionsProviderFactory(ImmutableArray<ISettingsProviderFactory<T>> factories)
{
_factories = factories;
}
public ISettingsProvider<T> GetForFile(string filePath)
{
var providers = TemporaryArray<ISettingsProvider<T>>.Empty;
foreach (var factory in _factories)
{
providers.Add(factory.GetForFile(filePath));
}
return new CombinedProvider<T>(providers.ToImmutableAndClear());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider
{
internal class CombinedOptionsProviderFactory<T> : ISettingsProviderFactory<T>
{
private ImmutableArray<ISettingsProviderFactory<T>> _factories;
public CombinedOptionsProviderFactory(ImmutableArray<ISettingsProviderFactory<T>> factories)
{
_factories = factories;
}
public ISettingsProvider<T> GetForFile(string filePath)
{
var providers = TemporaryArray<ISettingsProvider<T>>.Empty;
foreach (var factory in _factories)
{
providers.Add(factory.GetForFile(filePath));
}
return new CombinedProvider<T>(providers.ToImmutableAndClear());
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/CSharp/Portable/CaseCorrection/CSharpCaseCorrectionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CaseCorrection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CaseCorrection
{
[ExportLanguageService(typeof(ICaseCorrectionService), LanguageNames.CSharp), Shared]
internal class CSharpCaseCorrectionService : AbstractCaseCorrectionService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCaseCorrectionService()
{
}
protected override void AddReplacements(
SemanticModel? semanticModel,
SyntaxNode root,
ImmutableArray<TextSpan> spans,
Workspace workspace,
ConcurrentDictionary<SyntaxToken, SyntaxToken> replacements,
CancellationToken cancellationToken)
{
// C# doesn't support case correction since we are a case sensitive language.
return;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CaseCorrection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CaseCorrection
{
[ExportLanguageService(typeof(ICaseCorrectionService), LanguageNames.CSharp), Shared]
internal class CSharpCaseCorrectionService : AbstractCaseCorrectionService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCaseCorrectionService()
{
}
protected override void AddReplacements(
SemanticModel? semanticModel,
SyntaxNode root,
ImmutableArray<TextSpan> spans,
Workspace workspace,
ConcurrentDictionary<SyntaxToken, SyntaxToken> replacements,
CancellationToken cancellationToken)
{
// C# doesn't support case correction since we are a case sensitive language.
return;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Analyzers/VisualBasic/Analyzers/SimplifyLinqExpression/VisualBasicSimplifyLinqExpressionDiagnosticAnalyzer.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.Diagnostics
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.SimplifyLinqExpression
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyLinqExpression
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend Class VisualBasicSimplifyLinqExpressionDiagnosticAnalyzer
Inherits AbstractSimplifyLinqExpressionDiagnosticAnalyzer(Of InvocationExpressionSyntax, MemberAccessExpressionSyntax)
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance
Protected Overrides Function TryGetNextInvocationInChain(invocation As IInvocationOperation) As IInvocationOperation
' Unlike C# in VB exension methods are related in a simple child-parent relationship
' so in the case of A().ExensionB() to get from A to ExensionB we just need to get the parent of A
Return TryCast(invocation.Parent, IInvocationOperation)
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.Diagnostics
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.SimplifyLinqExpression
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyLinqExpression
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend Class VisualBasicSimplifyLinqExpressionDiagnosticAnalyzer
Inherits AbstractSimplifyLinqExpressionDiagnosticAnalyzer(Of InvocationExpressionSyntax, MemberAccessExpressionSyntax)
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance
Protected Overrides Function TryGetNextInvocationInChain(invocation As IInvocationOperation) As IInvocationOperation
' Unlike C# in VB exension methods are related in a simple child-parent relationship
' so in the case of A().ExensionB() to get from A to ExensionB we just need to get the parent of A
Return TryCast(invocation.Parent, IInvocationOperation)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/CSharp/Portable/CodeFixes/ConvertToAsync/CSharpConvertToAsyncMethodCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Async;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ConvertToAsync
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertToAsync), Shared]
internal class CSharpConvertToAsyncMethodCodeFixProvider : AbstractConvertToAsyncCodeFixProvider
{
/// <summary>
/// Cannot await void.
/// </summary>
private const string CS4008 = nameof(CS4008);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpConvertToAsyncMethodCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS4008);
protected override async Task<string> GetDescriptionAsync(
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var methodNode = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
// We only call GetDescription when we already know that we succeeded (so it's safe to
// assume we have a methodNode here).
return string.Format(CSharpFeaturesResources.Make_0_return_Task_instead_of_void, methodNode!.WithBody(null));
}
protected override async Task<Tuple<SyntaxTree, SyntaxNode>?> GetRootInOtherSyntaxTreeAsync(
SyntaxNode node,
SemanticModel semanticModel,
Diagnostic diagnostic,
CancellationToken cancellationToken)
{
var methodDeclaration = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
if (methodDeclaration == null)
{
return null;
}
var oldRoot = await methodDeclaration.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = oldRoot.ReplaceNode(methodDeclaration, ConvertToAsyncFunction(methodDeclaration));
return Tuple.Create(oldRoot.SyntaxTree, newRoot);
}
private static async Task<MethodDeclarationSyntax?> GetMethodDeclarationAsync(
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var invocationExpression = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.InvocationExpression));
if (invocationExpression == null)
{
return null;
}
if (!(semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol is IMethodSymbol methodSymbol))
{
return null;
}
var methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault();
if (methodReference == null)
{
return null;
}
if (!((await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) is MethodDeclarationSyntax methodDeclaration))
{
return null;
}
if (!methodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
return null;
}
return methodDeclaration;
}
private static MethodDeclarationSyntax ConvertToAsyncFunction(MethodDeclarationSyntax methodDeclaration)
{
return methodDeclaration.WithReturnType(
SyntaxFactory.ParseTypeName("Task")
.WithTriviaFrom(methodDeclaration));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Async;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ConvertToAsync
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertToAsync), Shared]
internal class CSharpConvertToAsyncMethodCodeFixProvider : AbstractConvertToAsyncCodeFixProvider
{
/// <summary>
/// Cannot await void.
/// </summary>
private const string CS4008 = nameof(CS4008);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpConvertToAsyncMethodCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS4008);
protected override async Task<string> GetDescriptionAsync(
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var methodNode = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
// We only call GetDescription when we already know that we succeeded (so it's safe to
// assume we have a methodNode here).
return string.Format(CSharpFeaturesResources.Make_0_return_Task_instead_of_void, methodNode!.WithBody(null));
}
protected override async Task<Tuple<SyntaxTree, SyntaxNode>?> GetRootInOtherSyntaxTreeAsync(
SyntaxNode node,
SemanticModel semanticModel,
Diagnostic diagnostic,
CancellationToken cancellationToken)
{
var methodDeclaration = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
if (methodDeclaration == null)
{
return null;
}
var oldRoot = await methodDeclaration.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = oldRoot.ReplaceNode(methodDeclaration, ConvertToAsyncFunction(methodDeclaration));
return Tuple.Create(oldRoot.SyntaxTree, newRoot);
}
private static async Task<MethodDeclarationSyntax?> GetMethodDeclarationAsync(
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var invocationExpression = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.InvocationExpression));
if (invocationExpression == null)
{
return null;
}
if (!(semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol is IMethodSymbol methodSymbol))
{
return null;
}
var methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault();
if (methodReference == null)
{
return null;
}
if (!((await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) is MethodDeclarationSyntax methodDeclaration))
{
return null;
}
if (!methodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
return null;
}
return methodDeclaration;
}
private static MethodDeclarationSyntax ConvertToAsyncFunction(MethodDeclarationSyntax methodDeclaration)
{
return methodDeclaration.WithReturnType(
SyntaxFactory.ParseTypeName("Task")
.WithTriviaFrom(methodDeclaration));
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AddMissingTokensCodeCleanupProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers
<ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.AddMissingTokens, LanguageNames.VisualBasic), [Shared]>
<ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.CaseCorrection, Before:=PredefinedCodeCleanupProviderNames.Format)>
Friend Class AddMissingTokensCodeCleanupProvider
Inherits AbstractTokensCodeCleanupProvider
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="https://github.com/dotnet/roslyn/issues/42820")>
Public Sub New()
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return PredefinedCodeCleanupProviderNames.AddMissingTokens
End Get
End Property
Protected Overrides Async Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter)
Return Await AddMissingTokensRewriter.CreateAsync(document, spans, cancellationToken).ConfigureAwait(False)
End Function
Private Class AddMissingTokensRewriter
Inherits AbstractTokensCodeCleanupProvider.Rewriter
Private ReadOnly _model As SemanticModel
Private Sub New(semanticModel As SemanticModel, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken)
MyBase.New(spans, cancellationToken)
Me._model = semanticModel
End Sub
Public Shared Async Function CreateAsync(document As Document, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) As Task(Of AddMissingTokensRewriter)
Dim modifiedSpan = spans.Collapse()
Dim semanticModel = If(document Is Nothing, Nothing,
Await document.ReuseExistingSpeculativeModelAsync(modifiedSpan, cancellationToken).ConfigureAwait(False))
Return New AddMissingTokensRewriter(semanticModel, spans, cancellationToken)
End Function
Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode
If TypeOf node Is ExpressionSyntax Then
Return VisitExpression(DirectCast(node, ExpressionSyntax))
Else
Return MyBase.Visit(node)
End If
End Function
Private Function VisitExpression(node As ExpressionSyntax) As SyntaxNode
If Not ShouldRewrite(node) Then
Return node
End If
Return AddParenthesesTransform(node, MyBase.Visit(node),
Function()
' we only care whole name not part of dotted names
Dim name As NameSyntax = TryCast(node, NameSyntax)
If name Is Nothing OrElse TypeOf name.Parent Is NameSyntax Then
Return False
End If
Return CheckName(name)
End Function,
Function(n) DirectCast(n, InvocationExpressionSyntax).ArgumentList,
Function(n) SyntaxFactory.InvocationExpression(n, SyntaxFactory.ArgumentList()),
Function(n) IsMethodSymbol(DirectCast(n, ExpressionSyntax)))
End Function
Private Function CheckName(name As NameSyntax) As Boolean
If _underStructuredTrivia OrElse name.IsStructuredTrivia() OrElse name.IsMissing Then
Return False
End If
' can't/don't try to transform member access to invocation
If TypeOf name.Parent Is MemberAccessExpressionSyntax OrElse
TypeOf name.Parent Is TupleElementSyntax OrElse
name.CheckParent(Of AttributeSyntax)(Function(p) p.Name Is name) OrElse
name.CheckParent(Of ImplementsClauseSyntax)(Function(p) p.InterfaceMembers.Any(Function(i) i Is name)) OrElse
name.CheckParent(Of UnaryExpressionSyntax)(Function(p) p.Kind = SyntaxKind.AddressOfExpression AndAlso p.Operand Is name) OrElse
name.CheckParent(Of InvocationExpressionSyntax)(Function(p) p.Expression Is name) OrElse
name.CheckParent(Of NamedFieldInitializerSyntax)(Function(p) p.Name Is name) OrElse
name.CheckParent(Of ImplementsStatementSyntax)(Function(p) p.Types.Any(Function(t) t Is name)) OrElse
name.CheckParent(Of HandlesClauseItemSyntax)(Function(p) p.EventMember Is name) OrElse
name.CheckParent(Of ObjectCreationExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of ArrayCreationExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of ArrayTypeSyntax)(Function(p) p.ElementType Is name) OrElse
name.CheckParent(Of SimpleAsClauseSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of TypeConstraintSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of GetTypeExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of TypeOfExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of CastExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of ForEachStatementSyntax)(Function(p) p.ControlVariable Is name) OrElse
name.CheckParent(Of ForStatementSyntax)(Function(p) p.ControlVariable Is name) OrElse
name.CheckParent(Of AssignmentStatementSyntax)(Function(p) p.Left Is name) OrElse
name.CheckParent(Of TypeArgumentListSyntax)(Function(p) p.Arguments.Any(Function(i) i Is name)) OrElse
name.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is name) OrElse
name.CheckParent(Of CastExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.Expression Is name) OrElse
name.CheckParent(Of NameOfExpressionSyntax)(Function(p) p.Argument Is name) Then
Return False
End If
Return True
End Function
Private Function IsMethodSymbol(expression As ExpressionSyntax) As Boolean
If Me._model Is Nothing Then
Return False
End If
Dim symbols = Me._model.GetSymbolInfo(expression, _cancellationToken).GetAllSymbols()
Return symbols.Any() AndAlso symbols.All(
Function(s) If(TryCast(s, IMethodSymbol)?.MethodKind = MethodKind.Ordinary, False))
End Function
Private Function IsDelegateType(expression As ExpressionSyntax) As Boolean
If Me._model Is Nothing Then
Return False
End If
Dim type = Me._model.GetTypeInfo(expression, _cancellationToken).Type
Return type.IsDelegateType
End Function
Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode
Dim newNode = MyBase.VisitInvocationExpression(node)
' make sure we are not under structured trivia
If _underStructuredTrivia Then
Return newNode
End If
If Not TypeOf node.Expression Is NameSyntax AndAlso
Not TypeOf node.Expression Is ParenthesizedExpressionSyntax AndAlso
Not TypeOf node.Expression Is MemberAccessExpressionSyntax Then
Return newNode
End If
Dim semanticChecker As Func(Of InvocationExpressionSyntax, Boolean) =
Function(n) IsMethodSymbol(n.Expression) OrElse IsDelegateType(n.Expression)
Return AddParenthesesTransform(
node, newNode, Function(n) n.Expression.Span.Length > 0, Function(n) n.ArgumentList, Function(n) n.WithArgumentList(SyntaxFactory.ArgumentList()), semanticChecker)
End Function
Public Overrides Function VisitRaiseEventStatement(node As RaiseEventStatementSyntax) As SyntaxNode
Return AddParenthesesTransform(
node, MyBase.VisitRaiseEventStatement(node), Function(n) Not n.Name.IsMissing, Function(n) n.ArgumentList, Function(n) n.WithArgumentList(SyntaxFactory.ArgumentList()))
End Function
Public Overrides Function VisitMethodStatement(node As MethodStatementSyntax) As SyntaxNode
Dim rewrittenMethod = DirectCast(AddParameterListTransform(node, MyBase.VisitMethodStatement(node), Function(n) Not n.Identifier.IsMissing), MethodStatementSyntax)
Return AsyncOrIteratorFunctionReturnTypeFixer.RewriteMethodStatement(rewrittenMethod, Me._model, node, Me._cancellationToken)
End Function
Public Overrides Function VisitSubNewStatement(node As SubNewStatementSyntax) As SyntaxNode
Return AddParameterListTransform(node, MyBase.VisitSubNewStatement(node), Function(n) Not n.NewKeyword.IsMissing)
End Function
Public Overrides Function VisitDeclareStatement(node As DeclareStatementSyntax) As SyntaxNode
Return AddParameterListTransform(node, MyBase.VisitDeclareStatement(node), Function(n) Not n.Identifier.IsMissing)
End Function
Public Overrides Function VisitDelegateStatement(node As DelegateStatementSyntax) As SyntaxNode
Return AddParameterListTransform(node, MyBase.VisitDelegateStatement(node), Function(n) Not n.Identifier.IsMissing)
End Function
Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SyntaxNode
If node.AsClause IsNot Nothing Then
Return MyBase.VisitEventStatement(node)
End If
Return AddParameterListTransform(node, MyBase.VisitEventStatement(node), Function(n) Not n.Identifier.IsMissing)
End Function
Public Overrides Function VisitAccessorStatement(node As AccessorStatementSyntax) As SyntaxNode
Dim newNode = MyBase.VisitAccessorStatement(node)
If node.DeclarationKeyword.Kind <> SyntaxKind.AddHandlerKeyword AndAlso
node.DeclarationKeyword.Kind <> SyntaxKind.RemoveHandlerKeyword AndAlso
node.DeclarationKeyword.Kind <> SyntaxKind.RaiseEventKeyword Then
Return newNode
End If
Return AddParameterListTransform(node, newNode, Function(n) Not n.DeclarationKeyword.IsMissing)
End Function
Public Overrides Function VisitAttribute(node As AttributeSyntax) As SyntaxNode
' we decide not to auto insert parentheses for attribute
Return MyBase.VisitAttribute(node)
End Function
Public Overrides Function VisitOperatorStatement(node As OperatorStatementSyntax) As SyntaxNode
' don't auto insert parentheses
' these methods are okay to be removed. but it is here to show other cases where parse tree node can have parentheses
Return MyBase.VisitOperatorStatement(node)
End Function
Public Overrides Function VisitPropertyStatement(node As PropertyStatementSyntax) As SyntaxNode
' don't auto insert parentheses
' these methods are okay to be removed. but it is here to show other cases where parse tree node can have parentheses
Return MyBase.VisitPropertyStatement(node)
End Function
Public Overrides Function VisitLambdaHeader(node As LambdaHeaderSyntax) As SyntaxNode
Dim rewrittenLambdaHeader = DirectCast(MyBase.VisitLambdaHeader(node), LambdaHeaderSyntax)
rewrittenLambdaHeader = AsyncOrIteratorFunctionReturnTypeFixer.RewriteLambdaHeader(rewrittenLambdaHeader, Me._model, node, Me._cancellationToken)
Return AddParameterListTransform(node, rewrittenLambdaHeader, Function(n) True)
End Function
Private Shared Function TryFixupTrivia(Of T As SyntaxNode)(node As T, previousToken As SyntaxToken, lastToken As SyntaxToken, ByRef newNode As T) As Boolean
' initialize to initial value
newNode = Nothing
' hold onto the trivia
Dim prevTrailingTrivia = previousToken.TrailingTrivia
' if previous token is not part of node and if it has any trivia, don't do anything
If Not node.DescendantTokens().Any(Function(token) token = previousToken) AndAlso prevTrailingTrivia.Count > 0 Then
Return False
End If
' remove the trivia from the token
Dim previousTokenWithoutTrailingTrivia = previousToken.WithTrailingTrivia(SyntaxFactory.ElasticMarker)
' If previousToken has trailing WhitespaceTrivia, strip off the trailing WhitespaceTrivia from the lastToken.
Dim lastTrailingTrivia = lastToken.TrailingTrivia
If prevTrailingTrivia.Any(SyntaxKind.WhitespaceTrivia) Then
lastTrailingTrivia = lastTrailingTrivia.WithoutLeadingWhitespaceOrEndOfLine()
End If
' get the trivia and attach it to the last token
Dim lastTokenWithTrailingTrivia = lastToken.WithTrailingTrivia(prevTrailingTrivia.Concat(lastTrailingTrivia))
' replace tokens
newNode = node.ReplaceTokens(SpecializedCollections.SingletonEnumerable(previousToken).Concat(lastToken),
Function(o, m)
If o = previousToken Then
Return previousTokenWithoutTrailingTrivia
ElseIf o = lastToken Then
Return lastTokenWithTrailingTrivia
End If
Throw ExceptionUtilities.UnexpectedValue(o)
End Function)
Return True
End Function
Private Function AddParameterListTransform(Of T As MethodBaseSyntax)(node As T, newNode As SyntaxNode, nameChecker As Func(Of T, Boolean)) As T
Dim transform As Func(Of T, T) = Function(n As T)
Dim newParamList = SyntaxFactory.ParameterList()
If n.ParameterList IsNot Nothing Then
If n.ParameterList.HasLeadingTrivia Then
newParamList = newParamList.WithLeadingTrivia(n.ParameterList.GetLeadingTrivia)
End If
If n.ParameterList.HasTrailingTrivia Then
newParamList = newParamList.WithTrailingTrivia(n.ParameterList.GetTrailingTrivia)
End If
End If
Dim nodeWithParams = DirectCast(n.WithParameterList(newParamList), T)
If n.HasTrailingTrivia AndAlso nodeWithParams.GetLastToken() = nodeWithParams.ParameterList.CloseParenToken Then
Dim trailing = n.GetTrailingTrivia
nodeWithParams = DirectCast(n _
.WithoutTrailingTrivia() _
.WithParameterList(newParamList) _
.WithTrailingTrivia(trailing), T)
End If
Return nodeWithParams
End Function
Return AddParenthesesTransform(node, newNode, nameChecker, Function(n) n.ParameterList, transform)
End Function
Private Function AddParenthesesTransform(Of T As SyntaxNode)(
originalNode As T,
node As SyntaxNode,
nameChecker As Func(Of T, Boolean),
listGetter As Func(Of T, SyntaxNode),
withTransform As Func(Of T, T),
Optional semanticPredicate As Func(Of T, Boolean) = Nothing
) As T
Dim newNode = DirectCast(node, T)
If Not nameChecker(newNode) Then
Return newNode
End If
Dim syntaxPredicate As Func(Of Boolean) = Function()
Dim list = listGetter(originalNode)
If list Is Nothing Then
Return True
End If
Dim paramList = TryCast(list, ParameterListSyntax)
If paramList IsNot Nothing Then
Return paramList.Parameters = Nothing AndAlso
paramList.OpenParenToken.IsMissing AndAlso
paramList.CloseParenToken.IsMissing
End If
Dim argsList = TryCast(list, ArgumentListSyntax)
Return argsList IsNot Nothing AndAlso
argsList.Arguments = Nothing AndAlso
argsList.OpenParenToken.IsMissing AndAlso
argsList.CloseParenToken.IsMissing
End Function
Return AddParenthesesTransform(originalNode, node, syntaxPredicate, listGetter, withTransform, semanticPredicate)
End Function
Private Function AddParenthesesTransform(Of T As SyntaxNode)(
originalNode As T,
node As SyntaxNode,
syntaxPredicate As Func(Of Boolean),
listGetter As Func(Of T, SyntaxNode),
transform As Func(Of T, T),
Optional semanticPredicate As Func(Of T, Boolean) = Nothing
) As T
Dim span = originalNode.Span
If syntaxPredicate() AndAlso
_spans.HasIntervalThatContains(span.Start, span.Length) AndAlso
CheckSkippedTriviaForMissingToken(originalNode, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken) Then
Dim transformedNode = transform(DirectCast(node, T))
' previous token can be different per different node types.
' it could be name or close paren of type parameter list and etc. also can be different based on
' what token is omitted
' get one that actually exist and get trailing trivia of that token
Dim fixedUpNode As T = Nothing
Dim list = listGetter(transformedNode)
Dim previousToken = list.GetFirstToken(includeZeroWidth:=True).GetPreviousToken(includeZeroWidth:=True)
Dim lastToken = list.GetLastToken(includeZeroWidth:=True)
If Not TryFixupTrivia(transformedNode, previousToken, lastToken, fixedUpNode) Then
Return DirectCast(node, T)
End If
' semanticPredicate is invoked at the last step as it is the most expensive operation which requires building the compilation for semantic validations.
If semanticPredicate Is Nothing OrElse semanticPredicate(originalNode) Then
Return DirectCast(fixedUpNode, T)
End If
End If
Return DirectCast(node, T)
End Function
Private Shared Function CheckSkippedTriviaForMissingToken(node As SyntaxNode, ParamArray kinds As SyntaxKind()) As Boolean
Dim lastToken = node.GetLastToken(includeZeroWidth:=True)
If lastToken.TrailingTrivia.Count = 0 Then
Return True
End If
Return Not lastToken _
.TrailingTrivia _
.Where(Function(t) t.Kind = SyntaxKind.SkippedTokensTrivia) _
.SelectMany(Function(t) DirectCast(t.GetStructure(), SkippedTokensTriviaSyntax).Tokens) _
.Any(Function(t) kinds.Contains(t.Kind))
End Function
Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitIfStatement(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword)
End Function
Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitIfDirectiveTrivia(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword)
End Function
Public Overrides Function VisitElseIfStatement(node As ElseIfStatementSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitElseIfStatement(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword)
End Function
Public Overrides Function VisitTypeArgumentList(node As TypeArgumentListSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitTypeArgumentList(node), Function(n) n.OfKeyword, SyntaxKind.OfKeyword)
End Function
Public Overrides Function VisitTypeParameterList(node As TypeParameterListSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitTypeParameterList(node), Function(n) n.OfKeyword, SyntaxKind.OfKeyword)
End Function
Public Overrides Function VisitContinueStatement(node As ContinueStatementSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitContinueStatement(node), Function(n) n.BlockKeyword, SyntaxKind.DoKeyword, SyntaxKind.ForKeyword, SyntaxKind.WhileKeyword)
End Function
Public Overrides Function VisitOptionStatement(node As OptionStatementSyntax) As SyntaxNode
Select Case node.NameKeyword.Kind
Case SyntaxKind.ExplicitKeyword,
SyntaxKind.InferKeyword,
SyntaxKind.StrictKeyword
Return AddMissingOrOmittedTokenTransform(node, node, Function(n) n.ValueKeyword, SyntaxKind.OnKeyword, SyntaxKind.OffKeyword)
Case Else
Return node
End Select
End Function
Public Overrides Function VisitSelectStatement(node As SelectStatementSyntax) As SyntaxNode
Dim newNode = DirectCast(MyBase.VisitSelectStatement(node), SelectStatementSyntax)
Return If(newNode.CaseKeyword.Kind = SyntaxKind.None,
newNode.WithCaseKeyword(SyntaxFactory.Token(SyntaxKind.CaseKeyword)),
newNode)
End Function
Private Function AddMissingOrOmittedTokenTransform(Of T As SyntaxNode)(
originalNode As T, node As SyntaxNode, tokenGetter As Func(Of T, SyntaxToken), ParamArray kinds As SyntaxKind()) As T
Dim newNode = DirectCast(node, T)
If Not CheckSkippedTriviaForMissingToken(originalNode, kinds) Then
Return newNode
End If
Dim newToken = tokenGetter(newNode)
Dim processedToken = ProcessToken(tokenGetter(originalNode), newToken, newNode)
If processedToken <> newToken Then
Dim replacedNode = ReplaceOrSetToken(newNode, newToken, processedToken)
Dim replacedToken = tokenGetter(replacedNode)
Dim previousToken = replacedToken.GetPreviousToken(includeZeroWidth:=True)
Dim fixedupNode As T = Nothing
If Not TryFixupTrivia(replacedNode, previousToken, replacedToken, fixedupNode) Then
Return newNode
End If
Return fixedupNode
End If
Return newNode
End Function
Private Function ProcessToken(originalToken As SyntaxToken, token As SyntaxToken, parent As SyntaxNode) As SyntaxToken
' special case omitted token case
If IsOmitted(originalToken) Then
Return ProcessOmittedToken(originalToken, token, parent)
End If
Dim span = originalToken.Span
If Not _spans.HasIntervalThatContains(span.Start, span.Length) Then
' token is outside of the provided span
Return token
End If
' token is not missing or if missing token is identifier there is not much we can do
If Not originalToken.IsMissing OrElse
originalToken.Kind = SyntaxKind.None OrElse
originalToken.Kind = SyntaxKind.IdentifierToken Then
Return token
End If
Return ProcessMissingToken(originalToken, token)
End Function
Private Shared Function ReplaceOrSetToken(Of T As SyntaxNode)(originalParent As T, tokenToFix As SyntaxToken, replacementToken As SyntaxToken) As T
If Not IsOmitted(tokenToFix) Then
Return originalParent.ReplaceToken(tokenToFix, replacementToken)
Else
Return DirectCast(SetOmittedToken(originalParent, replacementToken), T)
End If
End Function
Private Shared Function SetOmittedToken(originalParent As SyntaxNode, newToken As SyntaxToken) As SyntaxNode
Select Case newToken.Kind
Case SyntaxKind.ThenKeyword
' this can be regular If, an If directive, or an ElseIf
Dim regularIf = TryCast(originalParent, IfStatementSyntax)
If regularIf IsNot Nothing Then
Dim previousToken = regularIf.Condition.GetLastToken(includeZeroWidth:=True)
Dim nextToken = regularIf.GetLastToken.GetNextToken
If Not InvalidOmittedToken(previousToken, nextToken) Then
Return regularIf.WithThenKeyword(newToken)
End If
Else
Dim regularElseIf = TryCast(originalParent, ElseIfStatementSyntax)
If regularElseIf IsNot Nothing Then
Dim previousToken = regularElseIf.Condition.GetLastToken(includeZeroWidth:=True)
Dim nextToken = regularElseIf.GetLastToken.GetNextToken
If Not InvalidOmittedToken(previousToken, nextToken) Then
Return regularElseIf.WithThenKeyword(newToken)
End If
Else
Dim ifDirective = TryCast(originalParent, IfDirectiveTriviaSyntax)
If ifDirective IsNot Nothing Then
Dim previousToken = ifDirective.Condition.GetLastToken(includeZeroWidth:=True)
Dim nextToken = ifDirective.GetLastToken.GetNextToken
If Not InvalidOmittedToken(previousToken, nextToken) Then
Return ifDirective.WithThenKeyword(newToken)
End If
End If
End If
End If
Case SyntaxKind.OnKeyword
Dim optionStatement = TryCast(originalParent, OptionStatementSyntax)
If optionStatement IsNot Nothing Then
Return optionStatement.WithValueKeyword(newToken)
End If
End Select
Return originalParent
End Function
Private Shared Function IsOmitted(token As SyntaxToken) As Boolean
Return token.Kind = SyntaxKind.None
End Function
Private Shared Function ProcessOmittedToken(originalToken As SyntaxToken, token As SyntaxToken, parent As SyntaxNode) As SyntaxToken
' multiline if statement with missing then keyword case
If TypeOf parent Is IfStatementSyntax Then
Dim ifStatement = DirectCast(parent, IfStatementSyntax)
If Exist(ifStatement.Condition) AndAlso ifStatement.ThenKeyword = originalToken Then
Return If(parent.GetAncestor(Of MultiLineIfBlockSyntax)() IsNot Nothing, CreateOmittedToken(token, SyntaxKind.ThenKeyword), token)
End If
End If
If TryCast(parent, IfDirectiveTriviaSyntax)?.ThenKeyword = originalToken Then
Return CreateOmittedToken(token, SyntaxKind.ThenKeyword)
ElseIf TryCast(parent, ElseIfStatementSyntax)?.ThenKeyword = originalToken Then
Return If(parent.GetAncestor(Of ElseIfBlockSyntax)() IsNot Nothing, CreateOmittedToken(token, SyntaxKind.ThenKeyword), token)
ElseIf TryCast(parent, OptionStatementSyntax)?.ValueKeyword = originalToken Then
Return CreateOmittedToken(token, SyntaxKind.OnKeyword)
End If
Return token
End Function
Private Shared Function InvalidOmittedToken(previousToken As SyntaxToken, nextToken As SyntaxToken) As Boolean
' if previous token has a problem, don't bother
If previousToken.IsMissing OrElse previousToken.IsSkipped OrElse previousToken.Kind = 0 Then
Return True
End If
' if next token has a problem, do little bit more check
' if there is no next token, it is okay to insert the missing token
If nextToken.Kind = 0 Then
Return False
End If
' if next token is missing or skipped, check whether it has EOL
If nextToken.IsMissing OrElse nextToken.IsSkipped Then
Return Not previousToken.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) And
Not nextToken.LeadingTrivia.Any(SyntaxKind.EndOfLineTrivia)
End If
Return False
End Function
Private Shared Function Exist(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso node.Span.Length > 0
End Function
Private Shared Function ProcessMissingToken(originalToken As SyntaxToken, token As SyntaxToken) As SyntaxToken
' auto insert missing "Of" keyword in type argument list
If TryCast(originalToken.Parent, TypeArgumentListSyntax)?.OfKeyword = originalToken Then
Return CreateMissingToken(token)
ElseIf TryCast(originalToken.Parent, TypeParameterListSyntax)?.OfKeyword = originalToken Then
Return CreateMissingToken(token)
ElseIf TryCast(originalToken.Parent, ContinueStatementSyntax)?.BlockKeyword = originalToken Then
Return CreateMissingToken(token)
End If
Return token
End Function
Private Shared Function CreateMissingToken(token As SyntaxToken) As SyntaxToken
Return CreateToken(token, token.Kind)
End Function
Private Shared Function CreateOmittedToken(token As SyntaxToken, kind As SyntaxKind) As SyntaxToken
Return CreateToken(token, kind)
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers
<ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.AddMissingTokens, LanguageNames.VisualBasic), [Shared]>
<ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.CaseCorrection, Before:=PredefinedCodeCleanupProviderNames.Format)>
Friend Class AddMissingTokensCodeCleanupProvider
Inherits AbstractTokensCodeCleanupProvider
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="https://github.com/dotnet/roslyn/issues/42820")>
Public Sub New()
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return PredefinedCodeCleanupProviderNames.AddMissingTokens
End Get
End Property
Protected Overrides Async Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter)
Return Await AddMissingTokensRewriter.CreateAsync(document, spans, cancellationToken).ConfigureAwait(False)
End Function
Private Class AddMissingTokensRewriter
Inherits AbstractTokensCodeCleanupProvider.Rewriter
Private ReadOnly _model As SemanticModel
Private Sub New(semanticModel As SemanticModel, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken)
MyBase.New(spans, cancellationToken)
Me._model = semanticModel
End Sub
Public Shared Async Function CreateAsync(document As Document, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) As Task(Of AddMissingTokensRewriter)
Dim modifiedSpan = spans.Collapse()
Dim semanticModel = If(document Is Nothing, Nothing,
Await document.ReuseExistingSpeculativeModelAsync(modifiedSpan, cancellationToken).ConfigureAwait(False))
Return New AddMissingTokensRewriter(semanticModel, spans, cancellationToken)
End Function
Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode
If TypeOf node Is ExpressionSyntax Then
Return VisitExpression(DirectCast(node, ExpressionSyntax))
Else
Return MyBase.Visit(node)
End If
End Function
Private Function VisitExpression(node As ExpressionSyntax) As SyntaxNode
If Not ShouldRewrite(node) Then
Return node
End If
Return AddParenthesesTransform(node, MyBase.Visit(node),
Function()
' we only care whole name not part of dotted names
Dim name As NameSyntax = TryCast(node, NameSyntax)
If name Is Nothing OrElse TypeOf name.Parent Is NameSyntax Then
Return False
End If
Return CheckName(name)
End Function,
Function(n) DirectCast(n, InvocationExpressionSyntax).ArgumentList,
Function(n) SyntaxFactory.InvocationExpression(n, SyntaxFactory.ArgumentList()),
Function(n) IsMethodSymbol(DirectCast(n, ExpressionSyntax)))
End Function
Private Function CheckName(name As NameSyntax) As Boolean
If _underStructuredTrivia OrElse name.IsStructuredTrivia() OrElse name.IsMissing Then
Return False
End If
' can't/don't try to transform member access to invocation
If TypeOf name.Parent Is MemberAccessExpressionSyntax OrElse
TypeOf name.Parent Is TupleElementSyntax OrElse
name.CheckParent(Of AttributeSyntax)(Function(p) p.Name Is name) OrElse
name.CheckParent(Of ImplementsClauseSyntax)(Function(p) p.InterfaceMembers.Any(Function(i) i Is name)) OrElse
name.CheckParent(Of UnaryExpressionSyntax)(Function(p) p.Kind = SyntaxKind.AddressOfExpression AndAlso p.Operand Is name) OrElse
name.CheckParent(Of InvocationExpressionSyntax)(Function(p) p.Expression Is name) OrElse
name.CheckParent(Of NamedFieldInitializerSyntax)(Function(p) p.Name Is name) OrElse
name.CheckParent(Of ImplementsStatementSyntax)(Function(p) p.Types.Any(Function(t) t Is name)) OrElse
name.CheckParent(Of HandlesClauseItemSyntax)(Function(p) p.EventMember Is name) OrElse
name.CheckParent(Of ObjectCreationExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of ArrayCreationExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of ArrayTypeSyntax)(Function(p) p.ElementType Is name) OrElse
name.CheckParent(Of SimpleAsClauseSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of TypeConstraintSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of GetTypeExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of TypeOfExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of CastExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of ForEachStatementSyntax)(Function(p) p.ControlVariable Is name) OrElse
name.CheckParent(Of ForStatementSyntax)(Function(p) p.ControlVariable Is name) OrElse
name.CheckParent(Of AssignmentStatementSyntax)(Function(p) p.Left Is name) OrElse
name.CheckParent(Of TypeArgumentListSyntax)(Function(p) p.Arguments.Any(Function(i) i Is name)) OrElse
name.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is name) OrElse
name.CheckParent(Of CastExpressionSyntax)(Function(p) p.Type Is name) OrElse
name.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.Expression Is name) OrElse
name.CheckParent(Of NameOfExpressionSyntax)(Function(p) p.Argument Is name) Then
Return False
End If
Return True
End Function
Private Function IsMethodSymbol(expression As ExpressionSyntax) As Boolean
If Me._model Is Nothing Then
Return False
End If
Dim symbols = Me._model.GetSymbolInfo(expression, _cancellationToken).GetAllSymbols()
Return symbols.Any() AndAlso symbols.All(
Function(s) If(TryCast(s, IMethodSymbol)?.MethodKind = MethodKind.Ordinary, False))
End Function
Private Function IsDelegateType(expression As ExpressionSyntax) As Boolean
If Me._model Is Nothing Then
Return False
End If
Dim type = Me._model.GetTypeInfo(expression, _cancellationToken).Type
Return type.IsDelegateType
End Function
Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode
Dim newNode = MyBase.VisitInvocationExpression(node)
' make sure we are not under structured trivia
If _underStructuredTrivia Then
Return newNode
End If
If Not TypeOf node.Expression Is NameSyntax AndAlso
Not TypeOf node.Expression Is ParenthesizedExpressionSyntax AndAlso
Not TypeOf node.Expression Is MemberAccessExpressionSyntax Then
Return newNode
End If
Dim semanticChecker As Func(Of InvocationExpressionSyntax, Boolean) =
Function(n) IsMethodSymbol(n.Expression) OrElse IsDelegateType(n.Expression)
Return AddParenthesesTransform(
node, newNode, Function(n) n.Expression.Span.Length > 0, Function(n) n.ArgumentList, Function(n) n.WithArgumentList(SyntaxFactory.ArgumentList()), semanticChecker)
End Function
Public Overrides Function VisitRaiseEventStatement(node As RaiseEventStatementSyntax) As SyntaxNode
Return AddParenthesesTransform(
node, MyBase.VisitRaiseEventStatement(node), Function(n) Not n.Name.IsMissing, Function(n) n.ArgumentList, Function(n) n.WithArgumentList(SyntaxFactory.ArgumentList()))
End Function
Public Overrides Function VisitMethodStatement(node As MethodStatementSyntax) As SyntaxNode
Dim rewrittenMethod = DirectCast(AddParameterListTransform(node, MyBase.VisitMethodStatement(node), Function(n) Not n.Identifier.IsMissing), MethodStatementSyntax)
Return AsyncOrIteratorFunctionReturnTypeFixer.RewriteMethodStatement(rewrittenMethod, Me._model, node, Me._cancellationToken)
End Function
Public Overrides Function VisitSubNewStatement(node As SubNewStatementSyntax) As SyntaxNode
Return AddParameterListTransform(node, MyBase.VisitSubNewStatement(node), Function(n) Not n.NewKeyword.IsMissing)
End Function
Public Overrides Function VisitDeclareStatement(node As DeclareStatementSyntax) As SyntaxNode
Return AddParameterListTransform(node, MyBase.VisitDeclareStatement(node), Function(n) Not n.Identifier.IsMissing)
End Function
Public Overrides Function VisitDelegateStatement(node As DelegateStatementSyntax) As SyntaxNode
Return AddParameterListTransform(node, MyBase.VisitDelegateStatement(node), Function(n) Not n.Identifier.IsMissing)
End Function
Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SyntaxNode
If node.AsClause IsNot Nothing Then
Return MyBase.VisitEventStatement(node)
End If
Return AddParameterListTransform(node, MyBase.VisitEventStatement(node), Function(n) Not n.Identifier.IsMissing)
End Function
Public Overrides Function VisitAccessorStatement(node As AccessorStatementSyntax) As SyntaxNode
Dim newNode = MyBase.VisitAccessorStatement(node)
If node.DeclarationKeyword.Kind <> SyntaxKind.AddHandlerKeyword AndAlso
node.DeclarationKeyword.Kind <> SyntaxKind.RemoveHandlerKeyword AndAlso
node.DeclarationKeyword.Kind <> SyntaxKind.RaiseEventKeyword Then
Return newNode
End If
Return AddParameterListTransform(node, newNode, Function(n) Not n.DeclarationKeyword.IsMissing)
End Function
Public Overrides Function VisitAttribute(node As AttributeSyntax) As SyntaxNode
' we decide not to auto insert parentheses for attribute
Return MyBase.VisitAttribute(node)
End Function
Public Overrides Function VisitOperatorStatement(node As OperatorStatementSyntax) As SyntaxNode
' don't auto insert parentheses
' these methods are okay to be removed. but it is here to show other cases where parse tree node can have parentheses
Return MyBase.VisitOperatorStatement(node)
End Function
Public Overrides Function VisitPropertyStatement(node As PropertyStatementSyntax) As SyntaxNode
' don't auto insert parentheses
' these methods are okay to be removed. but it is here to show other cases where parse tree node can have parentheses
Return MyBase.VisitPropertyStatement(node)
End Function
Public Overrides Function VisitLambdaHeader(node As LambdaHeaderSyntax) As SyntaxNode
Dim rewrittenLambdaHeader = DirectCast(MyBase.VisitLambdaHeader(node), LambdaHeaderSyntax)
rewrittenLambdaHeader = AsyncOrIteratorFunctionReturnTypeFixer.RewriteLambdaHeader(rewrittenLambdaHeader, Me._model, node, Me._cancellationToken)
Return AddParameterListTransform(node, rewrittenLambdaHeader, Function(n) True)
End Function
Private Shared Function TryFixupTrivia(Of T As SyntaxNode)(node As T, previousToken As SyntaxToken, lastToken As SyntaxToken, ByRef newNode As T) As Boolean
' initialize to initial value
newNode = Nothing
' hold onto the trivia
Dim prevTrailingTrivia = previousToken.TrailingTrivia
' if previous token is not part of node and if it has any trivia, don't do anything
If Not node.DescendantTokens().Any(Function(token) token = previousToken) AndAlso prevTrailingTrivia.Count > 0 Then
Return False
End If
' remove the trivia from the token
Dim previousTokenWithoutTrailingTrivia = previousToken.WithTrailingTrivia(SyntaxFactory.ElasticMarker)
' If previousToken has trailing WhitespaceTrivia, strip off the trailing WhitespaceTrivia from the lastToken.
Dim lastTrailingTrivia = lastToken.TrailingTrivia
If prevTrailingTrivia.Any(SyntaxKind.WhitespaceTrivia) Then
lastTrailingTrivia = lastTrailingTrivia.WithoutLeadingWhitespaceOrEndOfLine()
End If
' get the trivia and attach it to the last token
Dim lastTokenWithTrailingTrivia = lastToken.WithTrailingTrivia(prevTrailingTrivia.Concat(lastTrailingTrivia))
' replace tokens
newNode = node.ReplaceTokens(SpecializedCollections.SingletonEnumerable(previousToken).Concat(lastToken),
Function(o, m)
If o = previousToken Then
Return previousTokenWithoutTrailingTrivia
ElseIf o = lastToken Then
Return lastTokenWithTrailingTrivia
End If
Throw ExceptionUtilities.UnexpectedValue(o)
End Function)
Return True
End Function
Private Function AddParameterListTransform(Of T As MethodBaseSyntax)(node As T, newNode As SyntaxNode, nameChecker As Func(Of T, Boolean)) As T
Dim transform As Func(Of T, T) = Function(n As T)
Dim newParamList = SyntaxFactory.ParameterList()
If n.ParameterList IsNot Nothing Then
If n.ParameterList.HasLeadingTrivia Then
newParamList = newParamList.WithLeadingTrivia(n.ParameterList.GetLeadingTrivia)
End If
If n.ParameterList.HasTrailingTrivia Then
newParamList = newParamList.WithTrailingTrivia(n.ParameterList.GetTrailingTrivia)
End If
End If
Dim nodeWithParams = DirectCast(n.WithParameterList(newParamList), T)
If n.HasTrailingTrivia AndAlso nodeWithParams.GetLastToken() = nodeWithParams.ParameterList.CloseParenToken Then
Dim trailing = n.GetTrailingTrivia
nodeWithParams = DirectCast(n _
.WithoutTrailingTrivia() _
.WithParameterList(newParamList) _
.WithTrailingTrivia(trailing), T)
End If
Return nodeWithParams
End Function
Return AddParenthesesTransform(node, newNode, nameChecker, Function(n) n.ParameterList, transform)
End Function
Private Function AddParenthesesTransform(Of T As SyntaxNode)(
originalNode As T,
node As SyntaxNode,
nameChecker As Func(Of T, Boolean),
listGetter As Func(Of T, SyntaxNode),
withTransform As Func(Of T, T),
Optional semanticPredicate As Func(Of T, Boolean) = Nothing
) As T
Dim newNode = DirectCast(node, T)
If Not nameChecker(newNode) Then
Return newNode
End If
Dim syntaxPredicate As Func(Of Boolean) = Function()
Dim list = listGetter(originalNode)
If list Is Nothing Then
Return True
End If
Dim paramList = TryCast(list, ParameterListSyntax)
If paramList IsNot Nothing Then
Return paramList.Parameters = Nothing AndAlso
paramList.OpenParenToken.IsMissing AndAlso
paramList.CloseParenToken.IsMissing
End If
Dim argsList = TryCast(list, ArgumentListSyntax)
Return argsList IsNot Nothing AndAlso
argsList.Arguments = Nothing AndAlso
argsList.OpenParenToken.IsMissing AndAlso
argsList.CloseParenToken.IsMissing
End Function
Return AddParenthesesTransform(originalNode, node, syntaxPredicate, listGetter, withTransform, semanticPredicate)
End Function
Private Function AddParenthesesTransform(Of T As SyntaxNode)(
originalNode As T,
node As SyntaxNode,
syntaxPredicate As Func(Of Boolean),
listGetter As Func(Of T, SyntaxNode),
transform As Func(Of T, T),
Optional semanticPredicate As Func(Of T, Boolean) = Nothing
) As T
Dim span = originalNode.Span
If syntaxPredicate() AndAlso
_spans.HasIntervalThatContains(span.Start, span.Length) AndAlso
CheckSkippedTriviaForMissingToken(originalNode, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken) Then
Dim transformedNode = transform(DirectCast(node, T))
' previous token can be different per different node types.
' it could be name or close paren of type parameter list and etc. also can be different based on
' what token is omitted
' get one that actually exist and get trailing trivia of that token
Dim fixedUpNode As T = Nothing
Dim list = listGetter(transformedNode)
Dim previousToken = list.GetFirstToken(includeZeroWidth:=True).GetPreviousToken(includeZeroWidth:=True)
Dim lastToken = list.GetLastToken(includeZeroWidth:=True)
If Not TryFixupTrivia(transformedNode, previousToken, lastToken, fixedUpNode) Then
Return DirectCast(node, T)
End If
' semanticPredicate is invoked at the last step as it is the most expensive operation which requires building the compilation for semantic validations.
If semanticPredicate Is Nothing OrElse semanticPredicate(originalNode) Then
Return DirectCast(fixedUpNode, T)
End If
End If
Return DirectCast(node, T)
End Function
Private Shared Function CheckSkippedTriviaForMissingToken(node As SyntaxNode, ParamArray kinds As SyntaxKind()) As Boolean
Dim lastToken = node.GetLastToken(includeZeroWidth:=True)
If lastToken.TrailingTrivia.Count = 0 Then
Return True
End If
Return Not lastToken _
.TrailingTrivia _
.Where(Function(t) t.Kind = SyntaxKind.SkippedTokensTrivia) _
.SelectMany(Function(t) DirectCast(t.GetStructure(), SkippedTokensTriviaSyntax).Tokens) _
.Any(Function(t) kinds.Contains(t.Kind))
End Function
Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitIfStatement(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword)
End Function
Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitIfDirectiveTrivia(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword)
End Function
Public Overrides Function VisitElseIfStatement(node As ElseIfStatementSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitElseIfStatement(node), Function(n) n.ThenKeyword, SyntaxKind.ThenKeyword)
End Function
Public Overrides Function VisitTypeArgumentList(node As TypeArgumentListSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitTypeArgumentList(node), Function(n) n.OfKeyword, SyntaxKind.OfKeyword)
End Function
Public Overrides Function VisitTypeParameterList(node As TypeParameterListSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitTypeParameterList(node), Function(n) n.OfKeyword, SyntaxKind.OfKeyword)
End Function
Public Overrides Function VisitContinueStatement(node As ContinueStatementSyntax) As SyntaxNode
Return AddMissingOrOmittedTokenTransform(node, MyBase.VisitContinueStatement(node), Function(n) n.BlockKeyword, SyntaxKind.DoKeyword, SyntaxKind.ForKeyword, SyntaxKind.WhileKeyword)
End Function
Public Overrides Function VisitOptionStatement(node As OptionStatementSyntax) As SyntaxNode
Select Case node.NameKeyword.Kind
Case SyntaxKind.ExplicitKeyword,
SyntaxKind.InferKeyword,
SyntaxKind.StrictKeyword
Return AddMissingOrOmittedTokenTransform(node, node, Function(n) n.ValueKeyword, SyntaxKind.OnKeyword, SyntaxKind.OffKeyword)
Case Else
Return node
End Select
End Function
Public Overrides Function VisitSelectStatement(node As SelectStatementSyntax) As SyntaxNode
Dim newNode = DirectCast(MyBase.VisitSelectStatement(node), SelectStatementSyntax)
Return If(newNode.CaseKeyword.Kind = SyntaxKind.None,
newNode.WithCaseKeyword(SyntaxFactory.Token(SyntaxKind.CaseKeyword)),
newNode)
End Function
Private Function AddMissingOrOmittedTokenTransform(Of T As SyntaxNode)(
originalNode As T, node As SyntaxNode, tokenGetter As Func(Of T, SyntaxToken), ParamArray kinds As SyntaxKind()) As T
Dim newNode = DirectCast(node, T)
If Not CheckSkippedTriviaForMissingToken(originalNode, kinds) Then
Return newNode
End If
Dim newToken = tokenGetter(newNode)
Dim processedToken = ProcessToken(tokenGetter(originalNode), newToken, newNode)
If processedToken <> newToken Then
Dim replacedNode = ReplaceOrSetToken(newNode, newToken, processedToken)
Dim replacedToken = tokenGetter(replacedNode)
Dim previousToken = replacedToken.GetPreviousToken(includeZeroWidth:=True)
Dim fixedupNode As T = Nothing
If Not TryFixupTrivia(replacedNode, previousToken, replacedToken, fixedupNode) Then
Return newNode
End If
Return fixedupNode
End If
Return newNode
End Function
Private Function ProcessToken(originalToken As SyntaxToken, token As SyntaxToken, parent As SyntaxNode) As SyntaxToken
' special case omitted token case
If IsOmitted(originalToken) Then
Return ProcessOmittedToken(originalToken, token, parent)
End If
Dim span = originalToken.Span
If Not _spans.HasIntervalThatContains(span.Start, span.Length) Then
' token is outside of the provided span
Return token
End If
' token is not missing or if missing token is identifier there is not much we can do
If Not originalToken.IsMissing OrElse
originalToken.Kind = SyntaxKind.None OrElse
originalToken.Kind = SyntaxKind.IdentifierToken Then
Return token
End If
Return ProcessMissingToken(originalToken, token)
End Function
Private Shared Function ReplaceOrSetToken(Of T As SyntaxNode)(originalParent As T, tokenToFix As SyntaxToken, replacementToken As SyntaxToken) As T
If Not IsOmitted(tokenToFix) Then
Return originalParent.ReplaceToken(tokenToFix, replacementToken)
Else
Return DirectCast(SetOmittedToken(originalParent, replacementToken), T)
End If
End Function
Private Shared Function SetOmittedToken(originalParent As SyntaxNode, newToken As SyntaxToken) As SyntaxNode
Select Case newToken.Kind
Case SyntaxKind.ThenKeyword
' this can be regular If, an If directive, or an ElseIf
Dim regularIf = TryCast(originalParent, IfStatementSyntax)
If regularIf IsNot Nothing Then
Dim previousToken = regularIf.Condition.GetLastToken(includeZeroWidth:=True)
Dim nextToken = regularIf.GetLastToken.GetNextToken
If Not InvalidOmittedToken(previousToken, nextToken) Then
Return regularIf.WithThenKeyword(newToken)
End If
Else
Dim regularElseIf = TryCast(originalParent, ElseIfStatementSyntax)
If regularElseIf IsNot Nothing Then
Dim previousToken = regularElseIf.Condition.GetLastToken(includeZeroWidth:=True)
Dim nextToken = regularElseIf.GetLastToken.GetNextToken
If Not InvalidOmittedToken(previousToken, nextToken) Then
Return regularElseIf.WithThenKeyword(newToken)
End If
Else
Dim ifDirective = TryCast(originalParent, IfDirectiveTriviaSyntax)
If ifDirective IsNot Nothing Then
Dim previousToken = ifDirective.Condition.GetLastToken(includeZeroWidth:=True)
Dim nextToken = ifDirective.GetLastToken.GetNextToken
If Not InvalidOmittedToken(previousToken, nextToken) Then
Return ifDirective.WithThenKeyword(newToken)
End If
End If
End If
End If
Case SyntaxKind.OnKeyword
Dim optionStatement = TryCast(originalParent, OptionStatementSyntax)
If optionStatement IsNot Nothing Then
Return optionStatement.WithValueKeyword(newToken)
End If
End Select
Return originalParent
End Function
Private Shared Function IsOmitted(token As SyntaxToken) As Boolean
Return token.Kind = SyntaxKind.None
End Function
Private Shared Function ProcessOmittedToken(originalToken As SyntaxToken, token As SyntaxToken, parent As SyntaxNode) As SyntaxToken
' multiline if statement with missing then keyword case
If TypeOf parent Is IfStatementSyntax Then
Dim ifStatement = DirectCast(parent, IfStatementSyntax)
If Exist(ifStatement.Condition) AndAlso ifStatement.ThenKeyword = originalToken Then
Return If(parent.GetAncestor(Of MultiLineIfBlockSyntax)() IsNot Nothing, CreateOmittedToken(token, SyntaxKind.ThenKeyword), token)
End If
End If
If TryCast(parent, IfDirectiveTriviaSyntax)?.ThenKeyword = originalToken Then
Return CreateOmittedToken(token, SyntaxKind.ThenKeyword)
ElseIf TryCast(parent, ElseIfStatementSyntax)?.ThenKeyword = originalToken Then
Return If(parent.GetAncestor(Of ElseIfBlockSyntax)() IsNot Nothing, CreateOmittedToken(token, SyntaxKind.ThenKeyword), token)
ElseIf TryCast(parent, OptionStatementSyntax)?.ValueKeyword = originalToken Then
Return CreateOmittedToken(token, SyntaxKind.OnKeyword)
End If
Return token
End Function
Private Shared Function InvalidOmittedToken(previousToken As SyntaxToken, nextToken As SyntaxToken) As Boolean
' if previous token has a problem, don't bother
If previousToken.IsMissing OrElse previousToken.IsSkipped OrElse previousToken.Kind = 0 Then
Return True
End If
' if next token has a problem, do little bit more check
' if there is no next token, it is okay to insert the missing token
If nextToken.Kind = 0 Then
Return False
End If
' if next token is missing or skipped, check whether it has EOL
If nextToken.IsMissing OrElse nextToken.IsSkipped Then
Return Not previousToken.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia) And
Not nextToken.LeadingTrivia.Any(SyntaxKind.EndOfLineTrivia)
End If
Return False
End Function
Private Shared Function Exist(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso node.Span.Length > 0
End Function
Private Shared Function ProcessMissingToken(originalToken As SyntaxToken, token As SyntaxToken) As SyntaxToken
' auto insert missing "Of" keyword in type argument list
If TryCast(originalToken.Parent, TypeArgumentListSyntax)?.OfKeyword = originalToken Then
Return CreateMissingToken(token)
ElseIf TryCast(originalToken.Parent, TypeParameterListSyntax)?.OfKeyword = originalToken Then
Return CreateMissingToken(token)
ElseIf TryCast(originalToken.Parent, ContinueStatementSyntax)?.BlockKeyword = originalToken Then
Return CreateMissingToken(token)
End If
Return token
End Function
Private Shared Function CreateMissingToken(token As SyntaxToken) As SyntaxToken
Return CreateToken(token, token.Kind)
End Function
Private Shared Function CreateOmittedToken(token As SyntaxToken, kind As SyntaxKind) As SyntaxToken
Return CreateToken(token, kind)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Test/Syntax/Parser/VisualBasicParseOptionsTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Globalization
Imports System.Linq
Imports Roslyn.Test.Utilities
Public Class VisualBasicParseOptionsTests
Inherits BasicTestBase
Private Sub TestProperty(Of T)(factory As Func(Of VisualBasicParseOptions, T, VisualBasicParseOptions), getter As Func(Of VisualBasicParseOptions, T), validValue As T)
Dim oldOpt1 = VisualBasicParseOptions.Default
Dim newOpt1 = factory(oldOpt1, validValue)
Dim newOpt2 = factory(newOpt1, validValue)
Assert.Equal(validValue, getter(newOpt1))
Assert.Same(newOpt2, newOpt1)
End Sub
<Fact>
Public Sub WithXxx()
TestProperty(Function(old, value) old.WithKind(value), Function(opt) opt.Kind, SourceCodeKind.Script)
TestProperty(Function(old, value) old.WithLanguageVersion(value), Function(opt) opt.LanguageVersion, LanguageVersion.VisualBasic9)
TestProperty(Function(old, value) old.WithDocumentationMode(value), Function(opt) opt.DocumentationMode, DocumentationMode.None)
End Sub
<Fact>
Public Sub WithLatestLanguageVersion()
Dim oldOpt1 = VisualBasicParseOptions.Default
Dim newOpt1 = oldOpt1.WithLanguageVersion(LanguageVersion.Latest)
Dim newOpt2 = newOpt1.WithLanguageVersion(LanguageVersion.Latest)
Assert.Equal(LanguageVersion.Latest.MapSpecifiedToEffectiveVersion, newOpt1.LanguageVersion)
Assert.Equal(LanguageVersion.Latest.MapSpecifiedToEffectiveVersion, newOpt2.LanguageVersion)
newOpt1 = oldOpt1.WithLanguageVersion(LanguageVersion.Default)
newOpt2 = newOpt1.WithLanguageVersion(LanguageVersion.Default)
Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion, newOpt1.LanguageVersion)
Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion, newOpt2.LanguageVersion)
End Sub
<Fact>
Public Sub WithPreprocessorSymbols()
Dim syms = ImmutableArray.Create(New KeyValuePair(Of String, Object)("A", 1),
New KeyValuePair(Of String, Object)("B", 2),
New KeyValuePair(Of String, Object)("C", 3))
TestProperty(Function(old, value) old.WithPreprocessorSymbols(value), Function(opt) opt.PreprocessorSymbols, syms)
Assert.Equal(0, VisualBasicParseOptions.Default.WithPreprocessorSymbols(syms).WithPreprocessorSymbols(CType(Nothing, ImmutableArray(Of KeyValuePair(Of String, Object)))).PreprocessorSymbols.Length)
Assert.Equal(0, VisualBasicParseOptions.Default.WithPreprocessorSymbols(syms).WithPreprocessorSymbols(DirectCast(Nothing, IEnumerable(Of KeyValuePair(Of String, Object)))).PreprocessorSymbols.Length)
Assert.Equal(0, VisualBasicParseOptions.Default.WithPreprocessorSymbols(syms).WithPreprocessorSymbols(DirectCast(Nothing, KeyValuePair(Of String, Object)())).PreprocessorSymbols.Length)
End Sub
<Fact>
Public Sub PredefinedPreprocessorSymbolsTests()
Dim options = VisualBasicParseOptions.Default
Dim empty = ImmutableArray.Create(Of KeyValuePair(Of String, Object))()
Dim symbols = AddPredefinedPreprocessorSymbols(OutputKind.NetModule)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "module")}, symbols.AsEnumerable)
' if the symbols are already there, don't change their values
symbols = AddPredefinedPreprocessorSymbols(OutputKind.DynamicallyLinkedLibrary, symbols)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "module")}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication,
{New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123)})
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123)}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication,
New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123))
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123)}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication, empty)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "exe")}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication, empty)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "winexe")}, symbols.AsEnumerable)
End Sub
<Fact>
Public Sub CurrentVersionNumber()
Dim highest = System.Enum.
GetValues(GetType(LanguageVersion)).
Cast(Of LanguageVersion).
Where(Function(x) x <> LanguageVersion.Latest).
Max().
ToDisplayString()
Assert.Equal(highest, PredefinedPreprocessorSymbols.CurrentVersionNumber.ToString(CultureInfo.InvariantCulture))
End Sub
<Fact, WorkItem(21094, "https://github.com/dotnet/roslyn/issues/21094")>
Public Sub CurrentVersionNumberIsCultureIndependent()
Dim currentCulture = CultureInfo.CurrentCulture
Try
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture
Dim invariantCultureVersion = PredefinedPreprocessorSymbols.CurrentVersionNumber
' cs-CZ uses decimal comma, which can cause issues
CultureInfo.CurrentCulture = New CultureInfo("cs-CZ", useUserOverride:=False)
Dim czechCultureVersion = PredefinedPreprocessorSymbols.CurrentVersionNumber
Assert.Equal(invariantCultureVersion, czechCultureVersion)
Finally
CultureInfo.CurrentCulture = currentCulture
End Try
End Sub
<Fact>
Public Sub PredefinedPreprocessorSymbols_Win8()
Dim options = VisualBasicParseOptions.Default
Dim symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsRuntimeApplication)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "appcontainerexe")}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsRuntimeMetadata)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "winmdobj")}, symbols.AsEnumerable)
End Sub
<Fact>
Public Sub ParseOptionsPass()
ParseAndVerify(<![CDATA[
Option strict
Option strict on
Option strict off
]]>)
ParseAndVerify(<![CDATA[
Option infer
Option infer on
option infer off
]]>)
ParseAndVerify(<![CDATA[
option explicit
Option explicit On
Option explicit off
]]>)
ParseAndVerify(<![CDATA[
Option compare text
Option compare binary
]]>)
End Sub
<Fact()>
Public Sub BC30208ERR_ExpectedOptionCompare()
ParseAndVerify(<![CDATA[
Option text
]]>,
<errors>
<error id="30208"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30979ERR_InvalidOptionInfer()
ParseAndVerify(<![CDATA[
Option infer xyz
]]>,
<errors>
<error id="30979"/>
</errors>)
End Sub
<Fact()>
Public Sub BC31141ERR_InvalidOptionStrictCustom()
ParseAndVerify(<![CDATA[
Option strict custom
]]>,
<errors>
<error id="31141"/>
</errors>)
End Sub
<Fact, WorkItem(536060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536060")>
Public Sub BC30620ERR_InvalidOptionStrict_FollowedByAssemblyAttribute()
ParseAndVerify(<![CDATA[
Option Strict False
<Assembly: CLSCompliant(True)>
]]>,
<errors>
<error id="30620"/>
</errors>)
End Sub
<Fact, WorkItem(536067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536067")>
Public Sub BC30627ERR_OptionStmtWrongOrder()
ParseAndVerify(<![CDATA[
Imports System
Option Infer On
]]>,
<errors>
<error id="30627"/>
</errors>)
End Sub
<Fact, WorkItem(536362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536362")>
Public Sub BC30206ERR_ExpectedForOptionStmt_NullReferenceException()
ParseAndVerify(<![CDATA[
Option
]]>,
<errors>
<error id="30206"/>
</errors>)
ParseAndVerify(<![CDATA[
Option on
]]>,
<errors>
<error id="30206"/>
</errors>)
End Sub
<Fact, WorkItem(536432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536432")>
Public Sub BC30205ERR_ExpectedEOS_ParseOption_ExtraSyntaxAtEOL()
ParseAndVerify(<![CDATA[
Option Infer On O
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
''' <summary>
''' If this test fails, please update the <see cref="ParseOptions.GetHashCode" />
''' And <see cref="ParseOptions.Equals" /> methods to
''' make sure they are doing the right thing with your New field And then update the baseline
''' here.
''' </summary>
<Fact>
Public Sub TestFieldsForEqualsAndGetHashCode()
ReflectionAssert.AssertPublicAndInternalFieldsAndProperties(
(GetType(VisualBasicParseOptions)),
"Features",
"Language",
"LanguageVersion",
"PreprocessorSymbolNames",
"PreprocessorSymbols",
"SpecifiedLanguageVersion")
End Sub
<Fact>
Public Sub SpecifiedKindIsMappedCorrectly()
Dim options = New VisualBasicParseOptions()
Assert.Equal(SourceCodeKind.Regular, options.Kind)
Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind)
options.Errors.Verify()
options = New VisualBasicParseOptions(kind:=SourceCodeKind.Regular)
Assert.Equal(SourceCodeKind.Regular, options.Kind)
Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind)
options.Errors.Verify()
options = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Assert.Equal(SourceCodeKind.Script, options.Kind)
Assert.Equal(SourceCodeKind.Script, options.SpecifiedKind)
options.Errors.Verify()
#Disable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
Assert.Equal(SourceCodeKind.Script, options.Kind)
Assert.Equal(SourceCodeKind.Interactive, options.SpecifiedKind)
#Enable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1))
options = New VisualBasicParseOptions(kind:=CType(Int32.MinValue, SourceCodeKind))
Assert.Equal(SourceCodeKind.Regular, options.Kind)
Assert.Equal(CType(Int32.MinValue, SourceCodeKind), options.SpecifiedKind)
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("-2147483648").WithLocation(1, 1))
End Sub
<Fact>
Public Sub TwoOptionsWithDifferentSpecifiedKindShouldNotHaveTheSameHashCodes()
Dim options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Dim options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Assert.Equal(options1.GetHashCode(), options2.GetHashCode())
' They both map internally to SourceCodeKind.Script
#Disable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
#Enable Warning BC40000 ' SourceCodeKind.Interactive Is obsolete
Assert.NotEqual(options1.GetHashCode(), options2.GetHashCode())
End Sub
<Fact>
Public Sub TwoOptionsWithDifferentSpecifiedKindShouldNotBeEqual()
Dim options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Dim options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Assert.True(options1.Equals(options2))
' They both map internally to SourceCodeKind.Script
#Disable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
#Enable Warning BC40000 ' SourceCodeKind.Interactive Is obsolete
Assert.False(options1.Equals(options2))
End Sub
<Fact>
Public Sub BadSourceCodeKindShouldProduceDiagnostics()
#Disable Warning BC40000 ' Type Or member Is obsolete
Dim options = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
#Enable Warning BC40000 ' Type Or member Is obsolete
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadDocumentationModeShouldProduceDiagnostics()
Dim options = New VisualBasicParseOptions(documentationMode:=CType(100, DocumentationMode))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadLanguageVersionShouldProduceDiagnostics()
Dim options = New VisualBasicParseOptions(languageVersion:=DirectCast(10000, LanguageVersion))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("test", Nothing)
symbols.Add("1", Nothing)
Dim options = New VisualBasicParseOptions(preprocessorSymbols:=symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "1").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadSourceCodeKindShouldProduceDiagnostics_WithVariation()
#Disable Warning BC40000 ' Type Or member Is obsolete
Dim options = New VisualBasicParseOptions().WithKind(SourceCodeKind.Interactive)
#Enable Warning BC40000 ' Type Or member Is obsolete
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadDocumentationModeShouldProduceDiagnostics_WithVariation()
Dim options = New VisualBasicParseOptions().WithDocumentationMode(CType(100, DocumentationMode))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadLanguageVersionShouldProduceDiagnostics_WithVariation()
Dim options = New VisualBasicParseOptions().WithLanguageVersion(DirectCast(10000, LanguageVersion))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_EmptyString()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_WhiteSpaceString()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add(" ", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", " ").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithDots()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("Good", Nothing)
symbols.Add("Bad.Symbol", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "Bad.Symbol").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithSlashes()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("Good", Nothing)
symbols.Add("Bad\\Symbol", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "Bad\\Symbol").WithLocation(1, 1))
End Sub
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Globalization
Imports System.Linq
Imports Roslyn.Test.Utilities
Public Class VisualBasicParseOptionsTests
Inherits BasicTestBase
Private Sub TestProperty(Of T)(factory As Func(Of VisualBasicParseOptions, T, VisualBasicParseOptions), getter As Func(Of VisualBasicParseOptions, T), validValue As T)
Dim oldOpt1 = VisualBasicParseOptions.Default
Dim newOpt1 = factory(oldOpt1, validValue)
Dim newOpt2 = factory(newOpt1, validValue)
Assert.Equal(validValue, getter(newOpt1))
Assert.Same(newOpt2, newOpt1)
End Sub
<Fact>
Public Sub WithXxx()
TestProperty(Function(old, value) old.WithKind(value), Function(opt) opt.Kind, SourceCodeKind.Script)
TestProperty(Function(old, value) old.WithLanguageVersion(value), Function(opt) opt.LanguageVersion, LanguageVersion.VisualBasic9)
TestProperty(Function(old, value) old.WithDocumentationMode(value), Function(opt) opt.DocumentationMode, DocumentationMode.None)
End Sub
<Fact>
Public Sub WithLatestLanguageVersion()
Dim oldOpt1 = VisualBasicParseOptions.Default
Dim newOpt1 = oldOpt1.WithLanguageVersion(LanguageVersion.Latest)
Dim newOpt2 = newOpt1.WithLanguageVersion(LanguageVersion.Latest)
Assert.Equal(LanguageVersion.Latest.MapSpecifiedToEffectiveVersion, newOpt1.LanguageVersion)
Assert.Equal(LanguageVersion.Latest.MapSpecifiedToEffectiveVersion, newOpt2.LanguageVersion)
newOpt1 = oldOpt1.WithLanguageVersion(LanguageVersion.Default)
newOpt2 = newOpt1.WithLanguageVersion(LanguageVersion.Default)
Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion, newOpt1.LanguageVersion)
Assert.Equal(LanguageVersion.Default.MapSpecifiedToEffectiveVersion, newOpt2.LanguageVersion)
End Sub
<Fact>
Public Sub WithPreprocessorSymbols()
Dim syms = ImmutableArray.Create(New KeyValuePair(Of String, Object)("A", 1),
New KeyValuePair(Of String, Object)("B", 2),
New KeyValuePair(Of String, Object)("C", 3))
TestProperty(Function(old, value) old.WithPreprocessorSymbols(value), Function(opt) opt.PreprocessorSymbols, syms)
Assert.Equal(0, VisualBasicParseOptions.Default.WithPreprocessorSymbols(syms).WithPreprocessorSymbols(CType(Nothing, ImmutableArray(Of KeyValuePair(Of String, Object)))).PreprocessorSymbols.Length)
Assert.Equal(0, VisualBasicParseOptions.Default.WithPreprocessorSymbols(syms).WithPreprocessorSymbols(DirectCast(Nothing, IEnumerable(Of KeyValuePair(Of String, Object)))).PreprocessorSymbols.Length)
Assert.Equal(0, VisualBasicParseOptions.Default.WithPreprocessorSymbols(syms).WithPreprocessorSymbols(DirectCast(Nothing, KeyValuePair(Of String, Object)())).PreprocessorSymbols.Length)
End Sub
<Fact>
Public Sub PredefinedPreprocessorSymbolsTests()
Dim options = VisualBasicParseOptions.Default
Dim empty = ImmutableArray.Create(Of KeyValuePair(Of String, Object))()
Dim symbols = AddPredefinedPreprocessorSymbols(OutputKind.NetModule)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "module")}, symbols.AsEnumerable)
' if the symbols are already there, don't change their values
symbols = AddPredefinedPreprocessorSymbols(OutputKind.DynamicallyLinkedLibrary, symbols)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "module")}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication,
{New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123)})
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123)}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication,
New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123))
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", "Goo"), New KeyValuePair(Of String, Object)("TARGET", 123)}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication, empty)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "exe")}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication, empty)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "winexe")}, symbols.AsEnumerable)
End Sub
<Fact>
Public Sub CurrentVersionNumber()
Dim highest = System.Enum.
GetValues(GetType(LanguageVersion)).
Cast(Of LanguageVersion).
Where(Function(x) x <> LanguageVersion.Latest).
Max().
ToDisplayString()
Assert.Equal(highest, PredefinedPreprocessorSymbols.CurrentVersionNumber.ToString(CultureInfo.InvariantCulture))
End Sub
<Fact, WorkItem(21094, "https://github.com/dotnet/roslyn/issues/21094")>
Public Sub CurrentVersionNumberIsCultureIndependent()
Dim currentCulture = CultureInfo.CurrentCulture
Try
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture
Dim invariantCultureVersion = PredefinedPreprocessorSymbols.CurrentVersionNumber
' cs-CZ uses decimal comma, which can cause issues
CultureInfo.CurrentCulture = New CultureInfo("cs-CZ", useUserOverride:=False)
Dim czechCultureVersion = PredefinedPreprocessorSymbols.CurrentVersionNumber
Assert.Equal(invariantCultureVersion, czechCultureVersion)
Finally
CultureInfo.CurrentCulture = currentCulture
End Try
End Sub
<Fact>
Public Sub PredefinedPreprocessorSymbols_Win8()
Dim options = VisualBasicParseOptions.Default
Dim symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsRuntimeApplication)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "appcontainerexe")}, symbols.AsEnumerable)
symbols = AddPredefinedPreprocessorSymbols(OutputKind.WindowsRuntimeMetadata)
AssertEx.SetEqual({New KeyValuePair(Of String, Object)("VBC_VER", PredefinedPreprocessorSymbols.CurrentVersionNumber), New KeyValuePair(Of String, Object)("TARGET", "winmdobj")}, symbols.AsEnumerable)
End Sub
<Fact>
Public Sub ParseOptionsPass()
ParseAndVerify(<![CDATA[
Option strict
Option strict on
Option strict off
]]>)
ParseAndVerify(<![CDATA[
Option infer
Option infer on
option infer off
]]>)
ParseAndVerify(<![CDATA[
option explicit
Option explicit On
Option explicit off
]]>)
ParseAndVerify(<![CDATA[
Option compare text
Option compare binary
]]>)
End Sub
<Fact()>
Public Sub BC30208ERR_ExpectedOptionCompare()
ParseAndVerify(<![CDATA[
Option text
]]>,
<errors>
<error id="30208"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30979ERR_InvalidOptionInfer()
ParseAndVerify(<![CDATA[
Option infer xyz
]]>,
<errors>
<error id="30979"/>
</errors>)
End Sub
<Fact()>
Public Sub BC31141ERR_InvalidOptionStrictCustom()
ParseAndVerify(<![CDATA[
Option strict custom
]]>,
<errors>
<error id="31141"/>
</errors>)
End Sub
<Fact, WorkItem(536060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536060")>
Public Sub BC30620ERR_InvalidOptionStrict_FollowedByAssemblyAttribute()
ParseAndVerify(<![CDATA[
Option Strict False
<Assembly: CLSCompliant(True)>
]]>,
<errors>
<error id="30620"/>
</errors>)
End Sub
<Fact, WorkItem(536067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536067")>
Public Sub BC30627ERR_OptionStmtWrongOrder()
ParseAndVerify(<![CDATA[
Imports System
Option Infer On
]]>,
<errors>
<error id="30627"/>
</errors>)
End Sub
<Fact, WorkItem(536362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536362")>
Public Sub BC30206ERR_ExpectedForOptionStmt_NullReferenceException()
ParseAndVerify(<![CDATA[
Option
]]>,
<errors>
<error id="30206"/>
</errors>)
ParseAndVerify(<![CDATA[
Option on
]]>,
<errors>
<error id="30206"/>
</errors>)
End Sub
<Fact, WorkItem(536432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536432")>
Public Sub BC30205ERR_ExpectedEOS_ParseOption_ExtraSyntaxAtEOL()
ParseAndVerify(<![CDATA[
Option Infer On O
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
''' <summary>
''' If this test fails, please update the <see cref="ParseOptions.GetHashCode" />
''' And <see cref="ParseOptions.Equals" /> methods to
''' make sure they are doing the right thing with your New field And then update the baseline
''' here.
''' </summary>
<Fact>
Public Sub TestFieldsForEqualsAndGetHashCode()
ReflectionAssert.AssertPublicAndInternalFieldsAndProperties(
(GetType(VisualBasicParseOptions)),
"Features",
"Language",
"LanguageVersion",
"PreprocessorSymbolNames",
"PreprocessorSymbols",
"SpecifiedLanguageVersion")
End Sub
<Fact>
Public Sub SpecifiedKindIsMappedCorrectly()
Dim options = New VisualBasicParseOptions()
Assert.Equal(SourceCodeKind.Regular, options.Kind)
Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind)
options.Errors.Verify()
options = New VisualBasicParseOptions(kind:=SourceCodeKind.Regular)
Assert.Equal(SourceCodeKind.Regular, options.Kind)
Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind)
options.Errors.Verify()
options = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Assert.Equal(SourceCodeKind.Script, options.Kind)
Assert.Equal(SourceCodeKind.Script, options.SpecifiedKind)
options.Errors.Verify()
#Disable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
Assert.Equal(SourceCodeKind.Script, options.Kind)
Assert.Equal(SourceCodeKind.Interactive, options.SpecifiedKind)
#Enable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1))
options = New VisualBasicParseOptions(kind:=CType(Int32.MinValue, SourceCodeKind))
Assert.Equal(SourceCodeKind.Regular, options.Kind)
Assert.Equal(CType(Int32.MinValue, SourceCodeKind), options.SpecifiedKind)
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("-2147483648").WithLocation(1, 1))
End Sub
<Fact>
Public Sub TwoOptionsWithDifferentSpecifiedKindShouldNotHaveTheSameHashCodes()
Dim options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Dim options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Assert.Equal(options1.GetHashCode(), options2.GetHashCode())
' They both map internally to SourceCodeKind.Script
#Disable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
#Enable Warning BC40000 ' SourceCodeKind.Interactive Is obsolete
Assert.NotEqual(options1.GetHashCode(), options2.GetHashCode())
End Sub
<Fact>
Public Sub TwoOptionsWithDifferentSpecifiedKindShouldNotBeEqual()
Dim options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Dim options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
Assert.True(options1.Equals(options2))
' They both map internally to SourceCodeKind.Script
#Disable Warning BC40000 ' SourceCodeKind.Interactive is obsolete
options1 = New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
options2 = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
#Enable Warning BC40000 ' SourceCodeKind.Interactive Is obsolete
Assert.False(options1.Equals(options2))
End Sub
<Fact>
Public Sub BadSourceCodeKindShouldProduceDiagnostics()
#Disable Warning BC40000 ' Type Or member Is obsolete
Dim options = New VisualBasicParseOptions(kind:=SourceCodeKind.Interactive)
#Enable Warning BC40000 ' Type Or member Is obsolete
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadDocumentationModeShouldProduceDiagnostics()
Dim options = New VisualBasicParseOptions(documentationMode:=CType(100, DocumentationMode))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadLanguageVersionShouldProduceDiagnostics()
Dim options = New VisualBasicParseOptions(languageVersion:=DirectCast(10000, LanguageVersion))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("test", Nothing)
symbols.Add("1", Nothing)
Dim options = New VisualBasicParseOptions(preprocessorSymbols:=symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "1").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadSourceCodeKindShouldProduceDiagnostics_WithVariation()
#Disable Warning BC40000 ' Type Or member Is obsolete
Dim options = New VisualBasicParseOptions().WithKind(SourceCodeKind.Interactive)
#Enable Warning BC40000 ' Type Or member Is obsolete
options.Errors.Verify(Diagnostic(ERRID.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadDocumentationModeShouldProduceDiagnostics_WithVariation()
Dim options = New VisualBasicParseOptions().WithDocumentationMode(CType(100, DocumentationMode))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadLanguageVersionShouldProduceDiagnostics_WithVariation()
Dim options = New VisualBasicParseOptions().WithLanguageVersion(DirectCast(10000, LanguageVersion))
options.Errors.Verify(Diagnostic(ERRID.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_EmptyString()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_WhiteSpaceString()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add(" ", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", " ").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithDots()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("Good", Nothing)
symbols.Add("Bad.Symbol", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "Bad.Symbol").WithLocation(1, 1))
End Sub
<Fact>
Public Sub BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithSlashes()
Dim symbols = New Dictionary(Of String, Object)
symbols.Add("Good", Nothing)
symbols.Add("Bad\\Symbol", Nothing)
Dim options = New VisualBasicParseOptions().WithPreprocessorSymbols(symbols)
options.Errors.Verify(Diagnostic(ERRID.ERR_ConditionalCompilationConstantNotValid).WithArguments("Identifier expected.", "Bad\\Symbol").WithLocation(1, 1))
End Sub
End Class
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/CodeFixes/Async/AbstractConvertToAsyncCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes.Async
{
internal abstract partial class AbstractConvertToAsyncCodeFixProvider : CodeFixProvider
{
protected abstract Task<string> GetDescriptionAsync(Diagnostic diagnostic, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken);
protected abstract Task<Tuple<SyntaxTree, SyntaxNode>> GetRootInOtherSyntaxTreeAsync(SyntaxNode node, SemanticModel semanticModel, Diagnostic diagnostic, CancellationToken cancellationToken);
public override FixAllProvider GetFixAllProvider()
{
// Fix All is not supported by this code fix
// https://github.com/dotnet/roslyn/issues/34463
return null;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (!TryGetNode(root, context.Span, out var node))
{
return;
}
var diagnostic = context.Diagnostics.FirstOrDefault();
var codeAction = await GetCodeActionAsync(
node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false);
if (codeAction != null)
{
context.RegisterCodeFix(codeAction, context.Diagnostics);
}
}
private static bool TryGetNode(SyntaxNode root, TextSpan span, out SyntaxNode node)
{
node = null;
var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>();
if (!ancestors.Any())
{
return false;
}
node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);
return node != null;
}
private async Task<CodeAction> GetCodeActionAsync(
SyntaxNode node, Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var result = await GetRootInOtherSyntaxTreeAsync(node, semanticModel, diagnostic, cancellationToken).ConfigureAwait(false);
if (result == null)
return null;
var syntaxTree = result.Item1;
var newRoot = result.Item2;
var otherDocument = document.Project.Solution.GetDocument(syntaxTree);
return new MyCodeAction(
await GetDescriptionAsync(diagnostic, node, semanticModel, cancellationToken).ConfigureAwait(false),
token => Task.FromResult(otherDocument.WithSyntaxRoot(newRoot)));
}
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.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes.Async
{
internal abstract partial class AbstractConvertToAsyncCodeFixProvider : CodeFixProvider
{
protected abstract Task<string> GetDescriptionAsync(Diagnostic diagnostic, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken);
protected abstract Task<Tuple<SyntaxTree, SyntaxNode>> GetRootInOtherSyntaxTreeAsync(SyntaxNode node, SemanticModel semanticModel, Diagnostic diagnostic, CancellationToken cancellationToken);
public override FixAllProvider GetFixAllProvider()
{
// Fix All is not supported by this code fix
// https://github.com/dotnet/roslyn/issues/34463
return null;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (!TryGetNode(root, context.Span, out var node))
{
return;
}
var diagnostic = context.Diagnostics.FirstOrDefault();
var codeAction = await GetCodeActionAsync(
node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false);
if (codeAction != null)
{
context.RegisterCodeFix(codeAction, context.Diagnostics);
}
}
private static bool TryGetNode(SyntaxNode root, TextSpan span, out SyntaxNode node)
{
node = null;
var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>();
if (!ancestors.Any())
{
return false;
}
node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);
return node != null;
}
private async Task<CodeAction> GetCodeActionAsync(
SyntaxNode node, Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var result = await GetRootInOtherSyntaxTreeAsync(node, semanticModel, diagnostic, cancellationToken).ConfigureAwait(false);
if (result == null)
return null;
var syntaxTree = result.Item1;
var newRoot = result.Item2;
var otherDocument = document.Project.Solution.GetDocument(syntaxTree);
return new MyCodeAction(
await GetDescriptionAsync(diagnostic, node, semanticModel, cancellationToken).ConfigureAwait(false),
token => Task.FromResult(otherDocument.WithSyntaxRoot(newRoot)));
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Analyzers/VisualBasic/CodeFixes/ConvertTypeOfToNameOf/VisualBasicConvertGetTypeToNameOfCodeFixProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.ConvertTypeOfToNameOf
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertTypeOfToNameOf
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), [Shared]>
Friend Class VisualBasicConvertGetTypeToNameOfCodeFixProvider
Inherits AbstractConvertTypeOfToNameOfCodeFixProvider
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function GetCodeFixTitle() As String
Return VisualBasicCodeFixesResources.Convert_GetType_to_NameOf
End Function
Protected Overrides Function GetSymbolTypeExpression(semanticModel As SemanticModel, node As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode
Dim expression = DirectCast(node, MemberAccessExpressionSyntax).Expression
Dim type = DirectCast(expression, GetTypeExpressionSyntax).Type
Dim symbolType = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol.GetSymbolType()
Dim symbolExpression = symbolType.GenerateExpressionSyntax()
If TypeOf symbolExpression Is IdentifierNameSyntax OrElse TypeOf symbolExpression Is MemberAccessExpressionSyntax Then
Return symbolExpression
End If
If TypeOf symbolExpression Is QualifiedNameSyntax Then
Dim qualifiedName = DirectCast(symbolExpression, QualifiedNameSyntax)
Return SyntaxFactory.SimpleMemberAccessExpression(qualifiedName.Left, qualifiedName.Right) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
Return Nothing
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.ConvertTypeOfToNameOf
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertTypeOfToNameOf
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), [Shared]>
Friend Class VisualBasicConvertGetTypeToNameOfCodeFixProvider
Inherits AbstractConvertTypeOfToNameOfCodeFixProvider
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function GetCodeFixTitle() As String
Return VisualBasicCodeFixesResources.Convert_GetType_to_NameOf
End Function
Protected Overrides Function GetSymbolTypeExpression(semanticModel As SemanticModel, node As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode
Dim expression = DirectCast(node, MemberAccessExpressionSyntax).Expression
Dim type = DirectCast(expression, GetTypeExpressionSyntax).Type
Dim symbolType = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol.GetSymbolType()
Dim symbolExpression = symbolType.GenerateExpressionSyntax()
If TypeOf symbolExpression Is IdentifierNameSyntax OrElse TypeOf symbolExpression Is MemberAccessExpressionSyntax Then
Return symbolExpression
End If
If TypeOf symbolExpression Is QualifiedNameSyntax Then
Dim qualifiedName = DirectCast(symbolExpression, QualifiedNameSyntax)
Return SyntaxFactory.SimpleMemberAccessExpression(qualifiedName.Left, qualifiedName.Right) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
Return Nothing
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ITemporaryTextStorageWithName.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Represents a <see cref="ITemporaryStorageWithName"/> which is used to hold data for <see cref="SourceText"/>.
/// </summary>
internal interface ITemporaryTextStorageWithName : ITemporaryTextStorage, ITemporaryStorageWithName
{
/// <summary>
/// Gets the value for the <see cref="SourceText.ChecksumAlgorithm"/> property for the <see cref="SourceText"/>
/// represented by this temporary storage.
/// </summary>
SourceHashAlgorithm ChecksumAlgorithm { get; }
/// <summary>
/// Gets the value for the <see cref="SourceText.Encoding"/> property for the <see cref="SourceText"/>
/// represented by this temporary storage.
/// </summary>
Encoding? Encoding { get; }
/// <summary>
/// Gets the checksum for the <see cref="SourceText"/> represented by this temporary storage. This is equivalent
/// to calling <see cref="SourceText.GetChecksum"/>.
/// </summary>
ImmutableArray<byte> GetChecksum();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Represents a <see cref="ITemporaryStorageWithName"/> which is used to hold data for <see cref="SourceText"/>.
/// </summary>
internal interface ITemporaryTextStorageWithName : ITemporaryTextStorage, ITemporaryStorageWithName
{
/// <summary>
/// Gets the value for the <see cref="SourceText.ChecksumAlgorithm"/> property for the <see cref="SourceText"/>
/// represented by this temporary storage.
/// </summary>
SourceHashAlgorithm ChecksumAlgorithm { get; }
/// <summary>
/// Gets the value for the <see cref="SourceText.Encoding"/> property for the <see cref="SourceText"/>
/// represented by this temporary storage.
/// </summary>
Encoding? Encoding { get; }
/// <summary>
/// Gets the checksum for the <see cref="SourceText"/> represented by this temporary storage. This is equivalent
/// to calling <see cref="SourceText.GetChecksum"/>.
/// </summary>
ImmutableArray<byte> GetChecksum();
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/CSharpTest2/Recommendations/DescendingKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class DescendingKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOrderByExpr()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSecondExpr()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x, y $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBetweenExprs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x, y $$, z"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDot()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y
orderby x.$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterComma()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y
orderby x, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCloseParen()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x.ToString() $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCloseBracket()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x.ToString()[0] $$"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class DescendingKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOrderByExpr()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSecondExpr()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x, y $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBetweenExprs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x, y $$, z"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDot()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y
orderby x.$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterComma()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y
orderby x, $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCloseParen()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x.ToString() $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCloseBracket()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
orderby x.ToString()[0] $$"));
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ISwitchOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ISwitchOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_01()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_02()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
var x = 3;
input = x;
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Locals: Local_1: System.Int32 x
Sections:
ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input = x')
Left:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_03()
{
string source = @"
using System;
class Program
{
static void M(object input)
{
/*<bind>*/switch (input)
{
case int x:
case long y:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Sections:
ISwitchCaseOperation (2 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int x: ... break;')
Locals: Local_1: System.Int32 x
Local_2: System.Int64 y
Clauses:
IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int x:')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False)
IPatternCaseClauseOperation (Label Id: 2) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case long y:')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'long y') (InputType: System.Object, NarrowedType: System.Int64, DeclaredSymbol: System.Int64 y, MatchesNull: False)
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_04()
{
string source = @"
using System;
class Program
{
static void M(object input)
{
/*<bind>*/switch (input)
{
case int y:
var x = 3;
input = x + y;
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Locals: Local_1: System.Int32 x
Sections:
ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int y: ... break;')
Locals: Local_1: System.Int32 y
Clauses:
IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int y:')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False)
Body:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x + y;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'input = x + y')
Left:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'x + y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LabelsInSwitch_01()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
goto case 2;
case 2:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... oto case 2;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto case 2;')
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 2: ... break;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 2) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 2:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LabelsInSwitch_02()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
goto default;
default:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... to default;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto default;')
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'default: ... break;')
Clauses:
IDefaultCaseClauseOperation (Label Id: 2) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:')
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_01()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
default:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_02()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
default:
result = true;
break;
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_03()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
default:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_04()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_05()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 0:
bool x = true;
result = x;
break;
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [System.Boolean x]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'x = true')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x = true')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B6]
Leaving: {R2} {R1}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R2} {R1}
}
}
Block[B6] - Exit
Predecessors: [B3] [B4] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_06()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
default:
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1*2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_07()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
default:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1*2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_08()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 2:
default:
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2*2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_09()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
goto case 3;
case 2:
goto default;
case 3:
result = true;
break;
default:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B5]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '3')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B1] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Leaving: {R1}
Block[B5] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_10()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
goto case 3;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(9,17): error CS0159: No such label 'case 3:' within the scope of the goto statement
// goto case 3;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto case 3;").WithArguments("case 3:").WithLocation(9, 17),
// file.cs(8,13): error CS8070: Control cannot fall out of switch from final case label ('case 1:')
// case 1:
Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 13)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto case 3;')
Children(0)
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_11()
{
string source = @"
public sealed class MyClass
{
void M(bool result, long input)
/*<bind>*/{
switch (input)
{
default:
result = false;
break;
case 1:
result = result;
break;
default:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(14,13): error CS0152: The switch statement contains multiple cases with the label value 'default'
// default:
Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "default:").WithArguments("default").WithLocation(14, 13),
// file.cs(12,17): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// result = result;
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "result = result").WithLocation(12, 17)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = result;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = result')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B4] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B2] [B3] [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_12()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1L:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
// case 1L:
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1L')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitNumeric)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1, IsInvalid) (Syntax: '1L')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_13()
{
string source = @"
public sealed class MyClass
{
void M(bool result, MyClass input, MyClass other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
public static bool operator ==(MyClass x, MyClass y) => false;
public static bool operator !=(MyClass x, MyClass y) => true;
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: MyClass, NarrowedType: MyClass)
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_14()
{
string source = @"
public sealed class MyClass
{
void M(bool result, MyClass input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
public static bool operator ==(MyClass x, long y) => false;
public static bool operator !=(MyClass x, long y) => true;
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0029: Cannot implicitly convert type 'int' to 'MyClass'
// case 1:
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "MyClass").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_15()
{
string source = @"
public sealed class MyClass
{
void M(bool result, MyClass input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
public static implicit operator MyClass(long x) => null;
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case 1:
Diagnostic(ErrorCode.ERR_ConstantExpected, "1").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: MyClass MyClass.op_Implicit(System.Int64 x)) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: MyClass MyClass.op_Implicit(System.Int64 x))
(ImplicitUserDefined)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_16()
{
string source = @"
public sealed class MyClass
{
void M(bool result)
/*<bind>*/{
case 1:
result = false;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(5,16): error CS1513: } expected
// /*<bind>*/{
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 16),
// file.cs(6,19): error CS1002: ; expected
// case 1:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 19),
// file.cs(6,19): error CS1513: } expected
// case 1:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 19),
// file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_17()
{
string source = @"
public sealed class MyClass
{
void M(bool result)
/*<bind>*/{
default:
result = false;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(6,13): error CS8716: There is no target type for the default literal.
// default:
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 13),
// file.cs(6,20): error CS1002: ; expected
// default:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 20),
// file.cs(6,20): error CS1513: } expected
// default:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 20),
// file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'default')
Expression:
IDefaultValueOperation (OperationKind.DefaultValue, Type: ?, IsInvalid) (Syntax: 'default')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_18()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_19()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input)
/*<bind>*/{
switch (input)
{
case null:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'null')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_20()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input, int? other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_21()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input, int? other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
// case other:
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "other").WithArguments("int?", "int").WithLocation(8, 18),
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitNullable)
Operand:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_22()
{
string source = @"
public sealed class MyClass
{
void M(bool result, dynamic input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchIOperation_022()
{
string source = @"
public sealed class MyClass
{
void M(bool result, dynamic input)
{
/*<bind>*/switch (input)
{
case 1:
result = false;
break;
}/*</bind>*/
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
var expectedOperationTree =
@"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 2 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;')
Clauses:
IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_23()
{
string source = @"
public sealed class MyClass
{
void M(bool result, dynamic input, dynamic other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: dynamic, NarrowedType: dynamic)
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_24()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input1, int input2)
/*<bind>*/{
switch (input1 ?? input2)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input1')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1 ?? input2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_25()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input1, int input2, int input3)
/*<bind>*/{
switch (input3)
{
case input1 ?? input2:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case input1 ?? input2:
Diagnostic(ErrorCode.ERR_ConstantExpected, "input1 ?? input2").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input3')
Value:
IParameterReferenceOperation: input3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input3')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input3')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_26()
{
string source = @"
public sealed class MyClass
{
void M(int input1, MyClass input2)
/*<bind>*/{
switch (input1)
{
case 1:
input2?.ToString();
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1')
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input2')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2')
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2?.ToString();')
Expression:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2} {R1}
}
}
Block[B4] - Exit
Predecessors: [B1] [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_27()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_28()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input, int? other)
/*<bind>*/{
switch (input)
{
case other ?? 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other ?? 1:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other ?? 1").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other ?? 1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') (InputType: System.Object, NarrowedType: System.Object)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'other ?? 1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other ?? 1')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_29()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case int x:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [System.Int32 x]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False)
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R2} {R1}
}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_30()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input1, bool other2, bool other3, bool other4)
/*<bind>*/{
switch (input1)
{
case int x when (other2 ? other3 : other4) :
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [System.Int32 x]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input1')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False)
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: other2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: other3 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other3')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Block[B5] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: other4 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other4')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R2} {R1}
}
}
Block[B7] - Exit
Predecessors: [B2] [B4] [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_31()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
case 2:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B5]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '2')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '2') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Leaving: {R1}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B2] [B3] [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_32()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input, bool? guard)
/*<bind>*/{
switch (input)
{
case 1 when guard ?? throw null:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B6]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'guard')
Value:
IParameterReferenceOperation: guard (OperationKind.ParameterReference, Type: System.Boolean?) (Syntax: 'guard')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'guard')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( System.Boolean System.Boolean?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'guard')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard')
Arguments(0)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B1] [B3] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_33()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case 1 when guard:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,25): error CS0103: The name 'guard' does not exist in the current context
// case 1 when guard:
Diagnostic(ErrorCode.ERR_NameNotInContext, "guard").WithArguments("guard").WithLocation(8, 25)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B4]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'guard')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'guard')
Children(0)
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B1] [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_34()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1+TakeOutParam(3, out MyClass x1):
result = false;
break;
}
}/*</bind>*/
int TakeOutParam(int a, out MyClass b)
{
b = default;
return a;
}
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case 1+TakeOutParam(3, out MyClass x1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "1+TakeOutParam(3, out MyClass x1)").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [MyClass x1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+TakeOutPa ... MyClass x1)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+TakeOutPa ... MyClass x1)')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Right:
IInvocationOperation ( System.Int32 MyClass.TakeOutParam(System.Int32 a, out MyClass b)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... MyClass x1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'TakeOutParam')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out MyClass x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: MyClass, IsInvalid) (Syntax: 'MyClass x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: MyClass, IsInvalid) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R2} {R1}
}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_35()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input)
/*<bind>*/{
switch (input)
{
case 1+(input is int x1 ? x1 : 0):
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case 1+(input is int x1 ? x1 : 0):
Diagnostic(ErrorCode.ERR_ConstantExpected, "1+(input is int x1 ? x1 : 0)").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
Locals: [System.Int32 x1]
.locals {R3}
{
CaptureIds: [1] [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Jump if False (Regular) to Block[B4]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'input is int x1')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int x1') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x1, MatchesNull: False)
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1')
Value:
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+(input is ... 1 ? x1 : 0)')
Left:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input is int x1 ? x1 : 0')
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R3}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R2} {R1}
}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns, CompilerFeature.Dataflow)]
[Fact]
public void EmptySwitchExpressionFlow()
{
string source = @"
class Program
{
public static void Main()
/*<bind>*/{
var r = 1 switch { };
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(6,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// var r = 1 switch { };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 19),
// file.cs(6,19): error CS8506: No best type was found for the switch expression.
// var r = 1 switch { };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 19)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [? r]
CaptureIds: [0]
.locals {R2}
{
CaptureIds: [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Throw) Block[null]
IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: '1 switch { }')
Arguments(0)
Initializer:
null
Block[B3] - Block [UnReachable]
Predecessors (0)
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }')
Left:
ILocalReferenceOperation: r (IsDeclaration: True) (OperationKind.LocalReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: '1 switch { }')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit [UnReachable]
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_36()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case < 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[0];
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< 1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< 1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_37()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input, int other)
/*<bind>*/{
switch (input)
{
case < other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,20): error CS0150: A constant value is expected
// case < other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 20)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '< other')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null, IsInvalid) (Syntax: '< other') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_38()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case < (true ? 10 : 11):
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Next (Regular) Block[B5]
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< (true ? 10 : 11)')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_39()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case not < (true ? 10 : 11):
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Next (Regular) Block[B5]
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'not < (true ? 10 : 11)')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
INegatedPatternOperation (OperationKind.NegatedPattern, Type: null) (Syntax: 'not < (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32)
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_40()
{
string source = @"
public sealed class MyClass
{
bool M(char input)
/*<bind>*/{
switch (input)
{
case (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or '_':
return true;
}
return false;
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '(>= 'A' and ... 'z') or '_'')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input')
Pattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... 'z') or '_'') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'')
RightPattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'')
RightPattern:
IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'')
RightPattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'')
RightPattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: ''_'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: _) (Syntax: ''_'')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Leaving: {R1}
}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_41()
{
string source = @"
public sealed class MyClass
{
bool M(object input)
/*<bind>*/{
switch (input)
{
case int or long or ulong:
return true;
default:
return false;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int or long or ulong')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or ulong') (InputType: System.Object, NarrowedType: System.Object)
LeftPattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object)
LeftPattern:
ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32)
RightPattern:
ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64)
RightPattern:
ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'ulong') (InputType: System.Object, NarrowedType: System.UInt64, MatchedType: System.UInt64)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ISwitchOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_01()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_02()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
var x = 3;
input = x;
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Locals: Local_1: System.Int32 x
Sections:
ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input = x')
Left:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_03()
{
string source = @"
using System;
class Program
{
static void M(object input)
{
/*<bind>*/switch (input)
{
case int x:
case long y:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Sections:
ISwitchCaseOperation (2 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int x: ... break;')
Locals: Local_1: System.Int32 x
Local_2: System.Int64 y
Clauses:
IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int x:')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False)
IPatternCaseClauseOperation (Label Id: 2) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case long y:')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'long y') (InputType: System.Object, NarrowedType: System.Int64, DeclaredSymbol: System.Int64 y, MatchesNull: False)
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LocalsInSwitch_04()
{
string source = @"
using System;
class Program
{
static void M(object input)
{
/*<bind>*/switch (input)
{
case int y:
var x = 3;
input = x + y;
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Locals: Local_1: System.Int32 x
Sections:
ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int y: ... break;')
Locals: Local_1: System.Int32 y
Clauses:
IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int y:')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False)
Body:
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x + y;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'input = x + y')
Left:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'x + y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LabelsInSwitch_01()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
goto case 2;
case 2:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... oto case 2;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto case 2;')
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 2: ... break;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 2) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 2:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LabelsInSwitch_02()
{
string source = @"
using System;
class Program
{
static void M(int input)
{
/*<bind>*/switch (input)
{
case 1:
goto default;
default:
break;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... to default;')
Clauses:
ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto default;')
ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'default: ... break;')
Clauses:
IDefaultCaseClauseOperation (Label Id: 2) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:')
Body:
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_01()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
default:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_02()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
default:
result = true;
break;
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_03()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
default:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_04()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_05()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 0:
bool x = true;
result = x;
break;
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [System.Boolean x]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'x = true')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x = true')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B6]
Leaving: {R2} {R1}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R2} {R1}
}
}
Block[B6] - Exit
Predecessors: [B3] [B4] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_06()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
default:
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1*2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_07()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
default:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1*2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_08()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 2:
default:
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2*2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_09()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
goto case 3;
case 2:
goto default;
case 3:
result = true;
break;
default:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B5]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B5]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '3')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B1] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Leaving: {R1}
Block[B5] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_10()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1:
goto case 3;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(9,17): error CS0159: No such label 'case 3:' within the scope of the goto statement
// goto case 3;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto case 3;").WithArguments("case 3:").WithLocation(9, 17),
// file.cs(8,13): error CS8070: Control cannot fall out of switch from final case label ('case 1:')
// case 1:
Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 13)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto case 3;')
Children(0)
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_11()
{
string source = @"
public sealed class MyClass
{
void M(bool result, long input)
/*<bind>*/{
switch (input)
{
default:
result = false;
break;
case 1:
result = result;
break;
default:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(14,13): error CS0152: The switch statement contains multiple cases with the label value 'default'
// default:
Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "default:").WithArguments("default").WithLocation(14, 13),
// file.cs(12,17): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// result = result;
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "result = result").WithLocation(12, 17)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'input')
Jump if False (Regular) to Block[B2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = result;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = result')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B4] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B2] [B3] [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_12()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1L:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
// case 1L:
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1L')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitNumeric)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1, IsInvalid) (Syntax: '1L')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_13()
{
string source = @"
public sealed class MyClass
{
void M(bool result, MyClass input, MyClass other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
public static bool operator ==(MyClass x, MyClass y) => false;
public static bool operator !=(MyClass x, MyClass y) => true;
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: MyClass, NarrowedType: MyClass)
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_14()
{
string source = @"
public sealed class MyClass
{
void M(bool result, MyClass input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
public static bool operator ==(MyClass x, long y) => false;
public static bool operator !=(MyClass x, long y) => true;
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0029: Cannot implicitly convert type 'int' to 'MyClass'
// case 1:
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "MyClass").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_15()
{
string source = @"
public sealed class MyClass
{
void M(bool result, MyClass input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
public static implicit operator MyClass(long x) => null;
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case 1:
Diagnostic(ErrorCode.ERR_ConstantExpected, "1").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: MyClass MyClass.op_Implicit(System.Int64 x)) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: MyClass MyClass.op_Implicit(System.Int64 x))
(ImplicitUserDefined)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_16()
{
string source = @"
public sealed class MyClass
{
void M(bool result)
/*<bind>*/{
case 1:
result = false;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(5,16): error CS1513: } expected
// /*<bind>*/{
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 16),
// file.cs(6,19): error CS1002: ; expected
// case 1:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 19),
// file.cs(6,19): error CS1513: } expected
// case 1:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 19),
// file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_17()
{
string source = @"
public sealed class MyClass
{
void M(bool result)
/*<bind>*/{
default:
result = false;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(6,13): error CS8716: There is no target type for the default literal.
// default:
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 13),
// file.cs(6,20): error CS1002: ; expected
// default:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 20),
// file.cs(6,20): error CS1513: } expected
// default:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 20),
// file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'default')
Expression:
IDefaultValueOperation (OperationKind.DefaultValue, Type: ?, IsInvalid) (Syntax: 'default')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_18()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_19()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input)
/*<bind>*/{
switch (input)
{
case null:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'null')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_20()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input, int? other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_21()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input, int? other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
// case other:
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "other").WithArguments("int?", "int").WithLocation(8, 18),
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ExplicitNullable)
Operand:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_22()
{
string source = @"
public sealed class MyClass
{
void M(bool result, dynamic input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchIOperation_022()
{
string source = @"
public sealed class MyClass
{
void M(bool result, dynamic input)
{
/*<bind>*/switch (input)
{
case 1:
result = false;
break;
}/*</bind>*/
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
var expectedOperationTree =
@"
ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }')
Switch expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Sections:
ISwitchCaseOperation (1 case clauses, 2 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;')
Clauses:
IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Body:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;')
";
VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_23()
{
string source = @"
public sealed class MyClass
{
void M(bool result, dynamic input, dynamic other)
/*<bind>*/{
switch (input)
{
case other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: dynamic, NarrowedType: dynamic)
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_24()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input1, int input2)
/*<bind>*/{
switch (input1 ?? input2)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input1')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1 ?? input2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_25()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input1, int input2, int input3)
/*<bind>*/{
switch (input3)
{
case input1 ?? input2:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case input1 ?? input2:
Diagnostic(ErrorCode.ERR_ConstantExpected, "input1 ?? input2").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input3')
Value:
IParameterReferenceOperation: input3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input3')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input3')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_26()
{
string source = @"
public sealed class MyClass
{
void M(int input1, MyClass input2)
/*<bind>*/{
switch (input1)
{
case 1:
input2?.ToString();
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1')
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input2')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2')
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2?.ToString();')
Expression:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2} {R1}
}
}
Block[B4] - Exit
Predecessors: [B1] [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_27()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_28()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input, int? other)
/*<bind>*/{
switch (input)
{
case other ?? 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case other ?? 1:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other ?? 1").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other ?? 1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') (InputType: System.Object, NarrowedType: System.Object)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'other ?? 1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other ?? 1')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_29()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case int x:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [System.Int32 x]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False)
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R2} {R1}
}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_30()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input1, bool other2, bool other3, bool other4)
/*<bind>*/{
switch (input1)
{
case int x when (other2 ? other3 : other4) :
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [System.Int32 x]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input1')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False)
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: other2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: other3 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other3')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Block[B5] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: other4 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other4')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R2} {R1}
}
}
Block[B7] - Exit
Predecessors: [B2] [B4] [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_31()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case 1:
result = false;
break;
case 2:
result = true;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B5]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '2')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '2') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Leaving: {R1}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B2] [B3] [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_32()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input, bool? guard)
/*<bind>*/{
switch (input)
{
case 1 when guard ?? throw null:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B6]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'guard')
Value:
IParameterReferenceOperation: guard (OperationKind.ParameterReference, Type: System.Boolean?) (Syntax: 'guard')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'guard')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( System.Boolean System.Boolean?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'guard')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard')
Arguments(0)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Next (Throw) Block[null]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B1] [B3] [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_33()
{
string source = @"
public sealed class MyClass
{
void M(bool result, object input)
/*<bind>*/{
switch (input)
{
case 1 when guard:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(8,25): error CS0103: The name 'guard' does not exist in the current context
// case 1 when guard:
Diagnostic(ErrorCode.ERR_NameNotInContext, "guard").WithArguments("guard").WithLocation(8, 25)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B4]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'guard')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'guard')
Children(0)
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B1] [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_34()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case 1+TakeOutParam(3, out MyClass x1):
result = false;
break;
}
}/*</bind>*/
int TakeOutParam(int a, out MyClass b)
{
b = default;
return a;
}
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case 1+TakeOutParam(3, out MyClass x1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "1+TakeOutParam(3, out MyClass x1)").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
Locals: [MyClass x1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+TakeOutPa ... MyClass x1)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+TakeOutPa ... MyClass x1)')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Right:
IInvocationOperation ( System.Int32 MyClass.TakeOutParam(System.Int32 a, out MyClass b)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... MyClass x1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'TakeOutParam')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out MyClass x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: MyClass, IsInvalid) (Syntax: 'MyClass x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: MyClass, IsInvalid) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Leaving: {R2} {R1}
}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void SwitchFlow_35()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int? input)
/*<bind>*/{
switch (input)
{
case 1+(input is int x1 ? x1 : 0):
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,18): error CS0150: A constant value is expected
// case 1+(input is int x1 ? x1 : 0):
Diagnostic(ErrorCode.ERR_ConstantExpected, "1+(input is int x1 ? x1 : 0)").WithLocation(8, 18)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
Locals: [System.Int32 x1]
.locals {R3}
{
CaptureIds: [1] [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Jump if False (Regular) to Block[B4]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'input is int x1')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
Pattern:
IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int x1') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x1, MatchesNull: False)
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1')
Value:
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+(input is ... 1 ? x1 : 0)')
Left:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input is int x1 ? x1 : 0')
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R3}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R2} {R1}
}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns, CompilerFeature.Dataflow)]
[Fact]
public void EmptySwitchExpressionFlow()
{
string source = @"
class Program
{
public static void Main()
/*<bind>*/{
var r = 1 switch { };
}/*</bind>*/
}
";
var expectedDiagnostics = new[] {
// file.cs(6,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// var r = 1 switch { };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 19),
// file.cs(6,19): error CS8506: No best type was found for the switch expression.
// var r = 1 switch { };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 19)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [? r]
CaptureIds: [0]
.locals {R2}
{
CaptureIds: [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Throw) Block[null]
IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: '1 switch { }')
Arguments(0)
Initializer:
null
Block[B3] - Block [UnReachable]
Predecessors (0)
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }')
Left:
ILocalReferenceOperation: r (IsDeclaration: True) (OperationKind.LocalReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: '1 switch { }')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit [UnReachable]
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_36()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case < 1:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[0];
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< 1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< 1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_37()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input, int other)
/*<bind>*/{
switch (input)
{
case < other:
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,20): error CS0150: A constant value is expected
// case < other:
Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 20)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '< other')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null, IsInvalid) (Syntax: '< other') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'other')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Leaving: {R1}
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_38()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case < (true ? 10 : 11):
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Next (Regular) Block[B5]
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< (true ? 10 : 11)')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_39()
{
string source = @"
public sealed class MyClass
{
void M(bool result, int input)
/*<bind>*/{
switch (input)
{
case not < (true ? 10 : 11):
result = false;
break;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Next (Regular) Block[B5]
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'not < (true ? 10 : 11)')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input')
Pattern:
INegatedPatternOperation (OperationKind.NegatedPattern, Type: null) (Syntax: 'not < (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32)
Pattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11')
Leaving: {R2} {R1}
Next (Regular) Block[B6]
Leaving: {R2}
}
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B7]
Leaving: {R1}
}
Block[B7] - Exit
Predecessors: [B5] [B6]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_40()
{
string source = @"
public sealed class MyClass
{
bool M(char input)
/*<bind>*/{
switch (input)
{
case (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or '_':
return true;
}
return false;
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '(>= 'A' and ... 'z') or '_'')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input')
Pattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... 'z') or '_'') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'')
RightPattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'')
RightPattern:
IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char)
LeftPattern:
IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'')
RightPattern:
IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'')
RightPattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: ''_'') (InputType: System.Char, NarrowedType: System.Char)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: _) (Syntax: ''_'')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Leaving: {R1}
}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)]
[Fact]
public void SwitchFlow_41()
{
string source = @"
public sealed class MyClass
{
bool M(object input)
/*<bind>*/{
switch (input)
{
case int or long or ulong:
return true;
default:
return false;
}
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input')
Jump if False (Regular) to Block[B3]
IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int or long or ulong')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input')
Pattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or ulong') (InputType: System.Object, NarrowedType: System.Object)
LeftPattern:
IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object)
LeftPattern:
ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32)
RightPattern:
ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64)
RightPattern:
ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'ulong') (InputType: System.Object, NarrowedType: System.UInt64, MatchedType: System.UInt64)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Leaving: {R1}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Remote/Core/SolutionAssetStorage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// Stores solution snapshots available to remote services.
/// </summary>
internal partial class SolutionAssetStorage
{
private static int s_scopeId = 1;
/// <summary>
/// Map from solution checksum scope id to its associated <see cref="SolutionState"/>.
/// </summary>
private readonly ConcurrentDictionary<int, (SolutionState Solution, SolutionReplicationContext ReplicationContext)> _solutionStates = new(concurrencyLevel: 2, capacity: 10);
public SolutionReplicationContext GetReplicationContext(int scopeId)
=> _solutionStates[scopeId].ReplicationContext;
/// <summary>
/// Adds given snapshot into the storage. This snapshot will be available within the returned <see cref="Scope"/>.
/// </summary>
internal ValueTask<Scope> StoreAssetsAsync(Solution solution, CancellationToken cancellationToken)
=> StoreAssetsAsync(solution, projectId: null, cancellationToken);
/// <summary>
/// Adds given snapshot into the storage. This snapshot will be available within the returned <see cref="Scope"/>.
/// </summary>
internal ValueTask<Scope> StoreAssetsAsync(Project project, CancellationToken cancellationToken)
=> StoreAssetsAsync(project.Solution, project.Id, cancellationToken);
private async ValueTask<Scope> StoreAssetsAsync(Solution solution, ProjectId? projectId, CancellationToken cancellationToken)
{
var solutionState = solution.State;
var solutionChecksum = projectId == null
? await solutionState.GetChecksumAsync(cancellationToken).ConfigureAwait(false)
: await solutionState.GetChecksumAsync(projectId, cancellationToken).ConfigureAwait(false);
var context = SolutionReplicationContext.Create();
var id = Interlocked.Increment(ref s_scopeId);
var solutionInfo = new PinnedSolutionInfo(
id,
fromPrimaryBranch: solutionState.BranchId == solutionState.Workspace.PrimaryBranchId,
solutionState.WorkspaceVersion,
solutionChecksum,
projectId);
Contract.ThrowIfFalse(_solutionStates.TryAdd(id, (solutionState, context)));
return new Scope(this, solutionInfo);
}
/// <summary>
/// Retrieve asset of a specified <paramref name="checksum"/> available within <paramref name="scopeId"/> scope from the storage.
/// </summary>
public async ValueTask<SolutionAsset?> GetAssetAsync(int scopeId, Checksum checksum, CancellationToken cancellationToken)
{
if (checksum == Checksum.Null)
{
// check nil case
return SolutionAsset.Null;
}
var remotableData = await FindAssetAsync(_solutionStates[scopeId].Solution, checksum, cancellationToken).ConfigureAwait(false);
if (remotableData != null)
{
return remotableData;
}
// if it reached here, it means things get cancelled. due to involving 2 processes,
// current design can make slightly staled requests to running even when things cancelled.
// if it is other case, remote host side will throw and close connection which will cause
// vs to crash.
// this should be changed once I address this design issue
cancellationToken.ThrowIfCancellationRequested();
return null;
}
/// <summary>
/// Retrieve assets of specified <paramref name="checksums"/> available within <paramref name="scopeId"/> scope from the storage.
/// </summary>
public async ValueTask<IReadOnlyDictionary<Checksum, SolutionAsset>> GetAssetsAsync(int scopeId, IEnumerable<Checksum> checksums, CancellationToken cancellationToken)
{
using var checksumsToFind = Creator.CreateChecksumSet(checksums);
var numberOfChecksumsToSearch = checksumsToFind.Object.Count;
var result = new Dictionary<Checksum, SolutionAsset>(numberOfChecksumsToSearch);
if (checksumsToFind.Object.Remove(Checksum.Null))
{
result[Checksum.Null] = SolutionAsset.Null;
}
await FindAssetsAsync(_solutionStates[scopeId].Solution, checksumsToFind.Object, result, cancellationToken).ConfigureAwait(false);
if (result.Count == numberOfChecksumsToSearch)
{
// no checksum left to find
Debug.Assert(checksumsToFind.Object.Count == 0);
return result;
}
// if it reached here, it means things get cancelled. due to involving 2 processes,
// current design can make slightly staled requests to running even when things cancelled.
// if it is other case, remote host side will throw and close connection which will cause
// vs to crash.
// this should be changed once I address this design issue
cancellationToken.ThrowIfCancellationRequested();
return result;
}
/// <summary>
/// Find an asset of the specified <paramref name="checksum"/> within <paramref name="solutionState"/>.
/// </summary>
private static async ValueTask<SolutionAsset?> FindAssetAsync(SolutionState solutionState, Checksum checksum, CancellationToken cancellationToken)
{
using var checksumPool = Creator.CreateChecksumSet(SpecializedCollections.SingletonEnumerable(checksum));
using var resultPool = Creator.CreateResultSet();
await FindAssetsAsync(solutionState, checksumPool.Object, resultPool.Object, cancellationToken).ConfigureAwait(false);
if (resultPool.Object.Count == 1)
{
var (resultingChecksum, value) = resultPool.Object.First();
Contract.ThrowIfFalse(checksum == resultingChecksum);
return new SolutionAsset(checksum, value);
}
return null;
}
/// <summary>
/// Find an assets of the specified <paramref name="remainingChecksumsToFind"/> within <paramref name="solutionState"/>.
/// Once an asset of given checksum is found the corresponding asset is placed to <paramref name="result"/> and the checksum is removed from <paramref name="remainingChecksumsToFind"/>.
/// </summary>
private static async Task FindAssetsAsync(SolutionState solutionState, HashSet<Checksum> remainingChecksumsToFind, Dictionary<Checksum, SolutionAsset> result, CancellationToken cancellationToken)
{
using var resultPool = Creator.CreateResultSet();
await FindAssetsAsync(solutionState, remainingChecksumsToFind, resultPool.Object, cancellationToken).ConfigureAwait(false);
foreach (var (checksum, value) in resultPool.Object)
{
result[checksum] = new SolutionAsset(checksum, value);
}
}
private static async Task FindAssetsAsync(SolutionState solutionState, HashSet<Checksum> remainingChecksumsToFind, Dictionary<Checksum, object> result, CancellationToken cancellationToken)
{
if (solutionState.TryGetStateChecksums(out var stateChecksums))
await stateChecksums.FindAsync(solutionState, remainingChecksumsToFind, result, cancellationToken).ConfigureAwait(false);
foreach (var projectId in solutionState.ProjectIds)
{
if (remainingChecksumsToFind.Count == 0)
break;
if (solutionState.TryGetStateChecksums(projectId, out var tuple))
await tuple.checksums.FindAsync(solutionState, remainingChecksumsToFind, result, cancellationToken).ConfigureAwait(false);
}
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly SolutionAssetStorage _solutionAssetStorage;
internal TestAccessor(SolutionAssetStorage solutionAssetStorage)
{
_solutionAssetStorage = solutionAssetStorage;
}
public async ValueTask<SolutionAsset?> GetAssetAsync(Checksum checksum, CancellationToken cancellationToken)
{
foreach (var (scopeId, _) in _solutionAssetStorage._solutionStates)
{
var data = await _solutionAssetStorage.GetAssetAsync(scopeId, checksum, cancellationToken).ConfigureAwait(false);
if (data != null)
{
return data;
}
}
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// Stores solution snapshots available to remote services.
/// </summary>
internal partial class SolutionAssetStorage
{
private static int s_scopeId = 1;
/// <summary>
/// Map from solution checksum scope id to its associated <see cref="SolutionState"/>.
/// </summary>
private readonly ConcurrentDictionary<int, (SolutionState Solution, SolutionReplicationContext ReplicationContext)> _solutionStates = new(concurrencyLevel: 2, capacity: 10);
public SolutionReplicationContext GetReplicationContext(int scopeId)
=> _solutionStates[scopeId].ReplicationContext;
/// <summary>
/// Adds given snapshot into the storage. This snapshot will be available within the returned <see cref="Scope"/>.
/// </summary>
internal ValueTask<Scope> StoreAssetsAsync(Solution solution, CancellationToken cancellationToken)
=> StoreAssetsAsync(solution, projectId: null, cancellationToken);
/// <summary>
/// Adds given snapshot into the storage. This snapshot will be available within the returned <see cref="Scope"/>.
/// </summary>
internal ValueTask<Scope> StoreAssetsAsync(Project project, CancellationToken cancellationToken)
=> StoreAssetsAsync(project.Solution, project.Id, cancellationToken);
private async ValueTask<Scope> StoreAssetsAsync(Solution solution, ProjectId? projectId, CancellationToken cancellationToken)
{
var solutionState = solution.State;
var solutionChecksum = projectId == null
? await solutionState.GetChecksumAsync(cancellationToken).ConfigureAwait(false)
: await solutionState.GetChecksumAsync(projectId, cancellationToken).ConfigureAwait(false);
var context = SolutionReplicationContext.Create();
var id = Interlocked.Increment(ref s_scopeId);
var solutionInfo = new PinnedSolutionInfo(
id,
fromPrimaryBranch: solutionState.BranchId == solutionState.Workspace.PrimaryBranchId,
solutionState.WorkspaceVersion,
solutionChecksum,
projectId);
Contract.ThrowIfFalse(_solutionStates.TryAdd(id, (solutionState, context)));
return new Scope(this, solutionInfo);
}
/// <summary>
/// Retrieve asset of a specified <paramref name="checksum"/> available within <paramref name="scopeId"/> scope from the storage.
/// </summary>
public async ValueTask<SolutionAsset?> GetAssetAsync(int scopeId, Checksum checksum, CancellationToken cancellationToken)
{
if (checksum == Checksum.Null)
{
// check nil case
return SolutionAsset.Null;
}
var remotableData = await FindAssetAsync(_solutionStates[scopeId].Solution, checksum, cancellationToken).ConfigureAwait(false);
if (remotableData != null)
{
return remotableData;
}
// if it reached here, it means things get cancelled. due to involving 2 processes,
// current design can make slightly staled requests to running even when things cancelled.
// if it is other case, remote host side will throw and close connection which will cause
// vs to crash.
// this should be changed once I address this design issue
cancellationToken.ThrowIfCancellationRequested();
return null;
}
/// <summary>
/// Retrieve assets of specified <paramref name="checksums"/> available within <paramref name="scopeId"/> scope from the storage.
/// </summary>
public async ValueTask<IReadOnlyDictionary<Checksum, SolutionAsset>> GetAssetsAsync(int scopeId, IEnumerable<Checksum> checksums, CancellationToken cancellationToken)
{
using var checksumsToFind = Creator.CreateChecksumSet(checksums);
var numberOfChecksumsToSearch = checksumsToFind.Object.Count;
var result = new Dictionary<Checksum, SolutionAsset>(numberOfChecksumsToSearch);
if (checksumsToFind.Object.Remove(Checksum.Null))
{
result[Checksum.Null] = SolutionAsset.Null;
}
await FindAssetsAsync(_solutionStates[scopeId].Solution, checksumsToFind.Object, result, cancellationToken).ConfigureAwait(false);
if (result.Count == numberOfChecksumsToSearch)
{
// no checksum left to find
Debug.Assert(checksumsToFind.Object.Count == 0);
return result;
}
// if it reached here, it means things get cancelled. due to involving 2 processes,
// current design can make slightly staled requests to running even when things cancelled.
// if it is other case, remote host side will throw and close connection which will cause
// vs to crash.
// this should be changed once I address this design issue
cancellationToken.ThrowIfCancellationRequested();
return result;
}
/// <summary>
/// Find an asset of the specified <paramref name="checksum"/> within <paramref name="solutionState"/>.
/// </summary>
private static async ValueTask<SolutionAsset?> FindAssetAsync(SolutionState solutionState, Checksum checksum, CancellationToken cancellationToken)
{
using var checksumPool = Creator.CreateChecksumSet(SpecializedCollections.SingletonEnumerable(checksum));
using var resultPool = Creator.CreateResultSet();
await FindAssetsAsync(solutionState, checksumPool.Object, resultPool.Object, cancellationToken).ConfigureAwait(false);
if (resultPool.Object.Count == 1)
{
var (resultingChecksum, value) = resultPool.Object.First();
Contract.ThrowIfFalse(checksum == resultingChecksum);
return new SolutionAsset(checksum, value);
}
return null;
}
/// <summary>
/// Find an assets of the specified <paramref name="remainingChecksumsToFind"/> within <paramref name="solutionState"/>.
/// Once an asset of given checksum is found the corresponding asset is placed to <paramref name="result"/> and the checksum is removed from <paramref name="remainingChecksumsToFind"/>.
/// </summary>
private static async Task FindAssetsAsync(SolutionState solutionState, HashSet<Checksum> remainingChecksumsToFind, Dictionary<Checksum, SolutionAsset> result, CancellationToken cancellationToken)
{
using var resultPool = Creator.CreateResultSet();
await FindAssetsAsync(solutionState, remainingChecksumsToFind, resultPool.Object, cancellationToken).ConfigureAwait(false);
foreach (var (checksum, value) in resultPool.Object)
{
result[checksum] = new SolutionAsset(checksum, value);
}
}
private static async Task FindAssetsAsync(SolutionState solutionState, HashSet<Checksum> remainingChecksumsToFind, Dictionary<Checksum, object> result, CancellationToken cancellationToken)
{
if (solutionState.TryGetStateChecksums(out var stateChecksums))
await stateChecksums.FindAsync(solutionState, remainingChecksumsToFind, result, cancellationToken).ConfigureAwait(false);
foreach (var projectId in solutionState.ProjectIds)
{
if (remainingChecksumsToFind.Count == 0)
break;
if (solutionState.TryGetStateChecksums(projectId, out var tuple))
await tuple.checksums.FindAsync(solutionState, remainingChecksumsToFind, result, cancellationToken).ConfigureAwait(false);
}
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly SolutionAssetStorage _solutionAssetStorage;
internal TestAccessor(SolutionAssetStorage solutionAssetStorage)
{
_solutionAssetStorage = solutionAssetStorage;
}
public async ValueTask<SolutionAsset?> GetAssetAsync(Checksum checksum, CancellationToken cancellationToken)
{
foreach (var (scopeId, _) in _solutionAssetStorage._solutionStates)
{
var data = await _solutionAssetStorage.GetAssetAsync(scopeId, checksum, cancellationToken).ConfigureAwait(false);
if (data != null)
{
return data;
}
}
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/IntroduceVariable/IntroduceVariableCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct)]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass)]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertConditional)]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertLogical)]
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.IntroduceVariable), Shared]
internal class IntroduceVariableCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public IntroduceVariableCodeRefactoringProvider()
{
}
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var service = document.GetLanguageService<IIntroduceVariableService>();
var action = await service.IntroduceVariableAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (action != null)
{
context.RegisterRefactoring(action, textSpan);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct)]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass)]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertConditional)]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertLogical)]
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.IntroduceVariable), Shared]
internal class IntroduceVariableCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public IntroduceVariableCodeRefactoringProvider()
{
}
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var service = document.GetLanguageService<IIntroduceVariableService>();
var action = await service.IntroduceVariableAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (action != null)
{
context.RegisterRefactoring(action, textSpan);
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.GenerateDefaultConstructorItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateDefaultConstructor : AbstractGenerateCodeItem, IEquatable<GenerateDefaultConstructor>
{
public GenerateDefaultConstructor(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateDefaultConstructor, text, Glyph.MethodPublic, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateDefaultConstructor(Text, DestinationTypeSymbolKey);
public override bool Equals(object? obj)
=> Equals(obj as GenerateDefaultConstructor);
public bool Equals(GenerateDefaultConstructor? other)
=> base.Equals(other);
public override int GetHashCode()
=> throw new NotImplementedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateDefaultConstructor : AbstractGenerateCodeItem, IEquatable<GenerateDefaultConstructor>
{
public GenerateDefaultConstructor(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateDefaultConstructor, text, Glyph.MethodPublic, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateDefaultConstructor(Text, DestinationTypeSymbolKey);
public override bool Equals(object? obj)
=> Equals(obj as GenerateDefaultConstructor);
public bool Equals(GenerateDefaultConstructor? other)
=> base.Equals(other);
public override int GetHashCode()
=> throw new NotImplementedException();
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/DirectiveSyntaxExtensions.DirectiveInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class DirectiveSyntaxExtensions
{
private class DirectiveInfo
{
// Maps a directive to its pair
public IDictionary<DirectiveTriviaSyntax, DirectiveTriviaSyntax> DirectiveMap { get; }
// Maps a #If/#elif/#else/#endIf directive to its list of matching #If/#elif/#else/#endIf directives
public IDictionary<DirectiveTriviaSyntax, IReadOnlyList<DirectiveTriviaSyntax>> ConditionalMap { get; }
// A set of inactive regions spans. The items in the tuple are the start and end line
// *both inclusive* of the inactive region. Actual PP lines are not continued within.
//
// Note: an interval tree might be a better structure here if there are lots of inactive
// regions. Consider switching to that if necessary.
public ISet<Tuple<int, int>> InactiveRegionLines { get; }
public DirectiveInfo(
IDictionary<DirectiveTriviaSyntax, DirectiveTriviaSyntax> directiveMap,
IDictionary<DirectiveTriviaSyntax, IReadOnlyList<DirectiveTriviaSyntax>> conditionalMap,
ISet<Tuple<int, int>> inactiveRegionLines)
{
this.DirectiveMap = directiveMap;
this.ConditionalMap = conditionalMap;
this.InactiveRegionLines = inactiveRegionLines;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class DirectiveSyntaxExtensions
{
private class DirectiveInfo
{
// Maps a directive to its pair
public IDictionary<DirectiveTriviaSyntax, DirectiveTriviaSyntax> DirectiveMap { get; }
// Maps a #If/#elif/#else/#endIf directive to its list of matching #If/#elif/#else/#endIf directives
public IDictionary<DirectiveTriviaSyntax, IReadOnlyList<DirectiveTriviaSyntax>> ConditionalMap { get; }
// A set of inactive regions spans. The items in the tuple are the start and end line
// *both inclusive* of the inactive region. Actual PP lines are not continued within.
//
// Note: an interval tree might be a better structure here if there are lots of inactive
// regions. Consider switching to that if necessary.
public ISet<Tuple<int, int>> InactiveRegionLines { get; }
public DirectiveInfo(
IDictionary<DirectiveTriviaSyntax, DirectiveTriviaSyntax> directiveMap,
IDictionary<DirectiveTriviaSyntax, IReadOnlyList<DirectiveTriviaSyntax>> conditionalMap,
ISet<Tuple<int, int>> inactiveRegionLines)
{
this.DirectiveMap = directiveMap;
this.ConditionalMap = conditionalMap;
this.InactiveRegionLines = inactiveRegionLines;
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/Binder/CatchClauseBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class CatchClauseBinder : LocalScopeBinder
{
private readonly CatchClauseSyntax _syntax;
public CatchClauseBinder(Binder enclosing, CatchClauseSyntax syntax)
: base(enclosing, (enclosing.Flags | BinderFlags.InCatchBlock) & ~BinderFlags.InNestedFinallyBlock)
{
Debug.Assert(syntax != null);
_syntax = syntax;
}
protected override ImmutableArray<LocalSymbol> BuildLocals()
{
var locals = ArrayBuilder<LocalSymbol>.GetInstance();
var declarationOpt = _syntax.Declaration;
if ((declarationOpt != null) && (declarationOpt.Identifier.Kind() != SyntaxKind.None))
{
locals.Add(SourceLocalSymbol.MakeLocal(this.ContainingMemberOrLambda, this, false, declarationOpt.Type, declarationOpt.Identifier, LocalDeclarationKind.CatchVariable));
}
if (_syntax.Filter != null)
{
ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Filter.FilterExpression);
}
return locals.ToImmutableAndFree();
}
internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator)
{
if (_syntax == scopeDesignator)
{
return this.Locals;
}
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
{
throw ExceptionUtilities.Unreachable;
}
internal override SyntaxNode ScopeDesignator
{
get
{
return _syntax;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class CatchClauseBinder : LocalScopeBinder
{
private readonly CatchClauseSyntax _syntax;
public CatchClauseBinder(Binder enclosing, CatchClauseSyntax syntax)
: base(enclosing, (enclosing.Flags | BinderFlags.InCatchBlock) & ~BinderFlags.InNestedFinallyBlock)
{
Debug.Assert(syntax != null);
_syntax = syntax;
}
protected override ImmutableArray<LocalSymbol> BuildLocals()
{
var locals = ArrayBuilder<LocalSymbol>.GetInstance();
var declarationOpt = _syntax.Declaration;
if ((declarationOpt != null) && (declarationOpt.Identifier.Kind() != SyntaxKind.None))
{
locals.Add(SourceLocalSymbol.MakeLocal(this.ContainingMemberOrLambda, this, false, declarationOpt.Type, declarationOpt.Identifier, LocalDeclarationKind.CatchVariable));
}
if (_syntax.Filter != null)
{
ExpressionVariableFinder.FindExpressionVariables(this, locals, _syntax.Filter.FilterExpression);
}
return locals.ToImmutableAndFree();
}
internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator)
{
if (_syntax == scopeDesignator)
{
return this.Locals;
}
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
{
throw ExceptionUtilities.Unreachable;
}
internal override SyntaxNode ScopeDesignator
{
get
{
return _syntax;
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core.Wpf/Preview/PreviewReferenceHighlightingTaggerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting;
using System;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
/// <summary>
/// Special tagger we use for previews that is told precisely which spans to
/// reference highlight.
/// </summary>
[Export(typeof(ITaggerProvider))]
[TagType(typeof(NavigableHighlightTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(TextViewRoles.PreviewRole)]
internal class PreviewReferenceHighlightingTaggerProvider
: AbstractPreviewTaggerProvider<NavigableHighlightTag>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewReferenceHighlightingTaggerProvider()
: base(PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey, ReferenceHighlightTag.Instance)
{
}
}
[Export(typeof(ITaggerProvider))]
[TagType(typeof(NavigableHighlightTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(TextViewRoles.PreviewRole)]
internal class PreviewWrittenReferenceHighlightingTaggerProvider
: AbstractPreviewTaggerProvider<NavigableHighlightTag>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewWrittenReferenceHighlightingTaggerProvider()
: base(PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey, WrittenReferenceHighlightTag.Instance)
{
}
}
[Export(typeof(ITaggerProvider))]
[TagType(typeof(NavigableHighlightTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(TextViewRoles.PreviewRole)]
internal class PreviewDefinitionHighlightingTaggerProvider
: AbstractPreviewTaggerProvider<NavigableHighlightTag>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewDefinitionHighlightingTaggerProvider()
: base(PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey, DefinitionHighlightTag.Instance)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting;
using System;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
/// <summary>
/// Special tagger we use for previews that is told precisely which spans to
/// reference highlight.
/// </summary>
[Export(typeof(ITaggerProvider))]
[TagType(typeof(NavigableHighlightTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(TextViewRoles.PreviewRole)]
internal class PreviewReferenceHighlightingTaggerProvider
: AbstractPreviewTaggerProvider<NavigableHighlightTag>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewReferenceHighlightingTaggerProvider()
: base(PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey, ReferenceHighlightTag.Instance)
{
}
}
[Export(typeof(ITaggerProvider))]
[TagType(typeof(NavigableHighlightTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(TextViewRoles.PreviewRole)]
internal class PreviewWrittenReferenceHighlightingTaggerProvider
: AbstractPreviewTaggerProvider<NavigableHighlightTag>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewWrittenReferenceHighlightingTaggerProvider()
: base(PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey, WrittenReferenceHighlightTag.Instance)
{
}
}
[Export(typeof(ITaggerProvider))]
[TagType(typeof(NavigableHighlightTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(TextViewRoles.PreviewRole)]
internal class PreviewDefinitionHighlightingTaggerProvider
: AbstractPreviewTaggerProvider<NavigableHighlightTag>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewDefinitionHighlightingTaggerProvider()
: base(PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey, DefinitionHighlightTag.Instance)
{
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core/EditorConfigSettings/Data/CodeStyle/CodeStyleSetting.EnumCodeStyleSettingBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater;
using Microsoft.CodeAnalysis.Utilities;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data
{
internal abstract partial class CodeStyleSetting
{
private abstract class EnumCodeStyleSettingBase<T> : CodeStyleSetting
where T : Enum
{
protected readonly T[] _enumValues;
private readonly string[] _valueDescriptions;
public EnumCodeStyleSettingBase(string description,
T[] enumValues,
string[] valueDescriptions,
string category,
OptionUpdater updater)
: base(description, updater)
{
if (enumValues.Length != valueDescriptions.Length)
{
throw new InvalidOperationException("Values and descriptions must have matching number of elements");
}
_enumValues = enumValues;
_valueDescriptions = valueDescriptions;
Category = category;
}
public override string Category { get; }
public override Type Type => typeof(T);
public override string GetCurrentValue() => _valueDescriptions[_enumValues.IndexOf(GetOption().Value)];
public override object? Value => GetOption().Value;
public override DiagnosticSeverity Severity => GetOption().Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden;
public override string[] GetValues() => _valueDescriptions;
protected abstract CodeStyleOption2<T> GetOption();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater;
using Microsoft.CodeAnalysis.Utilities;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data
{
internal abstract partial class CodeStyleSetting
{
private abstract class EnumCodeStyleSettingBase<T> : CodeStyleSetting
where T : Enum
{
protected readonly T[] _enumValues;
private readonly string[] _valueDescriptions;
public EnumCodeStyleSettingBase(string description,
T[] enumValues,
string[] valueDescriptions,
string category,
OptionUpdater updater)
: base(description, updater)
{
if (enumValues.Length != valueDescriptions.Length)
{
throw new InvalidOperationException("Values and descriptions must have matching number of elements");
}
_enumValues = enumValues;
_valueDescriptions = valueDescriptions;
Category = category;
}
public override string Category { get; }
public override Type Type => typeof(T);
public override string GetCurrentValue() => _valueDescriptions[_enumValues.IndexOf(GetOption().Value)];
public override object? Value => GetOption().Value;
public override DiagnosticSeverity Severity => GetOption().Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden;
public override string[] GetValues() => _valueDescriptions;
protected abstract CodeStyleOption2<T> GetOption();
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundObjectCreationExpression.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundObjectCreationExpression
Public Sub New(syntax As SyntaxNode, constructorOpt As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol,
Optional hasErrors As Boolean = False, Optional defaultArguments As BitVector = Nothing)
Me.New(syntax, constructorOpt, Nothing, arguments, defaultArguments:=defaultArguments, initializerOpt, type, hasErrors)
End Sub
Public Function Update(constructorOpt As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundObjectCreationExpression
Return Update(constructorOpt, methodGroupOpt:=Nothing, arguments, defaultArguments, initializerOpt, type)
End Function
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return Me.ConstructorOpt
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(DefaultArguments.IsNull OrElse Not Arguments.IsEmpty)
End Sub
#End If
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundObjectCreationExpression
Public Sub New(syntax As SyntaxNode, constructorOpt As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol,
Optional hasErrors As Boolean = False, Optional defaultArguments As BitVector = Nothing)
Me.New(syntax, constructorOpt, Nothing, arguments, defaultArguments:=defaultArguments, initializerOpt, type, hasErrors)
End Sub
Public Function Update(constructorOpt As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundObjectCreationExpression
Return Update(constructorOpt, methodGroupOpt:=Nothing, arguments, defaultArguments, initializerOpt, type)
End Function
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return Me.ConstructorOpt
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(DefaultArguments.IsNull OrElse Not Arguments.IsEmpty)
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/SymbolMapping/SymbolMappingResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.SymbolMapping
{
internal class SymbolMappingResult
{
public Project Project { get; }
public ISymbol Symbol { get; }
internal SymbolMappingResult(Project project, ISymbol symbol)
{
Contract.ThrowIfNull(project);
Contract.ThrowIfNull(symbol);
Project = project;
Symbol = symbol;
}
public Solution Solution => Project.Solution;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.SymbolMapping
{
internal class SymbolMappingResult
{
public Project Project { get; }
public ISymbol Symbol { get; }
internal SymbolMappingResult(Project project, ISymbol symbol)
{
Contract.ThrowIfNull(project);
Contract.ThrowIfNull(symbol);
Project = project;
Symbol = symbol;
}
public Solution Solution => Project.Solution;
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/ForEachStatementSyntaxExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class ForEachStatementSyntaxExtensions
{
public static bool IsTypeInferred(this CommonForEachStatementSyntax forEachStatement, SemanticModel semanticModel)
{
switch (forEachStatement.Kind())
{
case SyntaxKind.ForEachStatement:
return ((ForEachStatementSyntax)forEachStatement).Type.IsTypeInferred(semanticModel);
case SyntaxKind.ForEachVariableStatement:
return (((ForEachVariableStatementSyntax)forEachStatement).Variable as DeclarationExpressionSyntax)?.Type
.IsTypeInferred(semanticModel) == true;
default:
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class ForEachStatementSyntaxExtensions
{
public static bool IsTypeInferred(this CommonForEachStatementSyntax forEachStatement, SemanticModel semanticModel)
{
switch (forEachStatement.Kind())
{
case SyntaxKind.ForEachStatement:
return ((ForEachStatementSyntax)forEachStatement).Type.IsTypeInferred(semanticModel);
case SyntaxKind.ForEachVariableStatement:
return (((ForEachVariableStatementSyntax)forEachStatement).Variable as DeclarationExpressionSyntax)?.Type
.IsTypeInferred(semanticModel) == true;
default:
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDelegateCreationExpression.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDelegateCreationExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = () => { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action a = () => { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action a = () => { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = () => { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion_InitializerBindingReturnsJustAnonymousFunction()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/() => { }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = () => 1;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = () => 1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = () => 1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = () => 1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: '() => 1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// /*<bind>*/Action a = () => 1;/*</bind>*/
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 36)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = (int i) => { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = ... i) => { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = ... t i) => { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = (int i) => { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (int i) => { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: '(int i) => { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// /*<bind>*/Action a = (int i) => { };/*</bind>*/
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)(() => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)(() => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action a = /*<bind>*/(Action)(() => 1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 45)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)((int i) => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)((int i) => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// Action a = /*<bind>*/(Action)((int i) => { })/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 39)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_DelegateExpression()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = delegate() { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action a = ... gate() { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action a = ... egate() { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = delegate() { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= delegate() { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'delegate() { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'delegate() { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_DelegateExpression_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = delegate() { return 1; };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = ... eturn 1; };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = ... return 1; }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = delegat ... return 1; }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= delegate( ... return 1; }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'delegate() { return 1; }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate() { return 1; }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ return 1; }')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8030: Anonymous function converted to a void returning delegate cannot return a value
// /*<bind>*/Action a = delegate() { return 1; };/*</bind>*/
Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 43)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_DelegateExpression_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = delegate(int i) { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = ... int i) { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = ... (int i) { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = delegate(int i) { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= delegate(int i) { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'delegate(int i) { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate(int i) { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// /*<bind>*/Action a = delegate(int i) { };/*</bind>*/
Diagnostic(ErrorCode.ERR_BadDelArgCount, "delegate(int i) { }").WithArguments("System.Action", "1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
void M1() { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")]
public void DelegateCreationExpression_ImplicitMethodBinding_InitializerBindingReturnsJustMethodReference()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
static void M1() { }
}
";
string expectedOperationTree = @"
IMethodReferenceOperation: void Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// /*<bind>*/Action a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidIdentifier_InitializerBindingReturnsJustInvalidExpression()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
int M1() => 1;
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0407: 'int Program.M1()' has the wrong return type
// /*<bind>*/Action a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidReturnType_InitializerBindingReturnsJustMethodReference()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
int M1() => 1;
}
";
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, @"
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[]
{
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, @"
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[]
{
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'M1' matches delegate 'Action'
// /*<bind>*/Action a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M1").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidArgumentType_InitializerBindingReturnsJustNoneOperation()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M1").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/(Action)M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidIdentifierWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
object o = new object();
Action a = /*<bind>*/(Action)o.M1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid) (Syntax: '(Action)o.M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'o.M1')
Children(1):
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'object' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Action a = /*<bind>*/(Action)o.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("object", "M1").WithLocation(8, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
int M1() => 1;
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/(Action)M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "(Action)M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
}
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidReturnTypeWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
Program p = new Program();
Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
}
int M1() => 1;
}
";
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)p.M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'p.M1')
Instance Receiver:
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'p')
", new DiagnosticDescription[] {
// file.cs(8,30): error CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "(Action)p.M1").WithArguments("Program.M1()", "int").WithLocation(8, 30)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)p.M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'p.M1')
Children(1):
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'p')
", new DiagnosticDescription[] {
// file.cs(8,38): error CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "p.M1").WithArguments("Program.M1()", "int").WithLocation(8, 38)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// file.cs(7,30): error CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/(Action)M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "(Action)M1").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidArgumentTypeWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
Program p = new Program();
Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)p.M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'p.M1')
Children(1):
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'p')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,30): error CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "(Action)p.M1").WithArguments("M1", "System.Action").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(() => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(() => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(() => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(() => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action a = /*<bind>*/new Action(() => 1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 47)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((int i) => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... i) => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// Action a = /*<bind>*/new Action((int i) => { })/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion_InvalidMultipleParameters()
{
string source = @"
using System;
class C
{
void M1()
{
Action action = /*<bind>*/new Action((o) => { }, new object())/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... w object())')
Children(2):
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(o) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0149: Method name expected
// Action action = /*<bind>*/new Action((o) => { }, new object())/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(o) => { }, new object()").WithLocation(8, 46)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1()
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitStaticMethodBindingConversion_01()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
static void M1()
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitStaticMethodBindingConversion_02()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(this.M1)/*</bind>*/;
}
static void M1()
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(this.M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'this.M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid) (Syntax: 'this')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,41): error CS0176: Member 'Program.M1()' cannot be accessed with an instance reference; qualify it with a type name instead
// Action a = /*<bind>*/new Action(this.M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M1").WithArguments("Program.M1()").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversionWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
var p = new Program();
Action a = /*<bind>*/new Action(p.M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(p.M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'p.M1')
Instance Receiver:
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program) (Syntax: 'p')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion_InvalidMissingIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
int M1() => 1;
}
";
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[] {
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 41)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[] {
// file.cs(7,41): error CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 41)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1(object o)
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action(M1)").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateCreation_InvalidMultipleParameters()
{
string source = @"
using System;
class C
{
void M1()
{
Action action = /*<bind>*/new Action(M2, M3)/*</bind>*/;
}
void M2()
{
}
void M3()
{
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action(M2, M3)')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M3')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0149: Method name expected
// Action action = /*<bind>*/new Action(M2, M3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethodNameExpected, "M2, M3").WithLocation(8, 46)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_InvalidTargetArguments()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<string>'
// Action<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action(M1)").WithArguments("System.Action", "System.Action<string>").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_InvalidTargetReturn()
{
string source = @"
using System;
class Program
{
void Main()
{
Func<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<string>'
// Func<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action(M1)").WithArguments("System.Action", "System.Func<string>").WithLocation(7, 36)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)(() => { }))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action( ... () => { }))')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)(() => 1))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... )(() => 1))')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action a = /*<bind>*/new Action((Action)(() => 1))/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 56)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)((int i) => { }))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... i) => { }))')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)((int i) => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// Action a = /*<bind>*/new Action((Action)((int i) => { }))/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 50)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1() {}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action((Action)M1)')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidMissingIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Children(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 49)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
int M1() => 1;
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "(Action)M1").WithArguments("Program.M1()", "int").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1(int i) { }
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,41): error CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "(Action)M1").WithArguments("M1", "System.Action").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidTargetArgument()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<string>'
// Action<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action((Action)M1)").WithArguments("System.Action", "System.Action<string>").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidTargetReturn()
{
string source = @"
using System;
class Program
{
void Main()
{
Func<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<string>'
// Func<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action((Action)M1)").WithArguments("System.Action", "System.Func<string>").WithLocation(7, 36)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidConstructorArgument()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<int> a = /*<bind>*/new Action<int>((Action)M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action<System.Int32>, IsInvalid) (Syntax: 'new Action< ... (Action)M1)')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,35): error CS0123: No overload for 'Action.Invoke()' matches delegate 'Action<int>'
// Action<int> a = /*<bind>*/new Action<int>((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action<int>((Action)M1)").WithArguments("System.Action.Invoke()", "System.Action<int>").WithLocation(7, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConversionExpression_Implicit_ReferenceLambdaToDelegateConversion_InvalidSyntax()
{
string source = @"
class Program
{
delegate void DType();
void Main()
{
DType /*<bind>*/d1 = () =>/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: Program.DType d1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'd1 = () =>/*</bind>*/')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () =>/*</bind>*/')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Program.DType, IsInvalid, IsImplicit) (Syntax: '() =>/*</bind>*/')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() =>/*</bind>*/')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term ';'
// DType /*<bind>*/d1 = () =>/*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 46)
};
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics,
additionalOperationTreeVerifier: new IOperationTests_IConversionExpression.ExpectedSymbolVerifier().Verify);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_MultipleCandidates_InvalidNoMatch()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action<int> a = M1;/*</bind>*/
}
void M1(Program o) { }
void M1(string s) { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: 'M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'Program.M1(object)' matches delegate 'Action<int>'
// /*<bind>*/Action<int> a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M1").WithArguments("M1", "System.Action<int>").WithLocation(7, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_MultipleCandidates()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action<int> a = M1;/*</bind>*/
}
void M1(object o) { }
void M1(int i) { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action<int> a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action<int> a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsImplicit) (Syntax: 'M1')
Target:
IMethodReferenceOperation: void Program.M1(System.Int32 i) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_MultipleCandidates()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<string> a = /*<bind>*/new Action<string>(M1)/*</bind>*/;
}
void M1(object o) { }
void M1(string s) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>) (Syntax: 'new Action<string>(M1)')
Target:
IMethodReferenceOperation: void Program.M1(System.String s) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_MultipleCandidates_InvalidNoMatch()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<int> a = /*<bind>*/new Action<int>(M1)/*</bind>*/;
}
void M1(Program o) { }
void M1(string s) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid) (Syntax: 'new Action<int>(M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'Program.M1(object)' matches delegate 'Action<int>'
// Action<int> a = /*<bind>*/new Action<int>(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action<int>(M1)").WithArguments("M1", "System.Action<int>").WithLocation(7, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DelegateCreation_NoControlFlow()
{
string source = @"
using System;
class C
{
void M(Action a1, Action a2, Action a3, Action a4)
/*<bind>*/{
a1 = () => { };
a2 = M2;
a3 = new Action(a4);
}/*</bind>*/
void M2() { }
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = () => { };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a1 = () => { }')
Left:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { }')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '() => { }')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Exit
Predecessors: [B0#A0]
Statements (0)
}
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a2 = M2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a2 = M2')
Left:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'M2')
Target:
IMethodReferenceOperation: void C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a3 = new Action(a4);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a3 = new Action(a4)')
Left:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a3')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(a4)')
Target:
IParameterReferenceOperation: a4 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a4')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DelegateCreation_ControlFlowInTarget()
{
string source = @"
using System;
class C
{
void M(Action a1, Action a2, Action a3)
/*<bind>*/
{
a1 = new Action(a2 ?? a3);
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a2')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a2')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a2')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a3')
Value:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new Ac ... (a2 ?? a3);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a1 = new Ac ... n(a2 ?? a3)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(a2 ?? a3)')
Target:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a2 ?? a3')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDelegateCreationExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = () => { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action a = () => { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action a = () => { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = () => { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion_InitializerBindingReturnsJustAnonymousFunction()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/() => { }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = () => 1;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = () => 1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = () => 1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = () => 1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: '() => 1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// /*<bind>*/Action a = () => 1;/*</bind>*/
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 36)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = (int i) => { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = ... i) => { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = ... t i) => { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = (int i) => { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (int i) => { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: '(int i) => { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// /*<bind>*/Action a = (int i) => { };/*</bind>*/
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)(() => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)(() => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action a = /*<bind>*/(Action)(() => 1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 45)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)((int i) => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)((int i) => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// Action a = /*<bind>*/(Action)((int i) => { })/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 39)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_DelegateExpression()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = delegate() { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action a = ... gate() { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action a = ... egate() { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = delegate() { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= delegate() { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'delegate() { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'delegate() { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_DelegateExpression_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = delegate() { return 1; };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = ... eturn 1; };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = ... return 1; }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = delegat ... return 1; }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= delegate( ... return 1; }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'delegate() { return 1; }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate() { return 1; }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ return 1; }')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8030: Anonymous function converted to a void returning delegate cannot return a value
// /*<bind>*/Action a = delegate() { return 1; };/*</bind>*/
Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 43)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_DelegateExpression_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = delegate(int i) { };/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = ... int i) { };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = ... (int i) { }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = delegate(int i) { }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= delegate(int i) { }')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'delegate(int i) { }')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate(int i) { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// /*<bind>*/Action a = delegate(int i) { };/*</bind>*/
Diagnostic(ErrorCode.ERR_BadDelArgCount, "delegate(int i) { }").WithArguments("System.Action", "1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
void M1() { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")]
public void DelegateCreationExpression_ImplicitMethodBinding_InitializerBindingReturnsJustMethodReference()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
static void M1() { }
}
";
string expectedOperationTree = @"
IMethodReferenceOperation: void Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// /*<bind>*/Action a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidIdentifier_InitializerBindingReturnsJustInvalidExpression()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
int M1() => 1;
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0407: 'int Program.M1()' has the wrong return type
// /*<bind>*/Action a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidReturnType_InitializerBindingReturnsJustMethodReference()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
int M1() => 1;
}
";
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, @"
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[]
{
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, @"
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[]
{
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action a = M1;/*</bind>*/
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'M1' matches delegate 'Action'
// /*<bind>*/Action a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M1").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_InvalidArgumentType_InitializerBindingReturnsJustNoneOperation()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/M1/*</bind>*/;
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M1").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/(Action)M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidIdentifierWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
object o = new object();
Action a = /*<bind>*/(Action)o.M1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid) (Syntax: '(Action)o.M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'o.M1')
Children(1):
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'object' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// Action a = /*<bind>*/(Action)o.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("object", "M1").WithLocation(8, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
int M1() => 1;
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/(Action)M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "(Action)M1").WithArguments("Program.M1()", "int").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
}
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidReturnTypeWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
Program p = new Program();
Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
}
int M1() => 1;
}
";
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)p.M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'p.M1')
Instance Receiver:
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'p')
", new DiagnosticDescription[] {
// file.cs(8,30): error CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "(Action)p.M1").WithArguments("Program.M1()", "int").WithLocation(8, 30)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)p.M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'p.M1')
Children(1):
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'p')
", new DiagnosticDescription[] {
// file.cs(8,38): error CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "p.M1").WithArguments("Program.M1()", "int").WithLocation(8, 38)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/(Action)M1/*</bind>*/;
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[]
{
// file.cs(7,30): error CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/(Action)M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "(Action)M1").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitMethodBinding_InvalidArgumentTypeWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
Program p = new Program();
Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
}
void M1(object o) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)p.M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'p.M1')
Children(1):
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'p')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,30): error CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/(Action)p.M1/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "(Action)p.M1").WithArguments("M1", "System.Action").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<CastExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(() => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(() => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(() => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(() => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action a = /*<bind>*/new Action(() => 1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 47)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((int i) => { })/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... i) => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// Action a = /*<bind>*/new Action((int i) => { })/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitLambdaConversion_InvalidMultipleParameters()
{
string source = @"
using System;
class C
{
void M1()
{
Action action = /*<bind>*/new Action((o) => { }, new object())/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... w object())')
Children(2):
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(o) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0149: Method name expected
// Action action = /*<bind>*/new Action((o) => { }, new object())/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(o) => { }, new object()").WithLocation(8, 46)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1()
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitStaticMethodBindingConversion_01()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
static void M1()
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitStaticMethodBindingConversion_02()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(this.M1)/*</bind>*/;
}
static void M1()
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(this.M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'this.M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid) (Syntax: 'this')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,41): error CS0176: Member 'Program.M1()' cannot be accessed with an instance reference; qualify it with a type name instead
// Action a = /*<bind>*/new Action(this.M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M1").WithArguments("Program.M1()").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversionWithReceiver()
{
string source = @"
using System;
class Program
{
void Main()
{
var p = new Program();
Action a = /*<bind>*/new Action(p.M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(p.M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'p.M1')
Instance Receiver:
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: Program) (Syntax: 'p')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion_InvalidMissingIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
int M1() => 1;
}
";
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[] {
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 41)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
", new DiagnosticDescription[] {
// file.cs(7,41): error CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "int").WithLocation(7, 41)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndImplicitMethodBindingConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1(object o)
{ }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action(M1)").WithArguments("M1", "System.Action").WithLocation(7, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateCreation_InvalidMultipleParameters()
{
string source = @"
using System;
class C
{
void M1()
{
Action action = /*<bind>*/new Action(M2, M3)/*</bind>*/;
}
void M2()
{
}
void M3()
{
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action(M2, M3)')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M3')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0149: Method name expected
// Action action = /*<bind>*/new Action(M2, M3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethodNameExpected, "M2, M3").WithLocation(8, 46)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_InvalidTargetArguments()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<string>'
// Action<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action(M1)").WithArguments("System.Action", "System.Action<string>").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_InvalidTargetReturn()
{
string source = @"
using System;
class Program
{
void Main()
{
Func<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action(M1)')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<string>'
// Func<string> a = /*<bind>*/new Action(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action(M1)").WithArguments("System.Action", "System.Func<string>").WithLocation(7, 36)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitLambdaConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)(() => { }))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action( ... () => { }))')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => { }')
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitLambdaConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)(() => 1))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... )(() => 1))')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => 1')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Expression:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action a = /*<bind>*/new Action((Action)(() => 1))/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(7, 56)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitLambdaConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)((int i) => { }))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action( ... i) => { }))')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)((int i) => { })')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(int i) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1593: Delegate 'Action' does not take 1 arguments
// Action a = /*<bind>*/new Action((Action)((int i) => { }))/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int i) => { }").WithArguments("System.Action", "1").WithLocation(7, 50)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1() {}
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action((Action)M1)')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidMissingIdentifier()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Children(1):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M1')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'M1' does not exist in the current context
// Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "M1").WithArguments("M1").WithLocation(7, 49)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidReturnType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
int M1() => 1;
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: System.Int32 Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0407: 'int Program.M1()' has the wrong return type
// Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadRetType, "(Action)M1").WithArguments("Program.M1()", "int").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidArgumentType()
{
string source = @"
using System;
class Program
{
void Main()
{
Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1(int i) { }
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,41): error CS0123: No overload for 'M1' matches delegate 'Action'
// Action a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "(Action)M1").WithArguments("M1", "System.Action").WithLocation(7, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidTargetArgument()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<string>'
// Action<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action((Action)M1)").WithArguments("System.Action", "System.Action<string>").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidTargetReturn()
{
string source = @"
using System;
class Program
{
void Main()
{
Func<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'new Action((Action)M1)')
Target:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<string>'
// Func<string> a = /*<bind>*/new Action((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Action((Action)M1)").WithArguments("System.Action", "System.Func<string>").WithLocation(7, 36)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorAndExplicitMethodBindingConversion_InvalidConstructorArgument()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<int> a = /*<bind>*/new Action<int>((Action)M1)/*</bind>*/;
}
void M1() { }
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: System.Action<System.Int32>, IsInvalid) (Syntax: 'new Action< ... (Action)M1)')
Children(1):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)M1')
Target:
IMethodReferenceOperation: void Program.M1() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(7,35): error CS0123: No overload for 'Action.Invoke()' matches delegate 'Action<int>'
// Action<int> a = /*<bind>*/new Action<int>((Action)M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action<int>((Action)M1)").WithArguments("System.Action.Invoke()", "System.Action<int>").WithLocation(7, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConversionExpression_Implicit_ReferenceLambdaToDelegateConversion_InvalidSyntax()
{
string source = @"
class Program
{
delegate void DType();
void Main()
{
DType /*<bind>*/d1 = () =>/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: Program.DType d1) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'd1 = () =>/*</bind>*/')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () =>/*</bind>*/')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Program.DType, IsInvalid, IsImplicit) (Syntax: '() =>/*</bind>*/')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() =>/*</bind>*/')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '')
ReturnedValue:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term ';'
// DType /*<bind>*/d1 = () =>/*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 46)
};
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics,
additionalOperationTreeVerifier: new IOperationTests_IConversionExpression.ExpectedSymbolVerifier().Verify);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_MultipleCandidates_InvalidNoMatch()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action<int> a = M1;/*</bind>*/
}
void M1(Program o) { }
void M1(string s) { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> a) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: 'M1')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'Program.M1(object)' matches delegate 'Action<int>'
// /*<bind>*/Action<int> a = M1;/*</bind>*/
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M1").WithArguments("M1", "System.Action<int>").WithLocation(7, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ImplicitMethodBinding_MultipleCandidates()
{
string source = @"
using System;
class Program
{
void Main()
{
/*<bind>*/Action<int> a = M1;/*</bind>*/
}
void M1(object o) { }
void M1(int i) { }
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action<int> a = M1;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action<int> a = M1')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = M1')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= M1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsImplicit) (Syntax: 'M1')
Target:
IMethodReferenceOperation: void Program.M1(System.Int32 i) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_MultipleCandidates()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<string> a = /*<bind>*/new Action<string>(M1)/*</bind>*/;
}
void M1(object o) { }
void M1(string s) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>) (Syntax: 'new Action<string>(M1)')
Target:
IMethodReferenceOperation: void Program.M1(System.String s) (OperationKind.MethodReference, Type: null) (Syntax: 'M1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DelegateCreationExpression_ExplicitDelegateConstructorImplicitMethodBinding_MultipleCandidates_InvalidNoMatch()
{
string source = @"
using System;
class Program
{
void Main()
{
Action<int> a = /*<bind>*/new Action<int>(M1)/*</bind>*/;
}
void M1(Program o) { }
void M1(string s) { }
}
";
string expectedOperationTree = @"
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid) (Syntax: 'new Action<int>(M1)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M1')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0123: No overload for 'Program.M1(object)' matches delegate 'Action<int>'
// Action<int> a = /*<bind>*/new Action<int>(M1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action<int>(M1)").WithArguments("M1", "System.Action<int>").WithLocation(7, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DelegateCreation_NoControlFlow()
{
string source = @"
using System;
class C
{
void M(Action a1, Action a2, Action a3, Action a4)
/*<bind>*/{
a1 = () => { };
a2 = M2;
a3 = new Action(a4);
}/*</bind>*/
void M2() { }
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = () => { };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a1 = () => { }')
Left:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => { }')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '() => { }')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Exit
Predecessors: [B0#A0]
Statements (0)
}
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a2 = M2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a2 = M2')
Left:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'M2')
Target:
IMethodReferenceOperation: void C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a3 = new Action(a4);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a3 = new Action(a4)')
Left:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a3')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(a4)')
Target:
IParameterReferenceOperation: a4 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a4')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DelegateCreation_ControlFlowInTarget()
{
string source = @"
using System;
class C
{
void M(Action a1, Action a2, Action a3)
/*<bind>*/
{
a1 = new Action(a2 ?? a3);
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a2')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a2')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a2')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a2')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a3')
Value:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = new Ac ... (a2 ?? a3);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action) (Syntax: 'a1 = new Ac ... n(a2 ?? a3)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'new Action(a2 ?? a3)')
Target:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a2 ?? a3')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/VisualBasicTest/Structure/DelegateDeclarationStructureTests.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 DelegateDeclarationStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DelegateStatementSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New DelegateDeclarationStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDelegateWithComments() As Task
Const code = "
{|span:'Hello
'World|}
Delegate Sub $$Goo()
"
Await VerifyBlockSpansAsync(code,
Region("span", "' Hello ...", autoCollapse:=True))
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class DelegateDeclarationStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DelegateStatementSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New DelegateDeclarationStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDelegateWithComments() As Task
Const code = "
{|span:'Hello
'World|}
Delegate Sub $$Goo()
"
Await VerifyBlockSpansAsync(code,
Region("span", "' Hello ...", autoCollapse:=True))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpFindReferences.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpFindReferences : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpFindReferences(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpFindReferences))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void FindReferencesToCtor()
{
SetUpEditor(@"
class Program
{
}$$
");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "File2.cs");
VisualStudio.SolutionExplorer.OpenFile(project, "File2.cs");
SetUpEditor(@"
class SomeOtherClass
{
void M()
{
Program p = new Progr$$am();
}
}
");
VisualStudio.Editor.SendKeys(Shift(VirtualKey.F12));
const string programReferencesCaption = "'Program' references";
var results = VisualStudio.FindReferencesWindow.GetContents(programReferencesCaption);
var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption();
Assert.Equal(expected: programReferencesCaption, actual: activeWindowCaption);
Assert.Collection(
results,
new Action<Reference>[]
{
reference =>
{
Assert.Equal(expected: "class Program", actual: reference.Code);
Assert.Equal(expected: 1, actual: reference.Line);
Assert.Equal(expected: 6, actual: reference.Column);
},
reference =>
{
Assert.Equal(expected: "Program p = new Program();", actual: reference.Code);
Assert.Equal(expected: 5, actual: reference.Line);
Assert.Equal(expected: 24, actual: reference.Column);
}
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void FindReferencesToLocals()
{
using var telemetry = VisualStudio.EnableTestTelemetryChannel();
SetUpEditor(@"
class Program
{
static void Main()
{
int local = 1;
Console.WriteLine(local$$);
}
}
");
VisualStudio.Editor.SendKeys(Shift(VirtualKey.F12));
const string localReferencesCaption = "'local' references";
var results = VisualStudio.FindReferencesWindow.GetContents(localReferencesCaption);
var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption();
Assert.Equal(expected: localReferencesCaption, actual: activeWindowCaption);
Assert.Collection(
results,
new Action<Reference>[]
{
reference =>
{
Assert.Equal(expected: "int local = 1;", actual: reference.Code);
Assert.Equal(expected: 5, actual: reference.Line);
Assert.Equal(expected: 12, actual: reference.Column);
},
reference =>
{
Assert.Equal(expected: "Console.WriteLine(local);", actual: reference.Code);
Assert.Equal(expected: 6, actual: reference.Line);
Assert.Equal(expected: 26, actual: reference.Column);
}
});
telemetry.VerifyFired("vs/platform/findallreferences/search", "vs/ide/vbcs/commandhandler/findallreference");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void FindReferencesToString()
{
SetUpEditor(@"
class Program
{
static void Main()
{
string local = ""1""$$;
}
}
");
VisualStudio.Editor.SendKeys(Shift(VirtualKey.F12));
const string findReferencesCaption = "'\"1\"' references";
var results = VisualStudio.FindReferencesWindow.GetContents(findReferencesCaption);
var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption();
Assert.Equal(expected: findReferencesCaption, actual: activeWindowCaption);
Assert.Collection(
results,
new Action<Reference>[]
{
reference =>
{
Assert.Equal(expected: "string local = \"1\";", actual: reference.Code);
Assert.Equal(expected: 5, actual: reference.Line);
Assert.Equal(expected: 24, actual: reference.Column);
}
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void VerifyWorkingFolder()
{
SetUpEditor(@"class EmptyContent {$$}");
// verify working folder has set
Assert.NotNull(VisualStudio.Workspace.GetWorkingFolder());
VisualStudio.SolutionExplorer.CloseSolution();
// because the solution cache directory is stored in the user temp folder,
// closing the solution has no effect on what is returned.
Assert.NotNull(VisualStudio.Workspace.GetWorkingFolder());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpFindReferences : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpFindReferences(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpFindReferences))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void FindReferencesToCtor()
{
SetUpEditor(@"
class Program
{
}$$
");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "File2.cs");
VisualStudio.SolutionExplorer.OpenFile(project, "File2.cs");
SetUpEditor(@"
class SomeOtherClass
{
void M()
{
Program p = new Progr$$am();
}
}
");
VisualStudio.Editor.SendKeys(Shift(VirtualKey.F12));
const string programReferencesCaption = "'Program' references";
var results = VisualStudio.FindReferencesWindow.GetContents(programReferencesCaption);
var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption();
Assert.Equal(expected: programReferencesCaption, actual: activeWindowCaption);
Assert.Collection(
results,
new Action<Reference>[]
{
reference =>
{
Assert.Equal(expected: "class Program", actual: reference.Code);
Assert.Equal(expected: 1, actual: reference.Line);
Assert.Equal(expected: 6, actual: reference.Column);
},
reference =>
{
Assert.Equal(expected: "Program p = new Program();", actual: reference.Code);
Assert.Equal(expected: 5, actual: reference.Line);
Assert.Equal(expected: 24, actual: reference.Column);
}
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void FindReferencesToLocals()
{
using var telemetry = VisualStudio.EnableTestTelemetryChannel();
SetUpEditor(@"
class Program
{
static void Main()
{
int local = 1;
Console.WriteLine(local$$);
}
}
");
VisualStudio.Editor.SendKeys(Shift(VirtualKey.F12));
const string localReferencesCaption = "'local' references";
var results = VisualStudio.FindReferencesWindow.GetContents(localReferencesCaption);
var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption();
Assert.Equal(expected: localReferencesCaption, actual: activeWindowCaption);
Assert.Collection(
results,
new Action<Reference>[]
{
reference =>
{
Assert.Equal(expected: "int local = 1;", actual: reference.Code);
Assert.Equal(expected: 5, actual: reference.Line);
Assert.Equal(expected: 12, actual: reference.Column);
},
reference =>
{
Assert.Equal(expected: "Console.WriteLine(local);", actual: reference.Code);
Assert.Equal(expected: 6, actual: reference.Line);
Assert.Equal(expected: 26, actual: reference.Column);
}
});
telemetry.VerifyFired("vs/platform/findallreferences/search", "vs/ide/vbcs/commandhandler/findallreference");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void FindReferencesToString()
{
SetUpEditor(@"
class Program
{
static void Main()
{
string local = ""1""$$;
}
}
");
VisualStudio.Editor.SendKeys(Shift(VirtualKey.F12));
const string findReferencesCaption = "'\"1\"' references";
var results = VisualStudio.FindReferencesWindow.GetContents(findReferencesCaption);
var activeWindowCaption = VisualStudio.Shell.GetActiveWindowCaption();
Assert.Equal(expected: findReferencesCaption, actual: activeWindowCaption);
Assert.Collection(
results,
new Action<Reference>[]
{
reference =>
{
Assert.Equal(expected: "string local = \"1\";", actual: reference.Code);
Assert.Equal(expected: 5, actual: reference.Line);
Assert.Equal(expected: 24, actual: reference.Column);
}
});
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FindReferences)]
public void VerifyWorkingFolder()
{
SetUpEditor(@"class EmptyContent {$$}");
// verify working folder has set
Assert.NotNull(VisualStudio.Workspace.GetWorkingFolder());
VisualStudio.SolutionExplorer.CloseSolution();
// because the solution cache directory is stored in the user temp folder,
// closing the solution has no effect on what is returned.
Assert.NotNull(VisualStudio.Workspace.GetWorkingFolder());
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/Core/Test.Next/Remote/SnapshotSerializationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Remote.UnitTests
{
[CollectionDefinition(Name)]
public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture>
{
public const string Name = nameof(AssemblyLoadTestFixtureCollection);
private AssemblyLoadTestFixtureCollection() { }
}
[Collection(AssemblyLoadTestFixtureCollection.Name)]
[UseExportProvider]
public class SnapshotSerializationTests
{
private readonly AssemblyLoadTestFixture _testFixture;
public SnapshotSerializationTests(AssemblyLoadTestFixture testFixture)
{
_testFixture = testFixture;
}
private static Workspace CreateWorkspace(Type[] additionalParts = null)
=> new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).WithTestHostParts(TestHost.OutOfProcess).GetHostServices());
internal static Solution CreateFullSolution(Workspace workspace)
{
var solution = workspace.CurrentSolution;
var languages = ImmutableHashSet.Create(LanguageNames.CSharp, LanguageNames.VisualBasic);
var solutionOptions = solution.Workspace.Services.GetRequiredService<IOptionService>().GetSerializableOptionsSnapshot(languages);
solution = solution.WithOptions(solutionOptions);
var csCode = "class A { }";
var project1 = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var document1 = project1.AddDocument("Document1", SourceText.From(csCode));
var vbCode = "Class B\r\nEnd Class";
var project2 = document1.Project.Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic);
var document2 = project2.AddDocument("Document2", SourceText.From(vbCode));
solution = document2.Project.Solution.GetRequiredProject(project1.Id)
.AddProjectReference(new ProjectReference(project2.Id, ImmutableArray.Create("test")))
.AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddAnalyzerReference(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path1"), new TestAnalyzerAssemblyLoader()))
.AddAdditionalDocument("Additional", SourceText.From("hello"), ImmutableArray.Create("test"), @".\Add").Project.Solution;
return solution
.WithAnalyzerReferences(new[] { new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path2"), new TestAnalyzerAssemblyLoader()) })
.AddAnalyzerConfigDocuments(
ImmutableArray.Create(
DocumentInfo.Create(
DocumentId.CreateNewId(project1.Id),
".editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("root = true"), VersionStamp.Create())))));
}
[Fact]
public async Task CreateSolutionSnapshotId_Empty()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var checksum = scope.SolutionInfo.SolutionChecksum;
var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false);
var projectsSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(projectsSyncObject).ConfigureAwait(false);
Assert.Equal(0, solutionObject.Projects.Count);
}
[Fact]
public async Task CreateSolutionSnapshotId_Empty_Serialization()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Project()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
var checksum = scope.SolutionInfo.SolutionChecksum;
var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet);
var projectSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(projectSyncObject).ConfigureAwait(false);
Assert.Equal(1, solutionObject.Projects.Count);
await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 0, 0, 0, 0, 0).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Project_Serialization()
{
using var workspace = CreateWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(project.Solution, snapshot.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId()
{
var code = "class A { }";
using var workspace = CreateWorkspace();
var document = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code));
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false);
var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false);
Assert.Equal(1, solutionObject.Projects.Count);
await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 1, 0, 0, 0, 0).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Serialization()
{
var code = "class A { }";
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var document = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code));
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(document.Project.Solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var firstProjectChecksum = await solution.GetProject(solution.ProjectIds[0]).State.GetChecksumAsync(CancellationToken.None);
var secondProjectChecksum = await solution.GetProject(solution.ProjectIds[1]).State.GetChecksumAsync(CancellationToken.None);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false);
Assert.Equal(2, solutionObject.Projects.Count);
var projects = validator.ToProjectObjects(solutionObject.Projects);
await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == firstProjectChecksum).First(), 1, 1, 1, 1, 1).ConfigureAwait(false);
await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == secondProjectChecksum).First(), 1, 0, 0, 0, 0).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full_Serialization()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full_Asset_Serialization()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum);
await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full_Asset_Serialization_Desktop()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum);
await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Duplicate()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
// this is just data, one can hold the id outside of using statement. but
// one can't get asset using checksum from the id.
SolutionStateChecksums solutionId1;
SolutionStateChecksums solutionId2;
var validator = new SerializationValidator(workspace.Services);
using (var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false))
{
solutionId1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
using (var scope2 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false))
{
solutionId2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
// once pinned snapshot scope is released, there is no way to get back to asset.
// catch Exception because it will throw 2 different exception based on release or debug (ExceptionUtilities.UnexpectedValue)
Assert.ThrowsAny<Exception>(() => validator.SolutionStateEqual(solutionId1, solutionId2));
}
[Fact]
public void MetadataReference_RoundTrip_Test()
{
using var workspace = CreateWorkspace();
var reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var serializer = workspace.Services.GetService<ISerializerService>();
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public async Task Workspace_RoundTrip_Test()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
// recover solution from given snapshot
var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false);
var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
// create new snapshot from recovered solution
using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false);
// verify asset created by recovered solution is good
var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false);
// verify snapshots created from original solution and recovered solution are same
validator.SolutionStateEqual(solutionObject1, solutionObject2);
// recover new solution from recovered solution
var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false);
// create new snapshot from round tripped solution
using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false);
// verify asset created by rount trip solution is good
var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false);
// verify snapshots created from original solution and round trip solution are same.
validator.SolutionStateEqual(solutionObject2, solutionObject3);
}
[Fact]
public async Task Workspace_RoundTrip_Test_Desktop()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
// recover solution from given snapshot
var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false);
var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
// create new snapshot from recovered solution
using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false);
// verify asset created by recovered solution is good
var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false);
// verify snapshots created from original solution and recovered solution are same
validator.SolutionStateEqual(solutionObject1, solutionObject2);
scope1.Dispose();
// recover new solution from recovered solution
var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false);
// create new snapshot from round tripped solution
using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false);
// verify asset created by rount trip solution is good
var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false);
// verify snapshots created from original solution and round trip solution are same.
validator.SolutionStateEqual(solutionObject2, solutionObject3);
}
[Fact]
public async Task OptionSet_Serialization()
{
using var workspace = CreateWorkspace()
.CurrentSolution.AddProject("Project1", "Project.dll", LanguageNames.CSharp)
.Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic)
.Solution.Workspace;
await VerifyOptionSetsAsync(workspace, _ => { }).ConfigureAwait(false);
}
[Fact]
public async Task OptionSet_Serialization_CustomValue()
{
using var workspace = CreateWorkspace();
var newQualifyFieldAccessValue = new CodeStyleOption2<bool>(false, NotificationOption2.Error);
var newQualifyMethodAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Warning);
var newVarWhenTypeIsApparentValue = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion);
var newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Silent);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp, newQualifyFieldAccessValue)
.WithChangedOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic, newQualifyMethodAccessValue)
.WithChangedOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, newVarWhenTypeIsApparentValue)
.WithChangedOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic, newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue)));
var validator = new SerializationValidator(workspace.Services);
await VerifyOptionSetsAsync(workspace, VerifyOptions).ConfigureAwait(false);
void VerifyOptions(OptionSet options)
{
var actualQualifyFieldAccessValue = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp);
Assert.Equal(newQualifyFieldAccessValue, actualQualifyFieldAccessValue);
var actualQualifyMethodAccessValue = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic);
Assert.Equal(newQualifyMethodAccessValue, actualQualifyMethodAccessValue);
var actualVarWhenTypeIsApparentValue = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent);
Assert.Equal(newVarWhenTypeIsApparentValue, actualVarWhenTypeIsApparentValue);
var actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = options.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic);
Assert.Equal(newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue, actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue);
}
}
[Fact]
public void Missing_Metadata_Serialization_Test()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
var reference = new MissingMetadataReference();
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void Missing_Analyzer_Serialization_Test()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader());
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void Missing_Analyzer_Serialization_Desktop_Test()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader());
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void RoundTrip_Analyzer_Serialization_Test()
{
using var tempRoot = new TempRoot();
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
// actually shadow copy content
var location = typeof(object).Assembly.Location;
var file = tempRoot.CreateFile("shadow", "dll");
file.CopyContentFrom(location);
var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path)));
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void RoundTrip_Analyzer_Serialization_Desktop_Test()
{
using var tempRoot = new TempRoot();
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
// actually shadow copy content
var location = typeof(object).Assembly.Location;
var file = tempRoot.CreateFile("shadow", "dll");
file.CopyContentFrom(location);
var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path)));
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void ShadowCopied_Analyzer_Serialization_Desktop_Test()
{
using var tempRoot = new TempRoot();
using var workspace = CreateWorkspace();
var reference = CreateShadowCopiedAnalyzerReference(tempRoot);
var serializer = workspace.Services.GetService<ISerializerService>();
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
// this will verify serialized analyzer reference return same checksum as the original one
_ = CloneAsset(serializer, assetFromFile);
}
[Fact]
[WorkItem(1107294, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107294")]
public async Task SnapshotWithIdenticalAnalyzerFiles()
{
using var workspace = CreateWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
using var temp = new TempRoot();
var dir = temp.CreateDirectory();
// create two analyzer assembly files whose content is identical but path is different:
var file1 = dir.CreateFile("analyzer1.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path);
var file2 = dir.CreateFile("analyzer2.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path);
var analyzer1 = new AnalyzerFileReference(file1.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);
var analyzer2 = new AnalyzerFileReference(file2.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);
project = project.AddAnalyzerReferences(new[] { analyzer1, analyzer2 });
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false);
AssertEx.Equal(new[] { file1.Path, file2.Path }, recovered.GetProject(project.Id).AnalyzerReferences.Select(r => r.FullPath));
}
[Fact]
public async Task SnapshotWithMissingReferencesTest()
{
using var workspace = CreateWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var metadata = new MissingMetadataReference();
var analyzer = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader());
project = project.AddMetadataReference(metadata);
project = project.AddAnalyzerReference(analyzer);
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
// this shouldn't throw
var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false);
}
[Fact]
public async Task UnknownLanguageTest()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName);
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
// this shouldn't throw
var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false);
}
[Fact, WorkItem(44791, "https://github.com/dotnet/roslyn/issues/44791")]
public async Task UnknownLanguageOptionsTest()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName)
.Solution.AddProject("Project2", "Project2.dll", LanguageNames.CSharp);
workspace.TryApplyChanges(project.Solution);
await VerifyOptionSetsAsync(workspace, verifyOptionValues: _ => { });
}
[Fact]
public async Task EmptyAssetChecksumTest()
{
var document = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.CSharp).AddDocument("empty", SourceText.From(""));
var serializer = document.Project.Solution.Workspace.Services.GetService<ISerializerService>();
var source = serializer.CreateChecksum(await document.GetTextAsync().ConfigureAwait(false), CancellationToken.None);
var metadata = serializer.CreateChecksum(new MissingMetadataReference(), CancellationToken.None);
var analyzer = serializer.CreateChecksum(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing"), new MissingAnalyzerLoader()), CancellationToken.None);
Assert.NotEqual(source, metadata);
Assert.NotEqual(source, analyzer);
Assert.NotEqual(metadata, analyzer);
}
[Fact]
public async Task VBParseOptionsInCompilationOptions()
{
var project = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.VisualBasic);
project = project.WithCompilationOptions(
((VisualBasic.VisualBasicCompilationOptions)project.CompilationOptions).WithParseOptions((VisualBasic.VisualBasicParseOptions)project.ParseOptions));
var checksum = await project.State.GetChecksumAsync(CancellationToken.None).ConfigureAwait(false);
Assert.NotNull(checksum);
}
[Fact]
public async Task TestMetadataXmlDocComment()
{
using var tempRoot = new TempRoot();
// get original assembly location
var mscorlibLocation = typeof(object).Assembly.Location;
// set up dll and xml doc content
var tempDir = tempRoot.CreateDirectory();
var tempCorlib = tempDir.CopyFile(mscorlibLocation);
var tempCorlibXml = tempDir.CreateFile(Path.ChangeExtension(tempCorlib.Path, "xml"));
tempCorlibXml.WriteAllText(@"<?xml version=""1.0"" encoding=""utf-8""?>
<doc>
<assembly>
<name>mscorlib</name>
</assembly>
<members>
<member name=""T:System.Object"">
<summary>Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.To browse the .NET Framework source code for this type, see the Reference Source.</summary>
</member>
</members>
</doc>");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject("Project", "Project.dll", LanguageNames.CSharp)
.AddMetadataReference(MetadataReference.CreateFromFile(tempCorlib.Path))
.Solution;
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None);
// recover solution from given snapshot
var recovered = await validator.GetSolutionAsync(scope);
var compilation = await recovered.Projects.First().GetCompilationAsync(CancellationToken.None);
var objectType = compilation.GetTypeByMetadataName("System.Object");
var xmlDocComment = objectType.GetDocumentationCommentXml();
Assert.False(string.IsNullOrEmpty(xmlDocComment));
}
[Fact]
public void TestEncodingSerialization()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
// test with right serializable encoding
var sourceText = SourceText.From("Hello", Encoding.UTF8);
using (var stream = SerializableBytes.CreateWritableStream())
{
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
using var objectReader = ObjectReader.TryGetReader(stream);
var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
Assert.Equal(sourceText.ToString(), newText.ToString());
}
// test with wrong encoding that doesn't support serialization
sourceText = SourceText.From("Hello", new NotSerializableEncoding());
using (var stream = SerializableBytes.CreateWritableStream())
{
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
using var objectReader = ObjectReader.TryGetReader(stream);
var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
Assert.Equal(sourceText.ToString(), newText.ToString());
}
}
[Fact]
public void TestCompilationOptions_NullableAndImport()
{
var csharpOptions = CSharp.CSharpCompilation.Create("dummy").Options.WithNullableContextOptions(NullableContextOptions.Warnings).WithMetadataImportOptions(MetadataImportOptions.All);
var vbOptions = VisualBasic.VisualBasicCompilation.Create("dummy").Options.WithMetadataImportOptions(MetadataImportOptions.Internal);
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
VerifyOptions(csharpOptions);
VerifyOptions(vbOptions);
void VerifyOptions(CompilationOptions originalOptions)
{
using var stream = SerializableBytes.CreateWritableStream();
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(originalOptions, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
using var objectReader = ObjectReader.TryGetReader(stream);
var recoveredOptions = serializer.Deserialize<CompilationOptions>(originalOptions.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
var original = serializer.CreateChecksum(originalOptions, CancellationToken.None);
var recovered = serializer.CreateChecksum(recoveredOptions, CancellationToken.None);
Assert.Equal(original, recovered);
}
}
private static async Task VerifyOptionSetsAsync(Workspace workspace, Action<OptionSet> verifyOptionValues)
{
var solution = workspace.CurrentSolution;
verifyOptionValues(workspace.Options);
verifyOptionValues(solution.Options);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var checksum = scope.SolutionInfo.SolutionChecksum;
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet);
var recoveredSolution = await validator.GetSolutionAsync(scope);
// option should be exactly same
Assert.Equal(0, recoveredSolution.Options.GetChangedOptions(workspace.Options).Count());
verifyOptionValues(workspace.Options);
verifyOptionValues(recoveredSolution.Options);
// checksum for recovered solution should be the same.
using var recoveredScope = await validator.AssetStorage.StoreAssetsAsync(recoveredSolution, CancellationToken.None).ConfigureAwait(false);
var recoveredChecksum = recoveredScope.SolutionInfo.SolutionChecksum;
Assert.Equal(checksum, recoveredChecksum);
}
private static SolutionAsset CloneAsset(ISerializerService serializer, SolutionAsset asset)
{
using var stream = SerializableBytes.CreateWritableStream();
using var context = SolutionReplicationContext.Create();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(asset.Value, writer, context, CancellationToken.None);
}
stream.Position = 0;
using var reader = ObjectReader.TryGetReader(stream);
var recovered = serializer.Deserialize<object>(asset.Kind, reader, CancellationToken.None);
var assetFromStorage = new SolutionAsset(serializer.CreateChecksum(recovered, CancellationToken.None), recovered);
Assert.Equal(asset.Checksum, assetFromStorage.Checksum);
return assetFromStorage;
}
private static AnalyzerFileReference CreateShadowCopiedAnalyzerReference(TempRoot tempRoot)
{
// use 2 different files as shadow copied content
var original = typeof(AdhocWorkspace).Assembly.Location;
var shadow = tempRoot.CreateFile("shadow", "dll");
shadow.CopyContentFrom(typeof(object).Assembly.Location);
return new AnalyzerFileReference(original, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(original, shadow.Path)));
}
private class MissingAnalyzerLoader : AnalyzerAssemblyLoader
{
protected override Assembly LoadFromPathImpl(string fullPath)
=> throw new FileNotFoundException(fullPath);
}
private class MissingMetadataReference : PortableExecutableReference
{
public MissingMetadataReference()
: base(MetadataReferenceProperties.Assembly, "missing_reference", XmlDocumentationProvider.Default)
{
}
protected override DocumentationProvider CreateDocumentationProvider()
=> null;
protected override Metadata GetMetadataImpl()
=> throw new FileNotFoundException("can't find");
protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
=> this;
}
private class MockShadowCopyAnalyzerAssemblyLoader : IAnalyzerAssemblyLoader
{
private readonly ImmutableDictionary<string, string> _map;
public MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string> map)
=> _map = map;
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
=> Assembly.LoadFrom(_map[fullPath]);
}
private class NotSerializableEncoding : Encoding
{
private readonly Encoding _real = Encoding.UTF8;
public override string WebName => _real.WebName;
public override int GetByteCount(char[] chars, int index, int count) => _real.GetByteCount(chars, index, count);
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => GetBytes(chars, charIndex, charCount, bytes, byteIndex);
public override int GetCharCount(byte[] bytes, int index, int count) => GetCharCount(bytes, index, count);
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => GetChars(bytes, byteIndex, byteCount, chars, charIndex);
public override int GetMaxByteCount(int charCount) => GetMaxByteCount(charCount);
public override int GetMaxCharCount(int byteCount) => GetMaxCharCount(byteCount);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Remote.UnitTests
{
[CollectionDefinition(Name)]
public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture>
{
public const string Name = nameof(AssemblyLoadTestFixtureCollection);
private AssemblyLoadTestFixtureCollection() { }
}
[Collection(AssemblyLoadTestFixtureCollection.Name)]
[UseExportProvider]
public class SnapshotSerializationTests
{
private readonly AssemblyLoadTestFixture _testFixture;
public SnapshotSerializationTests(AssemblyLoadTestFixture testFixture)
{
_testFixture = testFixture;
}
private static Workspace CreateWorkspace(Type[] additionalParts = null)
=> new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).WithTestHostParts(TestHost.OutOfProcess).GetHostServices());
internal static Solution CreateFullSolution(Workspace workspace)
{
var solution = workspace.CurrentSolution;
var languages = ImmutableHashSet.Create(LanguageNames.CSharp, LanguageNames.VisualBasic);
var solutionOptions = solution.Workspace.Services.GetRequiredService<IOptionService>().GetSerializableOptionsSnapshot(languages);
solution = solution.WithOptions(solutionOptions);
var csCode = "class A { }";
var project1 = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var document1 = project1.AddDocument("Document1", SourceText.From(csCode));
var vbCode = "Class B\r\nEnd Class";
var project2 = document1.Project.Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic);
var document2 = project2.AddDocument("Document2", SourceText.From(vbCode));
solution = document2.Project.Solution.GetRequiredProject(project1.Id)
.AddProjectReference(new ProjectReference(project2.Id, ImmutableArray.Create("test")))
.AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddAnalyzerReference(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path1"), new TestAnalyzerAssemblyLoader()))
.AddAdditionalDocument("Additional", SourceText.From("hello"), ImmutableArray.Create("test"), @".\Add").Project.Solution;
return solution
.WithAnalyzerReferences(new[] { new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path2"), new TestAnalyzerAssemblyLoader()) })
.AddAnalyzerConfigDocuments(
ImmutableArray.Create(
DocumentInfo.Create(
DocumentId.CreateNewId(project1.Id),
".editorconfig",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From("root = true"), VersionStamp.Create())))));
}
[Fact]
public async Task CreateSolutionSnapshotId_Empty()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var checksum = scope.SolutionInfo.SolutionChecksum;
var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false);
var projectsSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(projectsSyncObject).ConfigureAwait(false);
Assert.Equal(0, solutionObject.Projects.Count);
}
[Fact]
public async Task CreateSolutionSnapshotId_Empty_Serialization()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Project()
{
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
var checksum = scope.SolutionInfo.SolutionChecksum;
var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet);
var projectSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(projectSyncObject).ConfigureAwait(false);
Assert.Equal(1, solutionObject.Projects.Count);
await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 0, 0, 0, 0, 0).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Project_Serialization()
{
using var workspace = CreateWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(project.Solution, snapshot.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId()
{
var code = "class A { }";
using var workspace = CreateWorkspace();
var document = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code));
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false);
var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false);
Assert.Equal(1, solutionObject.Projects.Count);
await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 1, 0, 0, 0, 0).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Serialization()
{
var code = "class A { }";
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution;
var document = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code));
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(document.Project.Solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var firstProjectChecksum = await solution.GetProject(solution.ProjectIds[0]).State.GetChecksumAsync(CancellationToken.None);
var secondProjectChecksum = await solution.GetProject(solution.ProjectIds[1]).State.GetChecksumAsync(CancellationToken.None);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false);
await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false);
Assert.Equal(2, solutionObject.Projects.Count);
var projects = validator.ToProjectObjects(solutionObject.Projects);
await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == firstProjectChecksum).First(), 1, 1, 1, 1, 1).ConfigureAwait(false);
await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == secondProjectChecksum).First(), 1, 0, 0, 0, 0).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full_Serialization()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full_Asset_Serialization()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum);
await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Full_Asset_Serialization_Desktop()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum);
await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false);
}
[Fact]
public async Task CreateSolutionSnapshotId_Duplicate()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
// this is just data, one can hold the id outside of using statement. but
// one can't get asset using checksum from the id.
SolutionStateChecksums solutionId1;
SolutionStateChecksums solutionId2;
var validator = new SerializationValidator(workspace.Services);
using (var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false))
{
solutionId1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
using (var scope2 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false))
{
solutionId2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
}
// once pinned snapshot scope is released, there is no way to get back to asset.
// catch Exception because it will throw 2 different exception based on release or debug (ExceptionUtilities.UnexpectedValue)
Assert.ThrowsAny<Exception>(() => validator.SolutionStateEqual(solutionId1, solutionId2));
}
[Fact]
public void MetadataReference_RoundTrip_Test()
{
using var workspace = CreateWorkspace();
var reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var serializer = workspace.Services.GetService<ISerializerService>();
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public async Task Workspace_RoundTrip_Test()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
// recover solution from given snapshot
var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false);
var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
// create new snapshot from recovered solution
using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false);
// verify asset created by recovered solution is good
var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false);
// verify snapshots created from original solution and recovered solution are same
validator.SolutionStateEqual(solutionObject1, solutionObject2);
// recover new solution from recovered solution
var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false);
// create new snapshot from round tripped solution
using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false);
// verify asset created by rount trip solution is good
var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false);
// verify snapshots created from original solution and round trip solution are same.
validator.SolutionStateEqual(solutionObject2, solutionObject3);
}
[Fact]
public async Task Workspace_RoundTrip_Test_Desktop()
{
using var workspace = CreateWorkspace();
var solution = CreateFullSolution(workspace);
var validator = new SerializationValidator(workspace.Services);
var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
// recover solution from given snapshot
var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false);
var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
// create new snapshot from recovered solution
using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false);
// verify asset created by recovered solution is good
var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false);
// verify snapshots created from original solution and recovered solution are same
validator.SolutionStateEqual(solutionObject1, solutionObject2);
scope1.Dispose();
// recover new solution from recovered solution
var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false);
// create new snapshot from round tripped solution
using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false);
// verify asset created by rount trip solution is good
var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false);
await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false);
// verify snapshots created from original solution and round trip solution are same.
validator.SolutionStateEqual(solutionObject2, solutionObject3);
}
[Fact]
public async Task OptionSet_Serialization()
{
using var workspace = CreateWorkspace()
.CurrentSolution.AddProject("Project1", "Project.dll", LanguageNames.CSharp)
.Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic)
.Solution.Workspace;
await VerifyOptionSetsAsync(workspace, _ => { }).ConfigureAwait(false);
}
[Fact]
public async Task OptionSet_Serialization_CustomValue()
{
using var workspace = CreateWorkspace();
var newQualifyFieldAccessValue = new CodeStyleOption2<bool>(false, NotificationOption2.Error);
var newQualifyMethodAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Warning);
var newVarWhenTypeIsApparentValue = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion);
var newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Silent);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp, newQualifyFieldAccessValue)
.WithChangedOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic, newQualifyMethodAccessValue)
.WithChangedOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, newVarWhenTypeIsApparentValue)
.WithChangedOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic, newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue)));
var validator = new SerializationValidator(workspace.Services);
await VerifyOptionSetsAsync(workspace, VerifyOptions).ConfigureAwait(false);
void VerifyOptions(OptionSet options)
{
var actualQualifyFieldAccessValue = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp);
Assert.Equal(newQualifyFieldAccessValue, actualQualifyFieldAccessValue);
var actualQualifyMethodAccessValue = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic);
Assert.Equal(newQualifyMethodAccessValue, actualQualifyMethodAccessValue);
var actualVarWhenTypeIsApparentValue = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent);
Assert.Equal(newVarWhenTypeIsApparentValue, actualVarWhenTypeIsApparentValue);
var actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = options.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic);
Assert.Equal(newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue, actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue);
}
}
[Fact]
public void Missing_Metadata_Serialization_Test()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
var reference = new MissingMetadataReference();
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void Missing_Analyzer_Serialization_Test()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader());
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void Missing_Analyzer_Serialization_Desktop_Test()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader());
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void RoundTrip_Analyzer_Serialization_Test()
{
using var tempRoot = new TempRoot();
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
// actually shadow copy content
var location = typeof(object).Assembly.Location;
var file = tempRoot.CreateFile("shadow", "dll");
file.CopyContentFrom(location);
var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path)));
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void RoundTrip_Analyzer_Serialization_Desktop_Test()
{
using var tempRoot = new TempRoot();
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
// actually shadow copy content
var location = typeof(object).Assembly.Location;
var file = tempRoot.CreateFile("shadow", "dll");
file.CopyContentFrom(location);
var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path)));
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
var assetFromStorage = CloneAsset(serializer, assetFromFile);
_ = CloneAsset(serializer, assetFromStorage);
}
[Fact]
public void ShadowCopied_Analyzer_Serialization_Desktop_Test()
{
using var tempRoot = new TempRoot();
using var workspace = CreateWorkspace();
var reference = CreateShadowCopiedAnalyzerReference(tempRoot);
var serializer = workspace.Services.GetService<ISerializerService>();
// make sure this doesn't throw
var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference);
// this will verify serialized analyzer reference return same checksum as the original one
_ = CloneAsset(serializer, assetFromFile);
}
[Fact]
[WorkItem(1107294, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107294")]
public async Task SnapshotWithIdenticalAnalyzerFiles()
{
using var workspace = CreateWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
using var temp = new TempRoot();
var dir = temp.CreateDirectory();
// create two analyzer assembly files whose content is identical but path is different:
var file1 = dir.CreateFile("analyzer1.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path);
var file2 = dir.CreateFile("analyzer2.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path);
var analyzer1 = new AnalyzerFileReference(file1.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);
var analyzer2 = new AnalyzerFileReference(file2.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented);
project = project.AddAnalyzerReferences(new[] { analyzer1, analyzer2 });
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false);
AssertEx.Equal(new[] { file1.Path, file2.Path }, recovered.GetProject(project.Id).AnalyzerReferences.Select(r => r.FullPath));
}
[Fact]
public async Task SnapshotWithMissingReferencesTest()
{
using var workspace = CreateWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var metadata = new MissingMetadataReference();
var analyzer = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader());
project = project.AddMetadataReference(metadata);
project = project.AddAnalyzerReference(analyzer);
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
// this shouldn't throw
var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false);
}
[Fact]
public async Task UnknownLanguageTest()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName);
var validator = new SerializationValidator(workspace.Services);
using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);
// this shouldn't throw
var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false);
}
[Fact, WorkItem(44791, "https://github.com/dotnet/roslyn/issues/44791")]
public async Task UnknownLanguageOptionsTest()
{
using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) });
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName)
.Solution.AddProject("Project2", "Project2.dll", LanguageNames.CSharp);
workspace.TryApplyChanges(project.Solution);
await VerifyOptionSetsAsync(workspace, verifyOptionValues: _ => { });
}
[Fact]
public async Task EmptyAssetChecksumTest()
{
var document = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.CSharp).AddDocument("empty", SourceText.From(""));
var serializer = document.Project.Solution.Workspace.Services.GetService<ISerializerService>();
var source = serializer.CreateChecksum(await document.GetTextAsync().ConfigureAwait(false), CancellationToken.None);
var metadata = serializer.CreateChecksum(new MissingMetadataReference(), CancellationToken.None);
var analyzer = serializer.CreateChecksum(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing"), new MissingAnalyzerLoader()), CancellationToken.None);
Assert.NotEqual(source, metadata);
Assert.NotEqual(source, analyzer);
Assert.NotEqual(metadata, analyzer);
}
[Fact]
public async Task VBParseOptionsInCompilationOptions()
{
var project = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.VisualBasic);
project = project.WithCompilationOptions(
((VisualBasic.VisualBasicCompilationOptions)project.CompilationOptions).WithParseOptions((VisualBasic.VisualBasicParseOptions)project.ParseOptions));
var checksum = await project.State.GetChecksumAsync(CancellationToken.None).ConfigureAwait(false);
Assert.NotNull(checksum);
}
[Fact]
public async Task TestMetadataXmlDocComment()
{
using var tempRoot = new TempRoot();
// get original assembly location
var mscorlibLocation = typeof(object).Assembly.Location;
// set up dll and xml doc content
var tempDir = tempRoot.CreateDirectory();
var tempCorlib = tempDir.CopyFile(mscorlibLocation);
var tempCorlibXml = tempDir.CreateFile(Path.ChangeExtension(tempCorlib.Path, "xml"));
tempCorlibXml.WriteAllText(@"<?xml version=""1.0"" encoding=""utf-8""?>
<doc>
<assembly>
<name>mscorlib</name>
</assembly>
<members>
<member name=""T:System.Object"">
<summary>Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.To browse the .NET Framework source code for this type, see the Reference Source.</summary>
</member>
</members>
</doc>");
using var workspace = CreateWorkspace();
var solution = workspace.CurrentSolution
.AddProject("Project", "Project.dll", LanguageNames.CSharp)
.AddMetadataReference(MetadataReference.CreateFromFile(tempCorlib.Path))
.Solution;
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None);
// recover solution from given snapshot
var recovered = await validator.GetSolutionAsync(scope);
var compilation = await recovered.Projects.First().GetCompilationAsync(CancellationToken.None);
var objectType = compilation.GetTypeByMetadataName("System.Object");
var xmlDocComment = objectType.GetDocumentationCommentXml();
Assert.False(string.IsNullOrEmpty(xmlDocComment));
}
[Fact]
public void TestEncodingSerialization()
{
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
// test with right serializable encoding
var sourceText = SourceText.From("Hello", Encoding.UTF8);
using (var stream = SerializableBytes.CreateWritableStream())
{
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
using var objectReader = ObjectReader.TryGetReader(stream);
var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
Assert.Equal(sourceText.ToString(), newText.ToString());
}
// test with wrong encoding that doesn't support serialization
sourceText = SourceText.From("Hello", new NotSerializableEncoding());
using (var stream = SerializableBytes.CreateWritableStream())
{
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
using var objectReader = ObjectReader.TryGetReader(stream);
var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
Assert.Equal(sourceText.ToString(), newText.ToString());
}
}
[Fact]
public void TestCompilationOptions_NullableAndImport()
{
var csharpOptions = CSharp.CSharpCompilation.Create("dummy").Options.WithNullableContextOptions(NullableContextOptions.Warnings).WithMetadataImportOptions(MetadataImportOptions.All);
var vbOptions = VisualBasic.VisualBasicCompilation.Create("dummy").Options.WithMetadataImportOptions(MetadataImportOptions.Internal);
using var workspace = CreateWorkspace();
var serializer = workspace.Services.GetService<ISerializerService>();
VerifyOptions(csharpOptions);
VerifyOptions(vbOptions);
void VerifyOptions(CompilationOptions originalOptions)
{
using var stream = SerializableBytes.CreateWritableStream();
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(originalOptions, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
using var objectReader = ObjectReader.TryGetReader(stream);
var recoveredOptions = serializer.Deserialize<CompilationOptions>(originalOptions.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
var original = serializer.CreateChecksum(originalOptions, CancellationToken.None);
var recovered = serializer.CreateChecksum(recoveredOptions, CancellationToken.None);
Assert.Equal(original, recovered);
}
}
private static async Task VerifyOptionSetsAsync(Workspace workspace, Action<OptionSet> verifyOptionValues)
{
var solution = workspace.CurrentSolution;
verifyOptionValues(workspace.Options);
verifyOptionValues(solution.Options);
var validator = new SerializationValidator(workspace.Services);
using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false);
var checksum = scope.SolutionInfo.SolutionChecksum;
var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false);
await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes);
await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet);
var recoveredSolution = await validator.GetSolutionAsync(scope);
// option should be exactly same
Assert.Equal(0, recoveredSolution.Options.GetChangedOptions(workspace.Options).Count());
verifyOptionValues(workspace.Options);
verifyOptionValues(recoveredSolution.Options);
// checksum for recovered solution should be the same.
using var recoveredScope = await validator.AssetStorage.StoreAssetsAsync(recoveredSolution, CancellationToken.None).ConfigureAwait(false);
var recoveredChecksum = recoveredScope.SolutionInfo.SolutionChecksum;
Assert.Equal(checksum, recoveredChecksum);
}
private static SolutionAsset CloneAsset(ISerializerService serializer, SolutionAsset asset)
{
using var stream = SerializableBytes.CreateWritableStream();
using var context = SolutionReplicationContext.Create();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(asset.Value, writer, context, CancellationToken.None);
}
stream.Position = 0;
using var reader = ObjectReader.TryGetReader(stream);
var recovered = serializer.Deserialize<object>(asset.Kind, reader, CancellationToken.None);
var assetFromStorage = new SolutionAsset(serializer.CreateChecksum(recovered, CancellationToken.None), recovered);
Assert.Equal(asset.Checksum, assetFromStorage.Checksum);
return assetFromStorage;
}
private static AnalyzerFileReference CreateShadowCopiedAnalyzerReference(TempRoot tempRoot)
{
// use 2 different files as shadow copied content
var original = typeof(AdhocWorkspace).Assembly.Location;
var shadow = tempRoot.CreateFile("shadow", "dll");
shadow.CopyContentFrom(typeof(object).Assembly.Location);
return new AnalyzerFileReference(original, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(original, shadow.Path)));
}
private class MissingAnalyzerLoader : AnalyzerAssemblyLoader
{
protected override Assembly LoadFromPathImpl(string fullPath)
=> throw new FileNotFoundException(fullPath);
}
private class MissingMetadataReference : PortableExecutableReference
{
public MissingMetadataReference()
: base(MetadataReferenceProperties.Assembly, "missing_reference", XmlDocumentationProvider.Default)
{
}
protected override DocumentationProvider CreateDocumentationProvider()
=> null;
protected override Metadata GetMetadataImpl()
=> throw new FileNotFoundException("can't find");
protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties)
=> this;
}
private class MockShadowCopyAnalyzerAssemblyLoader : IAnalyzerAssemblyLoader
{
private readonly ImmutableDictionary<string, string> _map;
public MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string> map)
=> _map = map;
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
=> Assembly.LoadFrom(_map[fullPath]);
}
private class NotSerializableEncoding : Encoding
{
private readonly Encoding _real = Encoding.UTF8;
public override string WebName => _real.WebName;
public override int GetByteCount(char[] chars, int index, int count) => _real.GetByteCount(chars, index, count);
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => GetBytes(chars, charIndex, charCount, bytes, byteIndex);
public override int GetCharCount(byte[] bytes, int index, int count) => GetCharCount(bytes, index, count);
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => GetChars(bytes, byteIndex, byteCount, chars, charIndex);
public override int GetMaxByteCount(int charCount) => GetMaxByteCount(charCount);
public override int GetMaxCharCount(int byteCount) => GetMaxCharCount(byteCount);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/VisualBasicTest/Structure/EventDeclarationStructureTests.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 EventDeclarationStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EventStatementSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New EventDeclarationStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestEvent() As Task
Const code = "
Class C1
Event $$AnEvent(ByVal EventNumber As Integer)
End Class
"
Await VerifyNoBlockSpansAsync(code)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestEventWithComments() As Task
Const code = "
Class C1
{|span:'My
'Event|}
Event $$AnEvent(ByVal EventNumber As Integer)
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "' My ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestCustomEvent() As Task
Const code = "
Class C1
{|span:Custom Event $$eventName As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Custom Event eventName As EventHandler ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestPrivateCustomEvent() As Task
Const code = "
Class C1
{|span:Private Custom Event $$eventName As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Private Custom Event eventName As EventHandler ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestCustomEventWithComments() As Task
Const code = "
Class C1
{|span1:'My
'Event|}
{|span2:Custom Event $$eventName As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span1", "' My ...", autoCollapse:=True),
Region("span2", "Custom Event eventName As EventHandler ...", autoCollapse:=True))
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class EventDeclarationStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EventStatementSyntax)
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New EventDeclarationStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestEvent() As Task
Const code = "
Class C1
Event $$AnEvent(ByVal EventNumber As Integer)
End Class
"
Await VerifyNoBlockSpansAsync(code)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestEventWithComments() As Task
Const code = "
Class C1
{|span:'My
'Event|}
Event $$AnEvent(ByVal EventNumber As Integer)
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "' My ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestCustomEvent() As Task
Const code = "
Class C1
{|span:Custom Event $$eventName As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Custom Event eventName As EventHandler ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestPrivateCustomEvent() As Task
Const code = "
Class C1
{|span:Private Custom Event $$eventName As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span", "Private Custom Event eventName As EventHandler ...", autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestCustomEventWithComments() As Task
Const code = "
Class C1
{|span1:'My
'Event|}
{|span2:Custom Event $$eventName As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("span1", "' My ...", autoCollapse:=True),
Region("span2", "Custom Event eventName As EventHandler ...", autoCollapse:=True))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/Core/Def/EditorConfigSettings/SettingsEditorFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.Internal.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.TextManager.Interop;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings
{
[Export(typeof(SettingsEditorFactory))]
[Guid(SettingsEditorFactoryGuidString)]
internal sealed class SettingsEditorFactory : IVsEditorFactory, IDisposable
{
public static readonly Guid SettingsEditorFactoryGuid = new(SettingsEditorFactoryGuidString);
public const string SettingsEditorFactoryGuidString = "68b46364-d378-42f2-9e72-37d86c5f4468";
public const string Extension = ".editorconfig";
private readonly ISettingsAggregator _settingsDataProviderFactory;
private readonly VisualStudioWorkspace _workspace;
private readonly IWpfTableControlProvider _controlProvider;
private readonly ITableManagerProvider _tableMangerProvider;
private readonly IVsEditorAdaptersFactoryService _vsEditorAdaptersFactoryService;
private readonly IThreadingContext _threadingContext;
private ServiceProvider? _vsServiceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SettingsEditorFactory(VisualStudioWorkspace workspace,
IWpfTableControlProvider controlProvider,
ITableManagerProvider tableMangerProvider,
IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService,
IThreadingContext threadingContext)
{
_settingsDataProviderFactory = workspace.Services.GetRequiredService<ISettingsAggregator>();
_workspace = workspace;
_controlProvider = controlProvider;
_tableMangerProvider = tableMangerProvider;
_vsEditorAdaptersFactoryService = vsEditorAdaptersFactoryService;
_threadingContext = threadingContext;
}
public void Dispose()
{
if (_vsServiceProvider is not null)
{
_vsServiceProvider.Dispose();
_vsServiceProvider = null;
}
}
public int CreateEditorInstance(uint grfCreateDoc,
string pszMkDocument,
string pszPhysicalView,
IVsHierarchy pvHier,
uint itemid,
IntPtr punkDocDataExisting,
out IntPtr ppunkDocView,
out IntPtr ppunkDocData,
out string? pbstrEditorCaption,
out Guid pguidCmdUI,
out int pgrfCDW)
{
// Initialize to null
ppunkDocView = IntPtr.Zero;
ppunkDocData = IntPtr.Zero;
pguidCmdUI = SettingsEditorFactoryGuid;
pgrfCDW = 0;
pbstrEditorCaption = null;
if (!_workspace.CurrentSolution.Projects.Any(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic))
{
// If there are no VB or C# projects loaded in the solution (so an editorconfig file in a C++ project) then we want their
// editorfactory to present the file instead of use showing ours
return VSConstants.VS_E_UNSUPPORTEDFORMAT;
}
// Validate inputs
if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
{
return VSConstants.E_INVALIDARG;
}
IVsTextLines? textBuffer = null;
if (punkDocDataExisting == IntPtr.Zero)
{
Assumes.NotNull(_vsServiceProvider);
if (_vsServiceProvider.TryGetService<SLocalRegistry, ILocalRegistry>(out var localRegistry))
{
var textLinesGuid = typeof(IVsTextLines).GUID;
_ = localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref textLinesGuid, 1 /*CLSCTX_INPROC_SERVER*/, out var ptr);
try
{
textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines;
}
finally
{
_ = Marshal.Release(ptr); // Release RefCount from CreateInstance call
}
if (textBuffer is IObjectWithSite objectWithSite)
{
var oleServiceProvider = _vsServiceProvider.GetService<IOleServiceProvider>();
objectWithSite.SetSite(oleServiceProvider);
}
}
}
else
{
textBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines;
if (textBuffer == null)
{
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
}
if (textBuffer is null)
{
throw new InvalidOperationException("unable to acquire text buffer");
}
// Create the editor
var newEditor = new SettingsEditorPane(_vsEditorAdaptersFactoryService,
_threadingContext,
_settingsDataProviderFactory,
_controlProvider,
_tableMangerProvider,
pszMkDocument,
textBuffer,
_workspace);
ppunkDocView = Marshal.GetIUnknownForObject(newEditor);
ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);
pbstrEditorCaption = "";
return VSConstants.S_OK;
}
public int SetSite(IOleServiceProvider psp)
{
_vsServiceProvider = new ServiceProvider(psp);
return VSConstants.S_OK;
}
public int Close() => VSConstants.S_OK;
public int MapLogicalView(ref Guid rguidLogicalView, out string? pbstrPhysicalView)
{
pbstrPhysicalView = null; // initialize out parameter
// we support only a single physical view
if (VSConstants.LOGVIEWID_Primary == rguidLogicalView)
{
return VSConstants.S_OK; // primary view uses NULL as pbstrPhysicalView
}
else
{
return VSConstants.E_NOTIMPL; // you must return E_NOTIMPL for any unrecognized rguidLogicalView values
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.Internal.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.TextManager.Interop;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings
{
[Export(typeof(SettingsEditorFactory))]
[Guid(SettingsEditorFactoryGuidString)]
internal sealed class SettingsEditorFactory : IVsEditorFactory, IDisposable
{
public static readonly Guid SettingsEditorFactoryGuid = new(SettingsEditorFactoryGuidString);
public const string SettingsEditorFactoryGuidString = "68b46364-d378-42f2-9e72-37d86c5f4468";
public const string Extension = ".editorconfig";
private readonly ISettingsAggregator _settingsDataProviderFactory;
private readonly VisualStudioWorkspace _workspace;
private readonly IWpfTableControlProvider _controlProvider;
private readonly ITableManagerProvider _tableMangerProvider;
private readonly IVsEditorAdaptersFactoryService _vsEditorAdaptersFactoryService;
private readonly IThreadingContext _threadingContext;
private ServiceProvider? _vsServiceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SettingsEditorFactory(VisualStudioWorkspace workspace,
IWpfTableControlProvider controlProvider,
ITableManagerProvider tableMangerProvider,
IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService,
IThreadingContext threadingContext)
{
_settingsDataProviderFactory = workspace.Services.GetRequiredService<ISettingsAggregator>();
_workspace = workspace;
_controlProvider = controlProvider;
_tableMangerProvider = tableMangerProvider;
_vsEditorAdaptersFactoryService = vsEditorAdaptersFactoryService;
_threadingContext = threadingContext;
}
public void Dispose()
{
if (_vsServiceProvider is not null)
{
_vsServiceProvider.Dispose();
_vsServiceProvider = null;
}
}
public int CreateEditorInstance(uint grfCreateDoc,
string pszMkDocument,
string pszPhysicalView,
IVsHierarchy pvHier,
uint itemid,
IntPtr punkDocDataExisting,
out IntPtr ppunkDocView,
out IntPtr ppunkDocData,
out string? pbstrEditorCaption,
out Guid pguidCmdUI,
out int pgrfCDW)
{
// Initialize to null
ppunkDocView = IntPtr.Zero;
ppunkDocData = IntPtr.Zero;
pguidCmdUI = SettingsEditorFactoryGuid;
pgrfCDW = 0;
pbstrEditorCaption = null;
if (!_workspace.CurrentSolution.Projects.Any(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic))
{
// If there are no VB or C# projects loaded in the solution (so an editorconfig file in a C++ project) then we want their
// editorfactory to present the file instead of use showing ours
return VSConstants.VS_E_UNSUPPORTEDFORMAT;
}
// Validate inputs
if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
{
return VSConstants.E_INVALIDARG;
}
IVsTextLines? textBuffer = null;
if (punkDocDataExisting == IntPtr.Zero)
{
Assumes.NotNull(_vsServiceProvider);
if (_vsServiceProvider.TryGetService<SLocalRegistry, ILocalRegistry>(out var localRegistry))
{
var textLinesGuid = typeof(IVsTextLines).GUID;
_ = localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref textLinesGuid, 1 /*CLSCTX_INPROC_SERVER*/, out var ptr);
try
{
textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines;
}
finally
{
_ = Marshal.Release(ptr); // Release RefCount from CreateInstance call
}
if (textBuffer is IObjectWithSite objectWithSite)
{
var oleServiceProvider = _vsServiceProvider.GetService<IOleServiceProvider>();
objectWithSite.SetSite(oleServiceProvider);
}
}
}
else
{
textBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines;
if (textBuffer == null)
{
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
}
if (textBuffer is null)
{
throw new InvalidOperationException("unable to acquire text buffer");
}
// Create the editor
var newEditor = new SettingsEditorPane(_vsEditorAdaptersFactoryService,
_threadingContext,
_settingsDataProviderFactory,
_controlProvider,
_tableMangerProvider,
pszMkDocument,
textBuffer,
_workspace);
ppunkDocView = Marshal.GetIUnknownForObject(newEditor);
ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);
pbstrEditorCaption = "";
return VSConstants.S_OK;
}
public int SetSite(IOleServiceProvider psp)
{
_vsServiceProvider = new ServiceProvider(psp);
return VSConstants.S_OK;
}
public int Close() => VSConstants.S_OK;
public int MapLogicalView(ref Guid rguidLogicalView, out string? pbstrPhysicalView)
{
pbstrPhysicalView = null; // initialize out parameter
// we support only a single physical view
if (VSConstants.LOGVIEWID_Primary == rguidLogicalView)
{
return VSConstants.S_OK; // primary view uses NULL as pbstrPhysicalView
}
else
{
return VSConstants.E_NOTIMPL; // you must return E_NOTIMPL for any unrecognized rguidLogicalView values
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/CSharp/Portable/Classification/Worker_DocumentationComments.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Classification
{
internal partial class Worker
{
private void ClassifyDocumentationComment(DocumentationCommentTriviaSyntax documentationComment)
{
if (!_textSpan.OverlapsWith(documentationComment.Span))
{
return;
}
foreach (var xmlNode in documentationComment.Content)
{
var childFullSpan = xmlNode.FullSpan;
if (childFullSpan.Start > _textSpan.End)
{
return;
}
else if (childFullSpan.End < _textSpan.Start)
{
continue;
}
ClassifyXmlNode(xmlNode);
}
// NOTE: the "EndOfComment" token is a special, zero width token. However, if it's a multi-line xml doc comment
// the final '*/" will be leading exterior trivia on it.
ClassifyXmlTrivia(documentationComment.EndOfComment.LeadingTrivia);
}
private void ClassifyXmlNode(XmlNodeSyntax node)
{
switch (node.Kind())
{
case SyntaxKind.XmlElement:
ClassifyXmlElement((XmlElementSyntax)node);
break;
case SyntaxKind.XmlEmptyElement:
ClassifyXmlEmptyElement((XmlEmptyElementSyntax)node);
break;
case SyntaxKind.XmlText:
ClassifyXmlText((XmlTextSyntax)node);
break;
case SyntaxKind.XmlComment:
ClassifyXmlComment((XmlCommentSyntax)node);
break;
case SyntaxKind.XmlCDataSection:
ClassifyXmlCDataSection((XmlCDataSectionSyntax)node);
break;
case SyntaxKind.XmlProcessingInstruction:
ClassifyXmlProcessingInstruction((XmlProcessingInstructionSyntax)node);
break;
}
}
private void ClassifyXmlTrivia(SyntaxTriviaList triviaList)
{
foreach (var t in triviaList)
{
switch (t.Kind())
{
case SyntaxKind.DocumentationCommentExteriorTrivia:
ClassifyExteriorTrivia(t);
break;
case SyntaxKind.SkippedTokensTrivia:
AddClassification(t, ClassificationTypeNames.XmlDocCommentText);
break;
}
}
}
private void ClassifyExteriorTrivia(SyntaxTrivia trivia)
{
// Note: The exterior trivia can contain whitespace (usually leading) and we want to avoid classifying it.
// However, meaningful exterior trivia can also have an undetermined length in the case of
// multiline doc comments.
// For example:
//
// /**<summary>
// ********* Goo
// ******* </summary>*/
// PERFORMANCE:
// While the call to SyntaxTrivia.ToString() looks like an allocation, it isn't.
// The SyntaxTrivia green node holds the string text of the trivia in a field and ToString()
// just returns a reference to that.
var text = trivia.ToString();
int? spanStart = null;
for (var index = 0; index < text.Length; index++)
{
var ch = text[index];
if (spanStart != null && char.IsWhiteSpace(ch))
{
var span = TextSpan.FromBounds(spanStart.Value, spanStart.Value + index);
AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter);
spanStart = null;
}
else if (spanStart == null && !char.IsWhiteSpace(ch))
{
spanStart = trivia.Span.Start + index;
}
}
// Add a final classification if we hadn't encountered anymore whitespace at the end.
if (spanStart != null)
{
var span = TextSpan.FromBounds(spanStart.Value, trivia.Span.End);
AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter);
}
}
private void AddXmlClassification(SyntaxToken token, string classificationType)
{
if (token.HasLeadingTrivia)
ClassifyXmlTrivia(token.LeadingTrivia);
AddClassification(token, classificationType);
if (token.HasTrailingTrivia)
ClassifyXmlTrivia(token.TrailingTrivia);
}
private void ClassifyXmlTextTokens(SyntaxTokenList textTokens)
{
foreach (var token in textTokens)
{
if (token.HasLeadingTrivia)
ClassifyXmlTrivia(token.LeadingTrivia);
ClassifyXmlTextToken(token);
if (token.HasTrailingTrivia)
ClassifyXmlTrivia(token.TrailingTrivia);
}
}
private void ClassifyXmlTextToken(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.XmlEntityLiteralToken)
{
AddClassification(token, ClassificationTypeNames.XmlDocCommentEntityReference);
}
else if (token.Kind() != SyntaxKind.XmlTextLiteralNewLineToken)
{
RoslynDebug.Assert(token.Parent is object);
switch (token.Parent.Kind())
{
case SyntaxKind.XmlText:
AddClassification(token, ClassificationTypeNames.XmlDocCommentText);
break;
case SyntaxKind.XmlTextAttribute:
AddClassification(token, ClassificationTypeNames.XmlDocCommentAttributeValue);
break;
case SyntaxKind.XmlComment:
AddClassification(token, ClassificationTypeNames.XmlDocCommentComment);
break;
case SyntaxKind.XmlCDataSection:
AddClassification(token, ClassificationTypeNames.XmlDocCommentCDataSection);
break;
case SyntaxKind.XmlProcessingInstruction:
AddClassification(token, ClassificationTypeNames.XmlDocCommentProcessingInstruction);
break;
}
}
}
private void ClassifyXmlName(XmlNameSyntax node)
{
var classificationType = node.Parent switch
{
XmlAttributeSyntax => ClassificationTypeNames.XmlDocCommentAttributeName,
XmlProcessingInstructionSyntax => ClassificationTypeNames.XmlDocCommentProcessingInstruction,
_ => ClassificationTypeNames.XmlDocCommentName,
};
var prefix = node.Prefix;
if (prefix != null)
{
AddXmlClassification(prefix.Prefix, classificationType);
AddXmlClassification(prefix.ColonToken, classificationType);
}
AddXmlClassification(node.LocalName, classificationType);
}
private void ClassifyXmlElement(XmlElementSyntax node)
{
ClassifyXmlElementStartTag(node.StartTag);
foreach (var xmlNode in node.Content)
{
ClassifyXmlNode(xmlNode);
}
ClassifyXmlElementEndTag(node.EndTag);
}
private void ClassifyXmlElementStartTag(XmlElementStartTagSyntax node)
{
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlName(node.Name);
foreach (var attribute in node.Attributes)
{
ClassifyXmlAttribute(attribute);
}
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlElementEndTag(XmlElementEndTagSyntax node)
{
AddXmlClassification(node.LessThanSlashToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlName(node.Name);
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlEmptyElement(XmlEmptyElementSyntax node)
{
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlName(node.Name);
foreach (var attribute in node.Attributes)
{
ClassifyXmlAttribute(attribute);
}
AddXmlClassification(node.SlashGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlAttribute(XmlAttributeSyntax attribute)
{
ClassifyXmlName(attribute.Name);
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter);
AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes);
switch (attribute.Kind())
{
case SyntaxKind.XmlTextAttribute:
ClassifyXmlTextTokens(((XmlTextAttributeSyntax)attribute).TextTokens);
break;
case SyntaxKind.XmlCrefAttribute:
ClassifyNode(((XmlCrefAttributeSyntax)attribute).Cref);
break;
case SyntaxKind.XmlNameAttribute:
ClassifyNode(((XmlNameAttributeSyntax)attribute).Identifier);
break;
}
AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes);
}
private void ClassifyXmlText(XmlTextSyntax node)
=> ClassifyXmlTextTokens(node.TextTokens);
private void ClassifyXmlComment(XmlCommentSyntax node)
{
AddXmlClassification(node.LessThanExclamationMinusMinusToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlTextTokens(node.TextTokens);
AddXmlClassification(node.MinusMinusGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlCDataSection(XmlCDataSectionSyntax node)
{
AddXmlClassification(node.StartCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlTextTokens(node.TextTokens);
AddXmlClassification(node.EndCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlProcessingInstruction(XmlProcessingInstructionSyntax node)
{
AddXmlClassification(node.StartProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction);
ClassifyXmlName(node.Name);
ClassifyXmlTextTokens(node.TextTokens);
AddXmlClassification(node.EndProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Classification
{
internal partial class Worker
{
private void ClassifyDocumentationComment(DocumentationCommentTriviaSyntax documentationComment)
{
if (!_textSpan.OverlapsWith(documentationComment.Span))
{
return;
}
foreach (var xmlNode in documentationComment.Content)
{
var childFullSpan = xmlNode.FullSpan;
if (childFullSpan.Start > _textSpan.End)
{
return;
}
else if (childFullSpan.End < _textSpan.Start)
{
continue;
}
ClassifyXmlNode(xmlNode);
}
// NOTE: the "EndOfComment" token is a special, zero width token. However, if it's a multi-line xml doc comment
// the final '*/" will be leading exterior trivia on it.
ClassifyXmlTrivia(documentationComment.EndOfComment.LeadingTrivia);
}
private void ClassifyXmlNode(XmlNodeSyntax node)
{
switch (node.Kind())
{
case SyntaxKind.XmlElement:
ClassifyXmlElement((XmlElementSyntax)node);
break;
case SyntaxKind.XmlEmptyElement:
ClassifyXmlEmptyElement((XmlEmptyElementSyntax)node);
break;
case SyntaxKind.XmlText:
ClassifyXmlText((XmlTextSyntax)node);
break;
case SyntaxKind.XmlComment:
ClassifyXmlComment((XmlCommentSyntax)node);
break;
case SyntaxKind.XmlCDataSection:
ClassifyXmlCDataSection((XmlCDataSectionSyntax)node);
break;
case SyntaxKind.XmlProcessingInstruction:
ClassifyXmlProcessingInstruction((XmlProcessingInstructionSyntax)node);
break;
}
}
private void ClassifyXmlTrivia(SyntaxTriviaList triviaList)
{
foreach (var t in triviaList)
{
switch (t.Kind())
{
case SyntaxKind.DocumentationCommentExteriorTrivia:
ClassifyExteriorTrivia(t);
break;
case SyntaxKind.SkippedTokensTrivia:
AddClassification(t, ClassificationTypeNames.XmlDocCommentText);
break;
}
}
}
private void ClassifyExteriorTrivia(SyntaxTrivia trivia)
{
// Note: The exterior trivia can contain whitespace (usually leading) and we want to avoid classifying it.
// However, meaningful exterior trivia can also have an undetermined length in the case of
// multiline doc comments.
// For example:
//
// /**<summary>
// ********* Goo
// ******* </summary>*/
// PERFORMANCE:
// While the call to SyntaxTrivia.ToString() looks like an allocation, it isn't.
// The SyntaxTrivia green node holds the string text of the trivia in a field and ToString()
// just returns a reference to that.
var text = trivia.ToString();
int? spanStart = null;
for (var index = 0; index < text.Length; index++)
{
var ch = text[index];
if (spanStart != null && char.IsWhiteSpace(ch))
{
var span = TextSpan.FromBounds(spanStart.Value, spanStart.Value + index);
AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter);
spanStart = null;
}
else if (spanStart == null && !char.IsWhiteSpace(ch))
{
spanStart = trivia.Span.Start + index;
}
}
// Add a final classification if we hadn't encountered anymore whitespace at the end.
if (spanStart != null)
{
var span = TextSpan.FromBounds(spanStart.Value, trivia.Span.End);
AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter);
}
}
private void AddXmlClassification(SyntaxToken token, string classificationType)
{
if (token.HasLeadingTrivia)
ClassifyXmlTrivia(token.LeadingTrivia);
AddClassification(token, classificationType);
if (token.HasTrailingTrivia)
ClassifyXmlTrivia(token.TrailingTrivia);
}
private void ClassifyXmlTextTokens(SyntaxTokenList textTokens)
{
foreach (var token in textTokens)
{
if (token.HasLeadingTrivia)
ClassifyXmlTrivia(token.LeadingTrivia);
ClassifyXmlTextToken(token);
if (token.HasTrailingTrivia)
ClassifyXmlTrivia(token.TrailingTrivia);
}
}
private void ClassifyXmlTextToken(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.XmlEntityLiteralToken)
{
AddClassification(token, ClassificationTypeNames.XmlDocCommentEntityReference);
}
else if (token.Kind() != SyntaxKind.XmlTextLiteralNewLineToken)
{
RoslynDebug.Assert(token.Parent is object);
switch (token.Parent.Kind())
{
case SyntaxKind.XmlText:
AddClassification(token, ClassificationTypeNames.XmlDocCommentText);
break;
case SyntaxKind.XmlTextAttribute:
AddClassification(token, ClassificationTypeNames.XmlDocCommentAttributeValue);
break;
case SyntaxKind.XmlComment:
AddClassification(token, ClassificationTypeNames.XmlDocCommentComment);
break;
case SyntaxKind.XmlCDataSection:
AddClassification(token, ClassificationTypeNames.XmlDocCommentCDataSection);
break;
case SyntaxKind.XmlProcessingInstruction:
AddClassification(token, ClassificationTypeNames.XmlDocCommentProcessingInstruction);
break;
}
}
}
private void ClassifyXmlName(XmlNameSyntax node)
{
var classificationType = node.Parent switch
{
XmlAttributeSyntax => ClassificationTypeNames.XmlDocCommentAttributeName,
XmlProcessingInstructionSyntax => ClassificationTypeNames.XmlDocCommentProcessingInstruction,
_ => ClassificationTypeNames.XmlDocCommentName,
};
var prefix = node.Prefix;
if (prefix != null)
{
AddXmlClassification(prefix.Prefix, classificationType);
AddXmlClassification(prefix.ColonToken, classificationType);
}
AddXmlClassification(node.LocalName, classificationType);
}
private void ClassifyXmlElement(XmlElementSyntax node)
{
ClassifyXmlElementStartTag(node.StartTag);
foreach (var xmlNode in node.Content)
{
ClassifyXmlNode(xmlNode);
}
ClassifyXmlElementEndTag(node.EndTag);
}
private void ClassifyXmlElementStartTag(XmlElementStartTagSyntax node)
{
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlName(node.Name);
foreach (var attribute in node.Attributes)
{
ClassifyXmlAttribute(attribute);
}
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlElementEndTag(XmlElementEndTagSyntax node)
{
AddXmlClassification(node.LessThanSlashToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlName(node.Name);
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlEmptyElement(XmlEmptyElementSyntax node)
{
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlName(node.Name);
foreach (var attribute in node.Attributes)
{
ClassifyXmlAttribute(attribute);
}
AddXmlClassification(node.SlashGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlAttribute(XmlAttributeSyntax attribute)
{
ClassifyXmlName(attribute.Name);
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter);
AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes);
switch (attribute.Kind())
{
case SyntaxKind.XmlTextAttribute:
ClassifyXmlTextTokens(((XmlTextAttributeSyntax)attribute).TextTokens);
break;
case SyntaxKind.XmlCrefAttribute:
ClassifyNode(((XmlCrefAttributeSyntax)attribute).Cref);
break;
case SyntaxKind.XmlNameAttribute:
ClassifyNode(((XmlNameAttributeSyntax)attribute).Identifier);
break;
}
AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes);
}
private void ClassifyXmlText(XmlTextSyntax node)
=> ClassifyXmlTextTokens(node.TextTokens);
private void ClassifyXmlComment(XmlCommentSyntax node)
{
AddXmlClassification(node.LessThanExclamationMinusMinusToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlTextTokens(node.TextTokens);
AddXmlClassification(node.MinusMinusGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlCDataSection(XmlCDataSectionSyntax node)
{
AddXmlClassification(node.StartCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter);
ClassifyXmlTextTokens(node.TextTokens);
AddXmlClassification(node.EndCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter);
}
private void ClassifyXmlProcessingInstruction(XmlProcessingInstructionSyntax node)
{
AddXmlClassification(node.StartProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction);
ClassifyXmlName(node.Name);
ClassifyXmlTextTokens(node.TextTokens);
AddXmlClassification(node.EndProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Analyzers/Core/Analyzers/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.UseConditionalExpression
{
internal abstract class AbstractUseConditionalExpressionDiagnosticAnalyzer<
TIfStatementSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TIfStatementSyntax : SyntaxNode
{
private readonly PerLanguageOption2<CodeStyleOption2<bool>> _option;
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected AbstractUseConditionalExpressionDiagnosticAnalyzer(
string descriptorId,
EnforceOnBuild enforceOnBuild,
LocalizableResourceString message,
PerLanguageOption2<CodeStyleOption2<bool>> option)
: base(descriptorId,
enforceOnBuild,
option,
new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_conditional_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
message)
{
_option = option;
}
protected abstract ISyntaxFacts GetSyntaxFacts();
protected abstract bool TryMatchPattern(IConditionalOperation ifOperation, ISymbol containingSymbol);
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeOperation, OperationKind.Conditional);
private void AnalyzeOperation(OperationAnalysisContext context)
{
var ifOperation = (IConditionalOperation)context.Operation;
if (ifOperation.Syntax is not TIfStatementSyntax ifStatement)
{
return;
}
var language = ifStatement.Language;
var option = context.GetOption(_option, language);
if (!option.Value)
{
return;
}
if (!TryMatchPattern(ifOperation, context.ContainingSymbol))
{
return;
}
var additionalLocations = ImmutableArray.Create(ifStatement.GetLocation());
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
ifStatement.GetFirstToken().GetLocation(),
option.Notification.Severity,
additionalLocations,
properties: null));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.UseConditionalExpression
{
internal abstract class AbstractUseConditionalExpressionDiagnosticAnalyzer<
TIfStatementSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TIfStatementSyntax : SyntaxNode
{
private readonly PerLanguageOption2<CodeStyleOption2<bool>> _option;
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected AbstractUseConditionalExpressionDiagnosticAnalyzer(
string descriptorId,
EnforceOnBuild enforceOnBuild,
LocalizableResourceString message,
PerLanguageOption2<CodeStyleOption2<bool>> option)
: base(descriptorId,
enforceOnBuild,
option,
new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_conditional_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
message)
{
_option = option;
}
protected abstract ISyntaxFacts GetSyntaxFacts();
protected abstract bool TryMatchPattern(IConditionalOperation ifOperation, ISymbol containingSymbol);
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeOperation, OperationKind.Conditional);
private void AnalyzeOperation(OperationAnalysisContext context)
{
var ifOperation = (IConditionalOperation)context.Operation;
if (ifOperation.Syntax is not TIfStatementSyntax ifStatement)
{
return;
}
var language = ifStatement.Language;
var option = context.GetOption(_option, language);
if (!option.Value)
{
return;
}
if (!TryMatchPattern(ifOperation, context.ContainingSymbol))
{
return;
}
var additionalLocations = ImmutableArray.Create(ifStatement.GetLocation());
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
ifStatement.GetFirstToken().GetLocation(),
option.Notification.Severity,
additionalLocations,
properties: null));
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/Portable/Syntax/SyntaxReference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A reference to a syntax node.
/// </summary>
public abstract class SyntaxReference
{
/// <summary>
/// The syntax tree that this references a node within.
/// </summary>
public abstract SyntaxTree SyntaxTree { get; }
/// <summary>
/// The span of the node referenced.
/// </summary>
public abstract TextSpan Span { get; }
/// <summary>
/// Retrieves the original referenced syntax node.
/// This action may cause a parse to happen to recover the syntax node.
/// </summary>
/// <returns>The original referenced syntax node.</returns>
public abstract SyntaxNode GetSyntax(CancellationToken cancellationToken = default);
/// <summary>
/// Retrieves the original referenced syntax node.
/// This action may cause a parse to happen to recover the syntax node.
/// </summary>
/// <returns>The original referenced syntax node.</returns>
public virtual Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(this.GetSyntax(cancellationToken));
}
/// <summary>
/// The location of this syntax reference.
/// </summary>
/// <returns>The location of this syntax reference.</returns>
/// <remarks>
/// More performant than GetSyntax().GetLocation().
/// </remarks>
internal Location GetLocation()
{
return this.SyntaxTree.GetLocation(this.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.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A reference to a syntax node.
/// </summary>
public abstract class SyntaxReference
{
/// <summary>
/// The syntax tree that this references a node within.
/// </summary>
public abstract SyntaxTree SyntaxTree { get; }
/// <summary>
/// The span of the node referenced.
/// </summary>
public abstract TextSpan Span { get; }
/// <summary>
/// Retrieves the original referenced syntax node.
/// This action may cause a parse to happen to recover the syntax node.
/// </summary>
/// <returns>The original referenced syntax node.</returns>
public abstract SyntaxNode GetSyntax(CancellationToken cancellationToken = default);
/// <summary>
/// Retrieves the original referenced syntax node.
/// This action may cause a parse to happen to recover the syntax node.
/// </summary>
/// <returns>The original referenced syntax node.</returns>
public virtual Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(this.GetSyntax(cancellationToken));
}
/// <summary>
/// The location of this syntax reference.
/// </summary>
/// <returns>The location of this syntax reference.</returns>
/// <remarks>
/// More performant than GetSyntax().GetLocation().
/// </remarks>
internal Location GetLocation()
{
return this.SyntaxTree.GetLocation(this.Span);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FixedStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitFixedStatement(BoundFixedStatement node)
{
ImmutableArray<BoundLocalDeclaration> localDecls = node.Declarations.LocalDeclarations;
int numFixedLocals = localDecls.Length;
var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance(node.Locals.Length);
localBuilder.AddRange(node.Locals);
var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(numFixedLocals + 1 + 1); //+1 for body, +1 for hidden seq point
var cleanup = new BoundStatement[numFixedLocals];
for (int i = 0; i < numFixedLocals; i++)
{
BoundLocalDeclaration localDecl = localDecls[i];
LocalSymbol pinnedTemp;
statementBuilder.Add(InitializeFixedStatementLocal(localDecl, _factory, out pinnedTemp));
localBuilder.Add(pinnedTemp);
// NOTE: Dev10 nulls out the locals in declaration order (as opposed to "popping" them in reverse order).
if (pinnedTemp.RefKind == RefKind.None)
{
// temp = null;
cleanup[i] = _factory.Assignment(_factory.Local(pinnedTemp), _factory.Null(pinnedTemp.Type));
}
else
{
Debug.Assert(!pinnedTemp.Type.IsManagedTypeNoUseSiteDiagnostics);
// temp = ref *default(T*);
cleanup[i] = _factory.Assignment(_factory.Local(pinnedTemp), new BoundPointerIndirectionOperator(
_factory.Syntax,
_factory.Default(new PointerTypeSymbol(pinnedTemp.TypeWithAnnotations)),
pinnedTemp.Type),
isRef: true);
}
}
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
statementBuilder.Add(rewrittenBody);
statementBuilder.Add(_factory.HiddenSequencePoint());
Debug.Assert(statementBuilder.Count == numFixedLocals + 1 + 1);
// In principle, the cleanup code (i.e. nulling out the pinned variables) is always
// in a finally block. However, we can optimize finally away (keeping the cleanup
// code) in cases where both of the following are true:
// 1) there are no branches out of the fixed statement; and
// 2) the fixed statement is not in a try block (syntactic or synthesized).
if (IsInTryBlock(node) || HasGotoOut(rewrittenBody))
{
return _factory.Block(
localBuilder.ToImmutableAndFree(),
new BoundTryStatement(
_factory.Syntax,
_factory.Block(statementBuilder.ToImmutableAndFree()),
ImmutableArray<BoundCatchBlock>.Empty,
_factory.Block(cleanup)));
}
else
{
statementBuilder.AddRange(cleanup);
return _factory.Block(localBuilder.ToImmutableAndFree(), statementBuilder.ToImmutableAndFree());
}
}
/// <summary>
/// Basically, what we need to know is, if an exception occurred within the fixed statement, would
/// additional code in the current method be executed before its stack frame was popped?
/// </summary>
private static bool IsInTryBlock(BoundFixedStatement boundFixed)
{
SyntaxNode? node = boundFixed.Syntax.Parent;
Debug.Assert(node is { });
while (node != null)
{
switch (node.Kind())
{
case SyntaxKind.TryStatement:
// NOTE: if we started in the catch or finally of this try statement,
// we will have bypassed this node.
return true;
case SyntaxKind.UsingStatement:
// ACASEY: In treating using statements as try-finally's, we're following
// Dev11. The practical explanation for Dev11's behavior is that using
// statements have already been lowered by the time the check is performed.
// A more thoughtful explanation is that user code could run between the
// raising of an exception and the unwinding of the stack (via Dispose())
// and that user code would likely appreciate the reduced memory pressure
// of having the fixed local unpinned.
// NOTE: As in Dev11, we're not emitting a try-finally if the fixed
// statement is nested within a lock statement. Practically, dev11
// probably lowers locks after fixed statement, and so, does not see
// the try-finally. More thoughtfully, no user code will run in the
// finally statement, so it's not necessary.
// BREAK: Takes into account whether an outer fixed statement will be
// lowered into a try-finally block and responds accordingly. This is
// unnecessary since nothing will ever be allocated in the finally
// block of a lowered fixed statement, so memory pressure is not an
// issue. Note that only nested fixed statements where the outer (but
// not the inner) fixed statement has an unmatched goto, but is not
// contained in a try-finally, will be affected. e.g.
// fixed (...) {
// fixed (...) { }
// goto L1: ;
// }
return true;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
// We're being conservative here - there's actually only
// a try block if the enumerator is disposable, but we
// can't tell that from the syntax. Dev11 checks in the
// lowered tree, so it is more precise.
return true;
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
// Stop looking.
return false;
case SyntaxKind.CatchClause:
// If we're in the catch of a try-catch-finally, then
// we're still in the scope of the try-finally handler.
Debug.Assert(node.Parent is TryStatementSyntax);
if (((TryStatementSyntax)node.Parent).Finally != null)
{
return true;
}
goto case SyntaxKind.FinallyClause;
case SyntaxKind.FinallyClause:
// Skip past the enclosing try to avoid a false positive.
node = node.Parent;
Debug.Assert(node is { } && node.Kind() == SyntaxKind.TryStatement);
node = node.Parent;
break;
default:
if (node is MemberDeclarationSyntax)
{
// Stop looking.
return false;
}
node = node.Parent;
break;
}
}
return false;
}
/// <summary>
/// If two (or more) fixed statements are nested, then we want to avoid having the outer
/// fixed statement re-traverse the lowered bound tree of the inner one. We accomplish
/// this by having each fixed statement cache a set of unmatched gotos that can be
/// reused by any containing fixed statements.
/// </summary>
private Dictionary<BoundNode, HashSet<LabelSymbol>>? _lazyUnmatchedLabelCache;
/// <summary>
/// Look for gotos without corresponding labels in the lowered body of a fixed statement.
/// </summary>
/// <remarks>
/// Assumes continue, break, etc have already been rewritten to gotos.
/// </remarks>
private bool HasGotoOut(BoundNode node)
{
if (_lazyUnmatchedLabelCache == null)
{
_lazyUnmatchedLabelCache = new Dictionary<BoundNode, HashSet<LabelSymbol>>();
}
HashSet<LabelSymbol> unmatched = UnmatchedGotoFinder.Find(node, _lazyUnmatchedLabelCache, RecursionDepth);
_lazyUnmatchedLabelCache.Add(node, unmatched);
return unmatched != null && unmatched.Count > 0;
}
public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node)
{
throw ExceptionUtilities.Unreachable; //Should be handled by VisitFixedStatement
}
private BoundStatement InitializeFixedStatementLocal(
BoundLocalDeclaration localDecl,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
BoundExpression? initializer = localDecl.InitializerOpt;
Debug.Assert(!ReferenceEquals(initializer, null));
LocalSymbol localSymbol = localDecl.LocalSymbol;
var fixedCollectionInitializer = (BoundFixedLocalCollectionInitializer)initializer;
if (fixedCollectionInitializer.GetPinnableOpt is { })
{
return InitializeFixedStatementGetPinnable(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
else if (fixedCollectionInitializer.Expression.Type is { SpecialType: SpecialType.System_String })
{
return InitializeFixedStatementStringLocal(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
else if (fixedCollectionInitializer.Expression.Type is { TypeKind: TypeKind.Array })
{
return InitializeFixedStatementArrayLocal(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
else
{
return InitializeFixedStatementRegularLocal(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
}
/// <summary>
/// <![CDATA[
/// fixed(int* ptr = &v){ ... } == becomes ===>
///
/// pinned ref int pinnedTemp = ref v; // pinning managed ref
/// int* ptr = (int*)&pinnedTemp; // unsafe cast to unmanaged ptr
/// . . .
/// ]]>
/// </summary>
private BoundStatement InitializeFixedStatementRegularLocal(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
Debug.Assert(initializerExpr.Type is { TypeKind: TypeKind.Pointer });
// initializer expr should be either an address(&) of something or a fixed field access.
// either should lower into addressof
Debug.Assert(initializerExpr.Kind == BoundKind.AddressOfOperator);
TypeSymbol initializerType = ((PointerTypeSymbol)initializerExpr.Type).PointedAtType;
// initializer expressions are bound/lowered right into addressof operators here
// that is a bit too far
// we need to pin the underlying field, and only then take the address.
initializerExpr = ((BoundAddressOfOperator)initializerExpr).Operand;
// intervening parens may have been skipped by the binder; find the declarator
VariableDeclaratorSyntax? declarator = fixedInitializer.Syntax.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
Debug.Assert(declarator != null);
pinnedTemp = factory.SynthesizedLocal(
initializerType,
syntax: declarator,
isPinned: true,
//NOTE: different from the array and string cases
// RefReadOnly to allow referring to readonly variables. (technically we only "read" through the temp anyways)
refKind: RefKind.RefReadOnly,
kind: SynthesizedLocalKind.FixedReference);
// NOTE: we pin the reference, not the pointer.
Debug.Assert(pinnedTemp.IsPinned);
Debug.Assert(!localSymbol.IsPinned);
// pinnedTemp = ref v;
BoundStatement pinnedTempInit = factory.Assignment(factory.Local(pinnedTemp), initializerExpr, isRef: true);
// &pinnedTemp
var addr = new BoundAddressOfOperator(
factory.Syntax,
factory.Local(pinnedTemp),
type: fixedInitializer.ElementPointerType);
// (int*)&pinnedTemp
var pointerValue = factory.Convert(
localType,
addr,
fixedInitializer.ElementPointerTypeConversion);
// ptr = (int*)&pinnedTemp;
BoundStatement localInit = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol,
factory.Assignment(factory.Local(localSymbol), pointerValue));
return factory.Block(pinnedTempInit, localInit);
}
/// <summary>
/// <![CDATA[
/// fixed(int* ptr = &v){ ... } == becomes ===>
///
/// pinned ref int pinnedTemp = ref v; // pinning managed ref
/// int* ptr = (int*)&pinnedTemp; // unsafe cast to unmanaged ptr
/// . . .
/// ]]>
/// </summary>
private BoundStatement InitializeFixedStatementGetPinnable(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
Debug.Assert(initializerExpr.Type is { });
var initializerType = initializerExpr.Type;
var initializerSyntax = initializerExpr.Syntax;
var getPinnableMethod = fixedInitializer.GetPinnableOpt;
Debug.Assert(getPinnableMethod is { });
// intervening parens may have been skipped by the binder; find the declarator
VariableDeclaratorSyntax? declarator = fixedInitializer.Syntax.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
Debug.Assert(declarator != null);
// pinned ref int pinnedTemp
pinnedTemp = factory.SynthesizedLocal(
getPinnableMethod.ReturnType,
syntax: declarator,
isPinned: true,
//NOTE: different from the array and string cases
// RefReadOnly to allow referring to readonly variables. (technically we only "read" through the temp anyways)
refKind: RefKind.RefReadOnly,
kind: SynthesizedLocalKind.FixedReference);
BoundExpression callReceiver;
int currentConditionalAccessID = 0;
bool needNullCheck = !initializerType.IsValueType;
if (needNullCheck)
{
currentConditionalAccessID = ++_currentConditionalAccessID;
callReceiver = new BoundConditionalReceiver(
initializerSyntax,
currentConditionalAccessID,
initializerType);
}
else
{
callReceiver = initializerExpr;
}
// .GetPinnable()
var getPinnableCall = getPinnableMethod.IsStatic ?
factory.Call(null, getPinnableMethod, callReceiver) :
factory.Call(callReceiver, getPinnableMethod);
// temp =ref .GetPinnable()
var tempAssignment = factory.AssignmentExpression(
factory.Local(pinnedTemp),
getPinnableCall,
isRef: true);
// &pinnedTemp
var addr = new BoundAddressOfOperator(
factory.Syntax,
factory.Local(pinnedTemp),
type: fixedInitializer.ElementPointerType);
// (int*)&pinnedTemp
var pointerValue = factory.Convert(
localType,
addr,
fixedInitializer.ElementPointerTypeConversion);
// {pinnedTemp =ref .GetPinnable(), (int*)&pinnedTemp}
BoundExpression pinAndGetPtr = factory.Sequence(
locals: ImmutableArray<LocalSymbol>.Empty,
sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment),
result: pointerValue);
if (needNullCheck)
{
// initializer?.{temp =ref .GetPinnable(), (int*)&pinnedTemp} ?? default;
pinAndGetPtr = new BoundLoweredConditionalAccess(
initializerSyntax,
initializerExpr,
hasValueMethodOpt: null,
whenNotNull: pinAndGetPtr,
whenNullOpt: null, // just return default(T*)
currentConditionalAccessID,
localType);
}
// ptr = initializer?.{temp =ref .GetPinnable(), (int*)&pinnedTemp} ?? default;
BoundStatement localInit = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, factory.Assignment(factory.Local(localSymbol), pinAndGetPtr));
return localInit;
}
/// <summary>
/// fixed(char* ptr = stringVar){ ... } == becomes ===>
///
/// pinned string pinnedTemp = stringVar; // pinning managed ref
/// char* ptr = (char*)pinnedTemp; // unsafe cast to unmanaged ptr
/// if (pinnedTemp != null) ptr += OffsetToStringData();
/// . . .
/// </summary>
private BoundStatement InitializeFixedStatementStringLocal(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
TypeSymbol? initializerType = initializerExpr.Type;
Debug.Assert(initializerType is { });
// intervening parens may have been skipped by the binder; find the declarator
VariableDeclaratorSyntax? declarator = fixedInitializer.Syntax.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
Debug.Assert(declarator != null);
pinnedTemp = factory.SynthesizedLocal(
initializerType,
syntax: declarator,
isPinned: true,
kind: SynthesizedLocalKind.FixedReference);
// NOTE: we pin the string, not the pointer.
Debug.Assert(pinnedTemp.IsPinned);
Debug.Assert(!localSymbol.IsPinned);
BoundStatement stringTempInit = factory.Assignment(factory.Local(pinnedTemp), initializerExpr);
// (char*)pinnedTemp;
var addr = factory.Convert(
fixedInitializer.ElementPointerType,
factory.Local(pinnedTemp),
Conversion.PinnedObjectToPointer);
var convertedStringTemp = factory.Convert(
localType,
addr,
fixedInitializer.ElementPointerTypeConversion);
BoundStatement localInit = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol,
factory.Assignment(factory.Local(localSymbol), convertedStringTemp));
BoundExpression notNullCheck = MakeNullCheck(factory.Syntax, factory.Local(localSymbol), BinaryOperatorKind.NotEqual);
BoundExpression helperCall;
MethodSymbol offsetMethod;
if (TryGetWellKnownTypeMember(fixedInitializer.Syntax, WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData, out offsetMethod))
{
helperCall = factory.Call(receiver: null, method: offsetMethod);
}
else
{
helperCall = new BoundBadExpression(fixedInitializer.Syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray<BoundExpression>.Empty, ErrorTypeSymbol.UnknownResultType);
}
BoundExpression addition = factory.Binary(BinaryOperatorKind.PointerAndIntAddition, localType, factory.Local(localSymbol), helperCall);
BoundStatement conditionalAdd = factory.If(notNullCheck, factory.Assignment(factory.Local(localSymbol), addition));
return factory.Block(stringTempInit, localInit, conditionalAdd);
}
/// <summary>
/// <![CDATA[
/// fixed(int* ptr = arr){ ... } == becomes ===>
///
/// pinned int[] pinnedTemp = arr; // pinning managed ref
/// int* ptr = pinnedTemp != null && pinnedTemp.Length != 0 ?
/// (int*)&pinnedTemp[0] : // unsafe cast to unmanaged ptr
/// 0;
/// . . .
/// ]]>
/// </summary>
private BoundStatement InitializeFixedStatementArrayLocal(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
TypeSymbol? initializerType = initializerExpr.Type;
Debug.Assert(initializerType is { });
pinnedTemp = factory.SynthesizedLocal(initializerType, isPinned: true);
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)pinnedTemp.Type;
TypeWithAnnotations arrayElementType = arrayType.ElementTypeWithAnnotations;
// NOTE: we pin the array, not the pointer.
Debug.Assert(pinnedTemp.IsPinned);
Debug.Assert(!localSymbol.IsPinned);
//(pinnedTemp = array)
BoundExpression arrayTempInit = factory.AssignmentExpression(factory.Local(pinnedTemp), initializerExpr);
//(pinnedTemp = array) != null
BoundExpression notNullCheck = MakeNullCheck(factory.Syntax, arrayTempInit, BinaryOperatorKind.NotEqual);
BoundExpression lengthCall;
if (arrayType.IsSZArray)
{
lengthCall = factory.ArrayLength(factory.Local(pinnedTemp));
}
else
{
MethodSymbol lengthMethod;
if (TryGetWellKnownTypeMember(fixedInitializer.Syntax, WellKnownMember.System_Array__get_Length, out lengthMethod))
{
lengthCall = factory.Call(factory.Local(pinnedTemp), lengthMethod);
}
else
{
lengthCall = new BoundBadExpression(fixedInitializer.Syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create<BoundExpression>(factory.Local(pinnedTemp)), ErrorTypeSymbol.UnknownResultType);
}
}
// NOTE: dev10 comment says ">", but code actually checks "!="
//temp.Length != 0
BoundExpression lengthCheck = factory.Binary(BinaryOperatorKind.IntNotEqual, factory.SpecialType(SpecialType.System_Boolean), lengthCall, factory.Literal(0));
//((temp = array) != null && temp.Length != 0)
BoundExpression condition = factory.Binary(BinaryOperatorKind.LogicalBoolAnd, factory.SpecialType(SpecialType.System_Boolean), notNullCheck, lengthCheck);
//temp[0]
BoundExpression firstElement = factory.ArrayAccessFirstElement(factory.Local(pinnedTemp));
// NOTE: this is a fixed statement address-of in that it's the initial value of the pointer.
//&temp[0]
BoundExpression firstElementAddress = new BoundAddressOfOperator(factory.Syntax, firstElement, type: new PointerTypeSymbol(arrayElementType));
BoundExpression convertedFirstElementAddress = factory.Convert(
localType,
firstElementAddress,
fixedInitializer.ElementPointerTypeConversion);
//loc = &temp[0]
BoundExpression consequenceAssignment = factory.AssignmentExpression(factory.Local(localSymbol), convertedFirstElementAddress);
//loc = null
BoundExpression alternativeAssignment = factory.AssignmentExpression(factory.Local(localSymbol), factory.Null(localType));
//(((temp = array) != null && temp.Length != 0) ? loc = &temp[0] : loc = null)
BoundStatement localInit = factory.ExpressionStatement(
new BoundConditionalOperator(factory.Syntax, false, condition, consequenceAssignment, alternativeAssignment, ConstantValue.NotAvailable, localType, wasTargetTyped: false, localType));
return InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, localInit);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitFixedStatement(BoundFixedStatement node)
{
ImmutableArray<BoundLocalDeclaration> localDecls = node.Declarations.LocalDeclarations;
int numFixedLocals = localDecls.Length;
var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance(node.Locals.Length);
localBuilder.AddRange(node.Locals);
var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(numFixedLocals + 1 + 1); //+1 for body, +1 for hidden seq point
var cleanup = new BoundStatement[numFixedLocals];
for (int i = 0; i < numFixedLocals; i++)
{
BoundLocalDeclaration localDecl = localDecls[i];
LocalSymbol pinnedTemp;
statementBuilder.Add(InitializeFixedStatementLocal(localDecl, _factory, out pinnedTemp));
localBuilder.Add(pinnedTemp);
// NOTE: Dev10 nulls out the locals in declaration order (as opposed to "popping" them in reverse order).
if (pinnedTemp.RefKind == RefKind.None)
{
// temp = null;
cleanup[i] = _factory.Assignment(_factory.Local(pinnedTemp), _factory.Null(pinnedTemp.Type));
}
else
{
Debug.Assert(!pinnedTemp.Type.IsManagedTypeNoUseSiteDiagnostics);
// temp = ref *default(T*);
cleanup[i] = _factory.Assignment(_factory.Local(pinnedTemp), new BoundPointerIndirectionOperator(
_factory.Syntax,
_factory.Default(new PointerTypeSymbol(pinnedTemp.TypeWithAnnotations)),
pinnedTemp.Type),
isRef: true);
}
}
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
statementBuilder.Add(rewrittenBody);
statementBuilder.Add(_factory.HiddenSequencePoint());
Debug.Assert(statementBuilder.Count == numFixedLocals + 1 + 1);
// In principle, the cleanup code (i.e. nulling out the pinned variables) is always
// in a finally block. However, we can optimize finally away (keeping the cleanup
// code) in cases where both of the following are true:
// 1) there are no branches out of the fixed statement; and
// 2) the fixed statement is not in a try block (syntactic or synthesized).
if (IsInTryBlock(node) || HasGotoOut(rewrittenBody))
{
return _factory.Block(
localBuilder.ToImmutableAndFree(),
new BoundTryStatement(
_factory.Syntax,
_factory.Block(statementBuilder.ToImmutableAndFree()),
ImmutableArray<BoundCatchBlock>.Empty,
_factory.Block(cleanup)));
}
else
{
statementBuilder.AddRange(cleanup);
return _factory.Block(localBuilder.ToImmutableAndFree(), statementBuilder.ToImmutableAndFree());
}
}
/// <summary>
/// Basically, what we need to know is, if an exception occurred within the fixed statement, would
/// additional code in the current method be executed before its stack frame was popped?
/// </summary>
private static bool IsInTryBlock(BoundFixedStatement boundFixed)
{
SyntaxNode? node = boundFixed.Syntax.Parent;
Debug.Assert(node is { });
while (node != null)
{
switch (node.Kind())
{
case SyntaxKind.TryStatement:
// NOTE: if we started in the catch or finally of this try statement,
// we will have bypassed this node.
return true;
case SyntaxKind.UsingStatement:
// ACASEY: In treating using statements as try-finally's, we're following
// Dev11. The practical explanation for Dev11's behavior is that using
// statements have already been lowered by the time the check is performed.
// A more thoughtful explanation is that user code could run between the
// raising of an exception and the unwinding of the stack (via Dispose())
// and that user code would likely appreciate the reduced memory pressure
// of having the fixed local unpinned.
// NOTE: As in Dev11, we're not emitting a try-finally if the fixed
// statement is nested within a lock statement. Practically, dev11
// probably lowers locks after fixed statement, and so, does not see
// the try-finally. More thoughtfully, no user code will run in the
// finally statement, so it's not necessary.
// BREAK: Takes into account whether an outer fixed statement will be
// lowered into a try-finally block and responds accordingly. This is
// unnecessary since nothing will ever be allocated in the finally
// block of a lowered fixed statement, so memory pressure is not an
// issue. Note that only nested fixed statements where the outer (but
// not the inner) fixed statement has an unmatched goto, but is not
// contained in a try-finally, will be affected. e.g.
// fixed (...) {
// fixed (...) { }
// goto L1: ;
// }
return true;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
// We're being conservative here - there's actually only
// a try block if the enumerator is disposable, but we
// can't tell that from the syntax. Dev11 checks in the
// lowered tree, so it is more precise.
return true;
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
// Stop looking.
return false;
case SyntaxKind.CatchClause:
// If we're in the catch of a try-catch-finally, then
// we're still in the scope of the try-finally handler.
Debug.Assert(node.Parent is TryStatementSyntax);
if (((TryStatementSyntax)node.Parent).Finally != null)
{
return true;
}
goto case SyntaxKind.FinallyClause;
case SyntaxKind.FinallyClause:
// Skip past the enclosing try to avoid a false positive.
node = node.Parent;
Debug.Assert(node is { } && node.Kind() == SyntaxKind.TryStatement);
node = node.Parent;
break;
default:
if (node is MemberDeclarationSyntax)
{
// Stop looking.
return false;
}
node = node.Parent;
break;
}
}
return false;
}
/// <summary>
/// If two (or more) fixed statements are nested, then we want to avoid having the outer
/// fixed statement re-traverse the lowered bound tree of the inner one. We accomplish
/// this by having each fixed statement cache a set of unmatched gotos that can be
/// reused by any containing fixed statements.
/// </summary>
private Dictionary<BoundNode, HashSet<LabelSymbol>>? _lazyUnmatchedLabelCache;
/// <summary>
/// Look for gotos without corresponding labels in the lowered body of a fixed statement.
/// </summary>
/// <remarks>
/// Assumes continue, break, etc have already been rewritten to gotos.
/// </remarks>
private bool HasGotoOut(BoundNode node)
{
if (_lazyUnmatchedLabelCache == null)
{
_lazyUnmatchedLabelCache = new Dictionary<BoundNode, HashSet<LabelSymbol>>();
}
HashSet<LabelSymbol> unmatched = UnmatchedGotoFinder.Find(node, _lazyUnmatchedLabelCache, RecursionDepth);
_lazyUnmatchedLabelCache.Add(node, unmatched);
return unmatched != null && unmatched.Count > 0;
}
public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node)
{
throw ExceptionUtilities.Unreachable; //Should be handled by VisitFixedStatement
}
private BoundStatement InitializeFixedStatementLocal(
BoundLocalDeclaration localDecl,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
BoundExpression? initializer = localDecl.InitializerOpt;
Debug.Assert(!ReferenceEquals(initializer, null));
LocalSymbol localSymbol = localDecl.LocalSymbol;
var fixedCollectionInitializer = (BoundFixedLocalCollectionInitializer)initializer;
if (fixedCollectionInitializer.GetPinnableOpt is { })
{
return InitializeFixedStatementGetPinnable(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
else if (fixedCollectionInitializer.Expression.Type is { SpecialType: SpecialType.System_String })
{
return InitializeFixedStatementStringLocal(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
else if (fixedCollectionInitializer.Expression.Type is { TypeKind: TypeKind.Array })
{
return InitializeFixedStatementArrayLocal(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
else
{
return InitializeFixedStatementRegularLocal(localDecl, localSymbol, fixedCollectionInitializer, factory, out pinnedTemp);
}
}
/// <summary>
/// <![CDATA[
/// fixed(int* ptr = &v){ ... } == becomes ===>
///
/// pinned ref int pinnedTemp = ref v; // pinning managed ref
/// int* ptr = (int*)&pinnedTemp; // unsafe cast to unmanaged ptr
/// . . .
/// ]]>
/// </summary>
private BoundStatement InitializeFixedStatementRegularLocal(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
Debug.Assert(initializerExpr.Type is { TypeKind: TypeKind.Pointer });
// initializer expr should be either an address(&) of something or a fixed field access.
// either should lower into addressof
Debug.Assert(initializerExpr.Kind == BoundKind.AddressOfOperator);
TypeSymbol initializerType = ((PointerTypeSymbol)initializerExpr.Type).PointedAtType;
// initializer expressions are bound/lowered right into addressof operators here
// that is a bit too far
// we need to pin the underlying field, and only then take the address.
initializerExpr = ((BoundAddressOfOperator)initializerExpr).Operand;
// intervening parens may have been skipped by the binder; find the declarator
VariableDeclaratorSyntax? declarator = fixedInitializer.Syntax.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
Debug.Assert(declarator != null);
pinnedTemp = factory.SynthesizedLocal(
initializerType,
syntax: declarator,
isPinned: true,
//NOTE: different from the array and string cases
// RefReadOnly to allow referring to readonly variables. (technically we only "read" through the temp anyways)
refKind: RefKind.RefReadOnly,
kind: SynthesizedLocalKind.FixedReference);
// NOTE: we pin the reference, not the pointer.
Debug.Assert(pinnedTemp.IsPinned);
Debug.Assert(!localSymbol.IsPinned);
// pinnedTemp = ref v;
BoundStatement pinnedTempInit = factory.Assignment(factory.Local(pinnedTemp), initializerExpr, isRef: true);
// &pinnedTemp
var addr = new BoundAddressOfOperator(
factory.Syntax,
factory.Local(pinnedTemp),
type: fixedInitializer.ElementPointerType);
// (int*)&pinnedTemp
var pointerValue = factory.Convert(
localType,
addr,
fixedInitializer.ElementPointerTypeConversion);
// ptr = (int*)&pinnedTemp;
BoundStatement localInit = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol,
factory.Assignment(factory.Local(localSymbol), pointerValue));
return factory.Block(pinnedTempInit, localInit);
}
/// <summary>
/// <![CDATA[
/// fixed(int* ptr = &v){ ... } == becomes ===>
///
/// pinned ref int pinnedTemp = ref v; // pinning managed ref
/// int* ptr = (int*)&pinnedTemp; // unsafe cast to unmanaged ptr
/// . . .
/// ]]>
/// </summary>
private BoundStatement InitializeFixedStatementGetPinnable(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
Debug.Assert(initializerExpr.Type is { });
var initializerType = initializerExpr.Type;
var initializerSyntax = initializerExpr.Syntax;
var getPinnableMethod = fixedInitializer.GetPinnableOpt;
Debug.Assert(getPinnableMethod is { });
// intervening parens may have been skipped by the binder; find the declarator
VariableDeclaratorSyntax? declarator = fixedInitializer.Syntax.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
Debug.Assert(declarator != null);
// pinned ref int pinnedTemp
pinnedTemp = factory.SynthesizedLocal(
getPinnableMethod.ReturnType,
syntax: declarator,
isPinned: true,
//NOTE: different from the array and string cases
// RefReadOnly to allow referring to readonly variables. (technically we only "read" through the temp anyways)
refKind: RefKind.RefReadOnly,
kind: SynthesizedLocalKind.FixedReference);
BoundExpression callReceiver;
int currentConditionalAccessID = 0;
bool needNullCheck = !initializerType.IsValueType;
if (needNullCheck)
{
currentConditionalAccessID = ++_currentConditionalAccessID;
callReceiver = new BoundConditionalReceiver(
initializerSyntax,
currentConditionalAccessID,
initializerType);
}
else
{
callReceiver = initializerExpr;
}
// .GetPinnable()
var getPinnableCall = getPinnableMethod.IsStatic ?
factory.Call(null, getPinnableMethod, callReceiver) :
factory.Call(callReceiver, getPinnableMethod);
// temp =ref .GetPinnable()
var tempAssignment = factory.AssignmentExpression(
factory.Local(pinnedTemp),
getPinnableCall,
isRef: true);
// &pinnedTemp
var addr = new BoundAddressOfOperator(
factory.Syntax,
factory.Local(pinnedTemp),
type: fixedInitializer.ElementPointerType);
// (int*)&pinnedTemp
var pointerValue = factory.Convert(
localType,
addr,
fixedInitializer.ElementPointerTypeConversion);
// {pinnedTemp =ref .GetPinnable(), (int*)&pinnedTemp}
BoundExpression pinAndGetPtr = factory.Sequence(
locals: ImmutableArray<LocalSymbol>.Empty,
sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment),
result: pointerValue);
if (needNullCheck)
{
// initializer?.{temp =ref .GetPinnable(), (int*)&pinnedTemp} ?? default;
pinAndGetPtr = new BoundLoweredConditionalAccess(
initializerSyntax,
initializerExpr,
hasValueMethodOpt: null,
whenNotNull: pinAndGetPtr,
whenNullOpt: null, // just return default(T*)
currentConditionalAccessID,
localType);
}
// ptr = initializer?.{temp =ref .GetPinnable(), (int*)&pinnedTemp} ?? default;
BoundStatement localInit = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, factory.Assignment(factory.Local(localSymbol), pinAndGetPtr));
return localInit;
}
/// <summary>
/// fixed(char* ptr = stringVar){ ... } == becomes ===>
///
/// pinned string pinnedTemp = stringVar; // pinning managed ref
/// char* ptr = (char*)pinnedTemp; // unsafe cast to unmanaged ptr
/// if (pinnedTemp != null) ptr += OffsetToStringData();
/// . . .
/// </summary>
private BoundStatement InitializeFixedStatementStringLocal(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
TypeSymbol? initializerType = initializerExpr.Type;
Debug.Assert(initializerType is { });
// intervening parens may have been skipped by the binder; find the declarator
VariableDeclaratorSyntax? declarator = fixedInitializer.Syntax.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
Debug.Assert(declarator != null);
pinnedTemp = factory.SynthesizedLocal(
initializerType,
syntax: declarator,
isPinned: true,
kind: SynthesizedLocalKind.FixedReference);
// NOTE: we pin the string, not the pointer.
Debug.Assert(pinnedTemp.IsPinned);
Debug.Assert(!localSymbol.IsPinned);
BoundStatement stringTempInit = factory.Assignment(factory.Local(pinnedTemp), initializerExpr);
// (char*)pinnedTemp;
var addr = factory.Convert(
fixedInitializer.ElementPointerType,
factory.Local(pinnedTemp),
Conversion.PinnedObjectToPointer);
var convertedStringTemp = factory.Convert(
localType,
addr,
fixedInitializer.ElementPointerTypeConversion);
BoundStatement localInit = InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol,
factory.Assignment(factory.Local(localSymbol), convertedStringTemp));
BoundExpression notNullCheck = MakeNullCheck(factory.Syntax, factory.Local(localSymbol), BinaryOperatorKind.NotEqual);
BoundExpression helperCall;
MethodSymbol offsetMethod;
if (TryGetWellKnownTypeMember(fixedInitializer.Syntax, WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData, out offsetMethod))
{
helperCall = factory.Call(receiver: null, method: offsetMethod);
}
else
{
helperCall = new BoundBadExpression(fixedInitializer.Syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray<BoundExpression>.Empty, ErrorTypeSymbol.UnknownResultType);
}
BoundExpression addition = factory.Binary(BinaryOperatorKind.PointerAndIntAddition, localType, factory.Local(localSymbol), helperCall);
BoundStatement conditionalAdd = factory.If(notNullCheck, factory.Assignment(factory.Local(localSymbol), addition));
return factory.Block(stringTempInit, localInit, conditionalAdd);
}
/// <summary>
/// <![CDATA[
/// fixed(int* ptr = arr){ ... } == becomes ===>
///
/// pinned int[] pinnedTemp = arr; // pinning managed ref
/// int* ptr = pinnedTemp != null && pinnedTemp.Length != 0 ?
/// (int*)&pinnedTemp[0] : // unsafe cast to unmanaged ptr
/// 0;
/// . . .
/// ]]>
/// </summary>
private BoundStatement InitializeFixedStatementArrayLocal(
BoundLocalDeclaration localDecl,
LocalSymbol localSymbol,
BoundFixedLocalCollectionInitializer fixedInitializer,
SyntheticBoundNodeFactory factory,
out LocalSymbol pinnedTemp)
{
TypeSymbol localType = localSymbol.Type;
BoundExpression initializerExpr = VisitExpression(fixedInitializer.Expression);
TypeSymbol? initializerType = initializerExpr.Type;
Debug.Assert(initializerType is { });
pinnedTemp = factory.SynthesizedLocal(initializerType, isPinned: true);
ArrayTypeSymbol arrayType = (ArrayTypeSymbol)pinnedTemp.Type;
TypeWithAnnotations arrayElementType = arrayType.ElementTypeWithAnnotations;
// NOTE: we pin the array, not the pointer.
Debug.Assert(pinnedTemp.IsPinned);
Debug.Assert(!localSymbol.IsPinned);
//(pinnedTemp = array)
BoundExpression arrayTempInit = factory.AssignmentExpression(factory.Local(pinnedTemp), initializerExpr);
//(pinnedTemp = array) != null
BoundExpression notNullCheck = MakeNullCheck(factory.Syntax, arrayTempInit, BinaryOperatorKind.NotEqual);
BoundExpression lengthCall;
if (arrayType.IsSZArray)
{
lengthCall = factory.ArrayLength(factory.Local(pinnedTemp));
}
else
{
MethodSymbol lengthMethod;
if (TryGetWellKnownTypeMember(fixedInitializer.Syntax, WellKnownMember.System_Array__get_Length, out lengthMethod))
{
lengthCall = factory.Call(factory.Local(pinnedTemp), lengthMethod);
}
else
{
lengthCall = new BoundBadExpression(fixedInitializer.Syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create<BoundExpression>(factory.Local(pinnedTemp)), ErrorTypeSymbol.UnknownResultType);
}
}
// NOTE: dev10 comment says ">", but code actually checks "!="
//temp.Length != 0
BoundExpression lengthCheck = factory.Binary(BinaryOperatorKind.IntNotEqual, factory.SpecialType(SpecialType.System_Boolean), lengthCall, factory.Literal(0));
//((temp = array) != null && temp.Length != 0)
BoundExpression condition = factory.Binary(BinaryOperatorKind.LogicalBoolAnd, factory.SpecialType(SpecialType.System_Boolean), notNullCheck, lengthCheck);
//temp[0]
BoundExpression firstElement = factory.ArrayAccessFirstElement(factory.Local(pinnedTemp));
// NOTE: this is a fixed statement address-of in that it's the initial value of the pointer.
//&temp[0]
BoundExpression firstElementAddress = new BoundAddressOfOperator(factory.Syntax, firstElement, type: new PointerTypeSymbol(arrayElementType));
BoundExpression convertedFirstElementAddress = factory.Convert(
localType,
firstElementAddress,
fixedInitializer.ElementPointerTypeConversion);
//loc = &temp[0]
BoundExpression consequenceAssignment = factory.AssignmentExpression(factory.Local(localSymbol), convertedFirstElementAddress);
//loc = null
BoundExpression alternativeAssignment = factory.AssignmentExpression(factory.Local(localSymbol), factory.Null(localType));
//(((temp = array) != null && temp.Length != 0) ? loc = &temp[0] : loc = null)
BoundStatement localInit = factory.ExpressionStatement(
new BoundConditionalOperator(factory.Syntax, false, condition, consequenceAssignment, alternativeAssignment, ConstantValue.NotAvailable, localType, wasTargetTyped: false, localType));
return InstrumentLocalDeclarationIfNecessary(localDecl, localSymbol, localInit);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/BoundTree/BoundDecisionDagNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
#if DEBUG
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
#endif
partial class BoundDecisionDagNode
{
public override bool Equals(object? other)
{
if (this == other)
return true;
switch (this, other)
{
case (BoundEvaluationDecisionDagNode n1, BoundEvaluationDecisionDagNode n2):
return n1.Evaluation.Equals(n2.Evaluation) && n1.Next == n2.Next;
case (BoundTestDecisionDagNode n1, BoundTestDecisionDagNode n2):
return n1.Test.Equals(n2.Test) && n1.WhenTrue == n2.WhenTrue && n1.WhenFalse == n2.WhenFalse;
case (BoundWhenDecisionDagNode n1, BoundWhenDecisionDagNode n2):
return n1.WhenExpression == n2.WhenExpression && n1.WhenTrue == n2.WhenTrue && n1.WhenFalse == n2.WhenFalse;
case (BoundLeafDecisionDagNode n1, BoundLeafDecisionDagNode n2):
return n1.Label == n2.Label;
default:
return false;
}
}
public override int GetHashCode()
{
switch (this)
{
case BoundEvaluationDecisionDagNode n:
return Hash.Combine(n.Evaluation.GetHashCode(), RuntimeHelpers.GetHashCode(n.Next));
case BoundTestDecisionDagNode n:
return Hash.Combine(n.Test.GetHashCode(), Hash.Combine(RuntimeHelpers.GetHashCode(n.WhenFalse), RuntimeHelpers.GetHashCode(n.WhenTrue)));
case BoundWhenDecisionDagNode n:
// See https://github.com/dotnet/runtime/pull/31819 for why ! is temporarily required below.
return Hash.Combine(RuntimeHelpers.GetHashCode(n.WhenExpression!), Hash.Combine(RuntimeHelpers.GetHashCode(n.WhenFalse!), RuntimeHelpers.GetHashCode(n.WhenTrue)));
case BoundLeafDecisionDagNode n:
return RuntimeHelpers.GetHashCode(n.Label);
default:
throw ExceptionUtilities.UnexpectedValue(this);
}
}
#if DEBUG
private int _id = -1;
public int Id
{
get
{
return _id;
}
internal set
{
Debug.Assert(value >= 0, "Id must be non-negative but was set to " + value);
Debug.Assert(_id == -1, $"Id was set to {_id} and set again to {value}");
_id = value;
}
}
internal new string GetDebuggerDisplay()
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append($"[{this.Id}]: ");
switch (this)
{
case BoundTestDecisionDagNode node:
builder.Append($"{node.Test.GetDebuggerDisplay()} ");
builder.Append(node.WhenTrue != null
? $"? [{node.WhenTrue.Id}] "
: "? <unreachable> ");
builder.Append(node.WhenFalse != null
? $": [{node.WhenFalse.Id}]"
: ": <unreachable>");
break;
case BoundEvaluationDecisionDagNode node:
builder.Append($"{node.Evaluation.GetDebuggerDisplay()}; ");
builder.Append(node.Next != null
? $"[{node.Next.Id}]"
: "<unreachable>");
break;
case BoundWhenDecisionDagNode node:
builder.Append("when ");
builder.Append(node.WhenExpression is { } when
? $"({when.Syntax}) "
: "<true> ");
builder.Append(node.WhenTrue != null
? $"? [{node.WhenTrue.Id}] "
: "? <unreachable> ");
builder.Append(node.WhenFalse != null
? $": [{node.WhenFalse.Id}]"
: ": <unreachable>");
break;
case BoundLeafDecisionDagNode node:
builder.Append(node.Label is GeneratedLabelSymbol generated
? $"leaf {generated.NameNoSequence} `{node.Syntax}`"
: $"leaf `{node.Label.Name}`");
break;
default:
builder.Append(base.GetDebuggerDisplay());
break;
}
return pooledBuilder.ToStringAndFree();
}
#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.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
#if DEBUG
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
#endif
partial class BoundDecisionDagNode
{
public override bool Equals(object? other)
{
if (this == other)
return true;
switch (this, other)
{
case (BoundEvaluationDecisionDagNode n1, BoundEvaluationDecisionDagNode n2):
return n1.Evaluation.Equals(n2.Evaluation) && n1.Next == n2.Next;
case (BoundTestDecisionDagNode n1, BoundTestDecisionDagNode n2):
return n1.Test.Equals(n2.Test) && n1.WhenTrue == n2.WhenTrue && n1.WhenFalse == n2.WhenFalse;
case (BoundWhenDecisionDagNode n1, BoundWhenDecisionDagNode n2):
return n1.WhenExpression == n2.WhenExpression && n1.WhenTrue == n2.WhenTrue && n1.WhenFalse == n2.WhenFalse;
case (BoundLeafDecisionDagNode n1, BoundLeafDecisionDagNode n2):
return n1.Label == n2.Label;
default:
return false;
}
}
public override int GetHashCode()
{
switch (this)
{
case BoundEvaluationDecisionDagNode n:
return Hash.Combine(n.Evaluation.GetHashCode(), RuntimeHelpers.GetHashCode(n.Next));
case BoundTestDecisionDagNode n:
return Hash.Combine(n.Test.GetHashCode(), Hash.Combine(RuntimeHelpers.GetHashCode(n.WhenFalse), RuntimeHelpers.GetHashCode(n.WhenTrue)));
case BoundWhenDecisionDagNode n:
// See https://github.com/dotnet/runtime/pull/31819 for why ! is temporarily required below.
return Hash.Combine(RuntimeHelpers.GetHashCode(n.WhenExpression!), Hash.Combine(RuntimeHelpers.GetHashCode(n.WhenFalse!), RuntimeHelpers.GetHashCode(n.WhenTrue)));
case BoundLeafDecisionDagNode n:
return RuntimeHelpers.GetHashCode(n.Label);
default:
throw ExceptionUtilities.UnexpectedValue(this);
}
}
#if DEBUG
private int _id = -1;
public int Id
{
get
{
return _id;
}
internal set
{
Debug.Assert(value >= 0, "Id must be non-negative but was set to " + value);
Debug.Assert(_id == -1, $"Id was set to {_id} and set again to {value}");
_id = value;
}
}
internal new string GetDebuggerDisplay()
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append($"[{this.Id}]: ");
switch (this)
{
case BoundTestDecisionDagNode node:
builder.Append($"{node.Test.GetDebuggerDisplay()} ");
builder.Append(node.WhenTrue != null
? $"? [{node.WhenTrue.Id}] "
: "? <unreachable> ");
builder.Append(node.WhenFalse != null
? $": [{node.WhenFalse.Id}]"
: ": <unreachable>");
break;
case BoundEvaluationDecisionDagNode node:
builder.Append($"{node.Evaluation.GetDebuggerDisplay()}; ");
builder.Append(node.Next != null
? $"[{node.Next.Id}]"
: "<unreachable>");
break;
case BoundWhenDecisionDagNode node:
builder.Append("when ");
builder.Append(node.WhenExpression is { } when
? $"({when.Syntax}) "
: "<true> ");
builder.Append(node.WhenTrue != null
? $"? [{node.WhenTrue.Id}] "
: "? <unreachable> ");
builder.Append(node.WhenFalse != null
? $": [{node.WhenFalse.Id}]"
: ": <unreachable>");
break;
case BoundLeafDecisionDagNode node:
builder.Append(node.Label is GeneratedLabelSymbol generated
? $"leaf {generated.NameNoSequence} `{node.Syntax}`"
: $"leaf `{node.Label.Name}`");
break;
default:
builder.Append(base.GetDebuggerDisplay());
break;
}
return pooledBuilder.ToStringAndFree();
}
#endif
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleRules.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal class NamingStyleRules
{
public ImmutableArray<NamingRule> NamingRules { get; }
private readonly ImmutableArray<SymbolKind> _symbolKindsThatCanBeOverridden =
ImmutableArray.Create(
SymbolKind.Method,
SymbolKind.Property,
SymbolKind.Event);
public NamingStyleRules(ImmutableArray<NamingRule> namingRules)
=> NamingRules = namingRules;
internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule)
{
if (NamingRules != null &&
IsSymbolNameAnalyzable(symbol))
{
foreach (var namingRule in NamingRules)
{
if (namingRule.SymbolSpecification.AppliesTo(symbol))
{
applicableRule = namingRule;
return true;
}
}
}
applicableRule = default;
return false;
}
private bool IsSymbolNameAnalyzable(ISymbol symbol)
{
if (_symbolKindsThatCanBeOverridden.Contains(symbol.Kind) && DoesSymbolImplementAnotherSymbol(symbol))
{
return false;
}
if (symbol is IMethodSymbol method)
{
return method.MethodKind == MethodKind.Ordinary ||
method.MethodKind == MethodKind.LocalFunction;
}
if (symbol is IPropertySymbol property)
{
return !property.IsIndexer;
}
return true;
}
private static bool DoesSymbolImplementAnotherSymbol(ISymbol symbol)
{
if (symbol.IsStatic)
{
return false;
}
var containingType = symbol.ContainingType;
if (containingType.TypeKind != TypeKind.Class && containingType.TypeKind != TypeKind.Struct)
{
return false;
}
return symbol.IsOverride ||
symbol.ExplicitInterfaceImplementations().Any() ||
IsInterfaceImplementation(symbol);
}
/// <summary>
/// This does not handle the case where a method in a base type implicitly implements an
/// interface method on behalf of one of its derived types.
/// </summary>
private static bool IsInterfaceImplementation(ISymbol symbol)
{
if (symbol.DeclaredAccessibility != Accessibility.Public)
{
return false;
}
var containingType = symbol.ContainingType;
var implementedInterfaces = containingType.AllInterfaces;
foreach (var implementedInterface in implementedInterfaces)
{
var implementedInterfaceMembersWithSameName = implementedInterface.GetMembers(symbol.Name);
foreach (var implementedInterfaceMember in implementedInterfaceMembersWithSameName)
{
if (symbol.Equals(containingType.FindImplementationForInterfaceMember(implementedInterfaceMember)))
{
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.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal class NamingStyleRules
{
public ImmutableArray<NamingRule> NamingRules { get; }
private readonly ImmutableArray<SymbolKind> _symbolKindsThatCanBeOverridden =
ImmutableArray.Create(
SymbolKind.Method,
SymbolKind.Property,
SymbolKind.Event);
public NamingStyleRules(ImmutableArray<NamingRule> namingRules)
=> NamingRules = namingRules;
internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule)
{
if (NamingRules != null &&
IsSymbolNameAnalyzable(symbol))
{
foreach (var namingRule in NamingRules)
{
if (namingRule.SymbolSpecification.AppliesTo(symbol))
{
applicableRule = namingRule;
return true;
}
}
}
applicableRule = default;
return false;
}
private bool IsSymbolNameAnalyzable(ISymbol symbol)
{
if (_symbolKindsThatCanBeOverridden.Contains(symbol.Kind) && DoesSymbolImplementAnotherSymbol(symbol))
{
return false;
}
if (symbol is IMethodSymbol method)
{
return method.MethodKind == MethodKind.Ordinary ||
method.MethodKind == MethodKind.LocalFunction;
}
if (symbol is IPropertySymbol property)
{
return !property.IsIndexer;
}
return true;
}
private static bool DoesSymbolImplementAnotherSymbol(ISymbol symbol)
{
if (symbol.IsStatic)
{
return false;
}
var containingType = symbol.ContainingType;
if (containingType.TypeKind != TypeKind.Class && containingType.TypeKind != TypeKind.Struct)
{
return false;
}
return symbol.IsOverride ||
symbol.ExplicitInterfaceImplementations().Any() ||
IsInterfaceImplementation(symbol);
}
/// <summary>
/// This does not handle the case where a method in a base type implicitly implements an
/// interface method on behalf of one of its derived types.
/// </summary>
private static bool IsInterfaceImplementation(ISymbol symbol)
{
if (symbol.DeclaredAccessibility != Accessibility.Public)
{
return false;
}
var containingType = symbol.ContainingType;
var implementedInterfaces = containingType.AllInterfaces;
foreach (var implementedInterface in implementedInterfaces)
{
var implementedInterfaceMembersWithSameName = implementedInterface.GetMembers(symbol.Name);
foreach (var implementedInterfaceMember in implementedInterfaceMembersWithSameName)
{
if (symbol.Equals(containingType.FindImplementationForInterfaceMember(implementedInterfaceMember)))
{
return true;
}
}
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/CSharp/Portable/Indentation/CSharpIndentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Indentation
{
[ExportLanguageService(typeof(IIndentationService), LanguageNames.CSharp), Shared]
internal sealed partial class CSharpIndentationService : AbstractIndentationService<CompilationUnitSyntax>
{
public static readonly CSharpIndentationService Instance = new();
private static readonly AbstractFormattingRule s_instance = new FormattingRule();
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")]
public CSharpIndentationService()
{
}
protected override AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle)
=> s_instance;
public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
IEnumerable<AbstractFormattingRule> formattingRules,
CompilationUnitSyntax root,
TextLine line,
IOptionService optionService,
OptionSet optionSet,
out SyntaxToken token)
{
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(root);
token = default;
if (!optionSet.GetOption(FormattingOptions.AutoFormattingOnReturn, LanguageNames.CSharp))
{
return false;
}
if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart)
{
return false;
}
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return false;
}
token = root.FindToken(firstNonWhitespacePosition.Value);
if (IsInvalidToken(token))
{
return false;
}
if (token.IsKind(SyntaxKind.None) ||
token.SpanStart != firstNonWhitespacePosition)
{
return false;
}
// first see whether there is a line operation for current token
var previousToken = token.GetPreviousToken(includeZeroWidth: true);
// only use smart token formatter when we have two visible tokens.
if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing)
{
return false;
}
var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet.AsAnalyzerConfigOptions(optionService, LanguageNames.CSharp));
if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
// no indentation operation, nothing to do for smart token formatter
return false;
}
// We're pressing enter between two tokens, have the formatter figure out hte appropriate
// indentation.
return true;
}
private static bool IsInvalidToken(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
private class FormattingRule : AbstractFormattingRule
{
public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
// these nodes should be from syntax tree from ITextSnapshot.
Debug.Assert(node.SyntaxTree != null);
Debug.Assert(node.SyntaxTree.GetText() != null);
nextOperation.Invoke();
ReplaceCaseIndentationRules(list, node);
if (node is BaseParameterListSyntax ||
node is TypeArgumentListSyntax ||
node is TypeParameterListSyntax ||
node.IsKind(SyntaxKind.Interpolation))
{
AddIndentBlockOperations(list, node);
return;
}
if (node is BaseArgumentListSyntax argument &&
!argument.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
!IsBracketedArgumentListMissingBrackets(argument as BracketedArgumentListSyntax))
{
AddIndentBlockOperations(list, argument);
return;
}
// only valid if the user has started to actually type a constructor initializer
if (node is ConstructorInitializerSyntax constructorInitializer &&
constructorInitializer.ArgumentList.OpenParenToken.Kind() != SyntaxKind.None &&
!constructorInitializer.ThisOrBaseKeyword.IsMissing)
{
var text = node.SyntaxTree.GetText();
// 3 different cases
// first case : this or base is the first token on line
// second case : colon is the first token on line
var colonIsFirstTokenOnLine = !constructorInitializer.ColonToken.IsMissing && constructorInitializer.ColonToken.IsFirstTokenOnLine(text);
var thisOrBaseIsFirstTokenOnLine = !constructorInitializer.ThisOrBaseKeyword.IsMissing && constructorInitializer.ThisOrBaseKeyword.IsFirstTokenOnLine(text);
if (colonIsFirstTokenOnLine || thisOrBaseIsFirstTokenOnLine)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
constructorInitializer.ThisOrBaseKeyword,
constructorInitializer.ArgumentList.OpenParenToken.GetNextToken(includeZeroWidth: true),
constructorInitializer.ArgumentList.CloseParenToken.GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativePosition));
}
else
{
// third case : none of them are the first token on the line
AddIndentBlockOperations(list, constructorInitializer.ArgumentList);
}
}
}
private static bool IsBracketedArgumentListMissingBrackets(BracketedArgumentListSyntax? node)
=> node != null && node.OpenBracketToken.IsMissing && node.CloseBracketToken.IsMissing;
private static void ReplaceCaseIndentationRules(List<IndentBlockOperation> list, SyntaxNode node)
{
if (!(node is SwitchSectionSyntax section) || section.Statements.Count == 0)
{
return;
}
var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true);
var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true);
for (var i = 0; i < list.Count; i++)
{
var operation = list[i];
if (operation.StartToken == startToken && operation.EndToken == endToken)
{
// replace operation
list[i] = FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: IndentBlockOption.RelativePosition);
}
}
}
private static void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node)
{
RoslynDebug.AssertNotNull(node.Parent);
// only add indent block operation if the base token is the first token on line
var baseToken = node.Parent.GetFirstToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
baseToken,
node.GetFirstToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true),
node.GetLastToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Indentation
{
[ExportLanguageService(typeof(IIndentationService), LanguageNames.CSharp), Shared]
internal sealed partial class CSharpIndentationService : AbstractIndentationService<CompilationUnitSyntax>
{
public static readonly CSharpIndentationService Instance = new();
private static readonly AbstractFormattingRule s_instance = new FormattingRule();
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")]
public CSharpIndentationService()
{
}
protected override AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle)
=> s_instance;
public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
IEnumerable<AbstractFormattingRule> formattingRules,
CompilationUnitSyntax root,
TextLine line,
IOptionService optionService,
OptionSet optionSet,
out SyntaxToken token)
{
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(root);
token = default;
if (!optionSet.GetOption(FormattingOptions.AutoFormattingOnReturn, LanguageNames.CSharp))
{
return false;
}
if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart)
{
return false;
}
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return false;
}
token = root.FindToken(firstNonWhitespacePosition.Value);
if (IsInvalidToken(token))
{
return false;
}
if (token.IsKind(SyntaxKind.None) ||
token.SpanStart != firstNonWhitespacePosition)
{
return false;
}
// first see whether there is a line operation for current token
var previousToken = token.GetPreviousToken(includeZeroWidth: true);
// only use smart token formatter when we have two visible tokens.
if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing)
{
return false;
}
var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet.AsAnalyzerConfigOptions(optionService, LanguageNames.CSharp));
if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
// no indentation operation, nothing to do for smart token formatter
return false;
}
// We're pressing enter between two tokens, have the formatter figure out hte appropriate
// indentation.
return true;
}
private static bool IsInvalidToken(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
private class FormattingRule : AbstractFormattingRule
{
public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
// these nodes should be from syntax tree from ITextSnapshot.
Debug.Assert(node.SyntaxTree != null);
Debug.Assert(node.SyntaxTree.GetText() != null);
nextOperation.Invoke();
ReplaceCaseIndentationRules(list, node);
if (node is BaseParameterListSyntax ||
node is TypeArgumentListSyntax ||
node is TypeParameterListSyntax ||
node.IsKind(SyntaxKind.Interpolation))
{
AddIndentBlockOperations(list, node);
return;
}
if (node is BaseArgumentListSyntax argument &&
!argument.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
!IsBracketedArgumentListMissingBrackets(argument as BracketedArgumentListSyntax))
{
AddIndentBlockOperations(list, argument);
return;
}
// only valid if the user has started to actually type a constructor initializer
if (node is ConstructorInitializerSyntax constructorInitializer &&
constructorInitializer.ArgumentList.OpenParenToken.Kind() != SyntaxKind.None &&
!constructorInitializer.ThisOrBaseKeyword.IsMissing)
{
var text = node.SyntaxTree.GetText();
// 3 different cases
// first case : this or base is the first token on line
// second case : colon is the first token on line
var colonIsFirstTokenOnLine = !constructorInitializer.ColonToken.IsMissing && constructorInitializer.ColonToken.IsFirstTokenOnLine(text);
var thisOrBaseIsFirstTokenOnLine = !constructorInitializer.ThisOrBaseKeyword.IsMissing && constructorInitializer.ThisOrBaseKeyword.IsFirstTokenOnLine(text);
if (colonIsFirstTokenOnLine || thisOrBaseIsFirstTokenOnLine)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
constructorInitializer.ThisOrBaseKeyword,
constructorInitializer.ArgumentList.OpenParenToken.GetNextToken(includeZeroWidth: true),
constructorInitializer.ArgumentList.CloseParenToken.GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativePosition));
}
else
{
// third case : none of them are the first token on the line
AddIndentBlockOperations(list, constructorInitializer.ArgumentList);
}
}
}
private static bool IsBracketedArgumentListMissingBrackets(BracketedArgumentListSyntax? node)
=> node != null && node.OpenBracketToken.IsMissing && node.CloseBracketToken.IsMissing;
private static void ReplaceCaseIndentationRules(List<IndentBlockOperation> list, SyntaxNode node)
{
if (!(node is SwitchSectionSyntax section) || section.Statements.Count == 0)
{
return;
}
var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true);
var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true);
for (var i = 0; i < list.Count; i++)
{
var operation = list[i];
if (operation.StartToken == startToken && operation.EndToken == endToken)
{
// replace operation
list[i] = FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: IndentBlockOption.RelativePosition);
}
}
}
private static void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node)
{
RoslynDebug.AssertNotNull(node.Parent);
// only add indent block operation if the base token is the first token on line
var baseToken = node.Parent.GetFirstToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
baseToken,
node.GetFirstToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true),
node.GetLastToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine));
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Syntax/ForOrForEachBlockSyntax.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Partial Public Class ForOrForEachBlockSyntax
''' <summary>
''' The For or For Each statement that begins the block.
''' </summary>
Public MustOverride ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax
End Class
Partial Public Class ForBlockSyntax
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Public Overrides ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax
Get
Return ForStatement
End Get
End Property
End Class
Partial Public Class ForEachBlockSyntax
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Public Overrides ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax
Get
Return ForEachStatement
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Partial Public Class ForOrForEachBlockSyntax
''' <summary>
''' The For or For Each statement that begins the block.
''' </summary>
Public MustOverride ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax
End Class
Partial Public Class ForBlockSyntax
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Public Overrides ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax
Get
Return ForStatement
End Get
End Property
End Class
Partial Public Class ForEachBlockSyntax
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)>
Public Overrides ReadOnly Property ForOrForEachStatement As ForOrForEachStatementSyntax
Get
Return ForEachStatement
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/CodeAnalysisTest/MetadataReferences/ModuleMetadataTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.IO;
using Roslyn.Test.Utilities;
using Xunit;
using System.Collections.Generic;
using System.Reflection.PortableExecutable;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class ModuleMetadataTests : TestBase
{
[Fact]
public unsafe void CreateFromMetadata_Errors()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromMetadata(IntPtr.Zero, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromMetadata((IntPtr)ptr, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromMetadata((IntPtr)ptr, -1); });
fixed (byte* ptr = new byte[] { 1, 2, 3 })
{
var metadata = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, 3);
Assert.Throws<BadImageFormatException>(() => metadata.GetModuleNames());
}
}
[Fact]
public unsafe void CreateFromMetadata_Assembly()
{
var assembly = TestResources.Basic.Members;
PEHeaders h = new PEHeaders(new MemoryStream(assembly));
fixed (byte* ptr = &assembly[h.MetadataStartOffset])
{
var metadata = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize);
Assert.Equal(new AssemblyIdentity("Members"), metadata.Module.ReadAssemblyIdentityOrThrow());
}
}
[Fact]
public unsafe void CreateFromMetadata_Module()
{
var netModule = TestResources.MetadataTests.NetModule01.ModuleCS00;
PEHeaders h = new PEHeaders(new MemoryStream(netModule));
fixed (byte* ptr = &netModule[h.MetadataStartOffset])
{
ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize);
}
}
[Fact]
public unsafe void CreateFromImage()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(IntPtr.Zero, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromImage((IntPtr)ptr, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromImage((IntPtr)ptr, -1); });
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(default(ImmutableArray<byte>)));
IEnumerable<byte> enumerableImage = null;
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(enumerableImage));
byte[] arrayImage = null;
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(arrayImage));
// It's not particularly important that this not throw. The parsing of the metadata is now lazy, and the result is that an exception
// will be thrown when something tugs on the metadata later.
ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Invalid.EmptyModuleTable);
}
[Fact]
public void CreateFromImageStream()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromStream(peStream: null));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromStream(new TestStream(canRead: false, canSeek: true)));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromStream(new TestStream(canRead: true, canSeek: false)));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void CreateFromFile()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromFile((string)null));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromFile(""));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromFile(@"c:\*"));
char systemDrive = Environment.GetFolderPath(Environment.SpecialFolder.Windows)[0];
Assert.Throws<IOException>(() => ModuleMetadata.CreateFromFile(@"http://goo.bar"));
Assert.Throws<FileNotFoundException>(() => ModuleMetadata.CreateFromFile(systemDrive + @":\file_that_does_not_exists.dll"));
Assert.Throws<FileNotFoundException>(() => ModuleMetadata.CreateFromFile(systemDrive + @":\directory_that_does_not_exists\file_that_does_not_exists.dll"));
Assert.Throws<PathTooLongException>(() => ModuleMetadata.CreateFromFile(systemDrive + @":\" + new string('x', 1000)));
Assert.Throws<IOException>(() => ModuleMetadata.CreateFromFile(Environment.GetFolderPath(Environment.SpecialFolder.Windows)));
}
[Fact]
public void Disposal()
{
var md = ModuleMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
md.Dispose();
Assert.Throws<ObjectDisposedException>(() => md.Module);
md.Dispose();
}
[Fact]
public void ImageOwnership()
{
var m = ModuleMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
var copy1 = m.Copy();
var copy2 = copy1.Copy();
Assert.True(m.IsImageOwner, "Metadata should own the image");
Assert.False(copy1.IsImageOwner, "Copy should not own the image");
Assert.False(copy2.IsImageOwner, "Copy should not own the image");
// the image is shared
Assert.NotNull(m.Module);
Assert.Equal(copy1.Module, m.Module);
Assert.Equal(copy2.Module, m.Module);
// dispose copy - no effect on the underlying image or other copies:
copy1.Dispose();
Assert.Throws<ObjectDisposedException>(() => copy1.Module);
Assert.NotNull(m.Module);
Assert.NotNull(copy2.Module);
// dispose the owner - all copies are invalidated:
m.Dispose();
Assert.Throws<ObjectDisposedException>(() => m.Module);
Assert.Throws<ObjectDisposedException>(() => copy1.Module);
Assert.Throws<ObjectDisposedException>(() => copy2.Module);
}
[Fact, WorkItem(2988, "https://github.com/dotnet/roslyn/issues/2988")]
public void EmptyStream()
{
ModuleMetadata.CreateFromStream(new MemoryStream(), PEStreamOptions.Default);
Assert.Throws<BadImageFormatException>(() => ModuleMetadata.CreateFromStream(new MemoryStream(), PEStreamOptions.PrefetchMetadata));
Assert.Throws<BadImageFormatException>(() => ModuleMetadata.CreateFromStream(new MemoryStream(), PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.IO;
using Roslyn.Test.Utilities;
using Xunit;
using System.Collections.Generic;
using System.Reflection.PortableExecutable;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class ModuleMetadataTests : TestBase
{
[Fact]
public unsafe void CreateFromMetadata_Errors()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromMetadata(IntPtr.Zero, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromMetadata((IntPtr)ptr, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromMetadata((IntPtr)ptr, -1); });
fixed (byte* ptr = new byte[] { 1, 2, 3 })
{
var metadata = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, 3);
Assert.Throws<BadImageFormatException>(() => metadata.GetModuleNames());
}
}
[Fact]
public unsafe void CreateFromMetadata_Assembly()
{
var assembly = TestResources.Basic.Members;
PEHeaders h = new PEHeaders(new MemoryStream(assembly));
fixed (byte* ptr = &assembly[h.MetadataStartOffset])
{
var metadata = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize);
Assert.Equal(new AssemblyIdentity("Members"), metadata.Module.ReadAssemblyIdentityOrThrow());
}
}
[Fact]
public unsafe void CreateFromMetadata_Module()
{
var netModule = TestResources.MetadataTests.NetModule01.ModuleCS00;
PEHeaders h = new PEHeaders(new MemoryStream(netModule));
fixed (byte* ptr = &netModule[h.MetadataStartOffset])
{
ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize);
}
}
[Fact]
public unsafe void CreateFromImage()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(IntPtr.Zero, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromImage((IntPtr)ptr, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { fixed (byte* ptr = new byte[] { 1, 2, 3 }) ModuleMetadata.CreateFromImage((IntPtr)ptr, -1); });
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(default(ImmutableArray<byte>)));
IEnumerable<byte> enumerableImage = null;
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(enumerableImage));
byte[] arrayImage = null;
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromImage(arrayImage));
// It's not particularly important that this not throw. The parsing of the metadata is now lazy, and the result is that an exception
// will be thrown when something tugs on the metadata later.
ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Invalid.EmptyModuleTable);
}
[Fact]
public void CreateFromImageStream()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromStream(peStream: null));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromStream(new TestStream(canRead: false, canSeek: true)));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromStream(new TestStream(canRead: true, canSeek: false)));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void CreateFromFile()
{
Assert.Throws<ArgumentNullException>(() => ModuleMetadata.CreateFromFile((string)null));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromFile(""));
Assert.Throws<ArgumentException>(() => ModuleMetadata.CreateFromFile(@"c:\*"));
char systemDrive = Environment.GetFolderPath(Environment.SpecialFolder.Windows)[0];
Assert.Throws<IOException>(() => ModuleMetadata.CreateFromFile(@"http://goo.bar"));
Assert.Throws<FileNotFoundException>(() => ModuleMetadata.CreateFromFile(systemDrive + @":\file_that_does_not_exists.dll"));
Assert.Throws<FileNotFoundException>(() => ModuleMetadata.CreateFromFile(systemDrive + @":\directory_that_does_not_exists\file_that_does_not_exists.dll"));
Assert.Throws<PathTooLongException>(() => ModuleMetadata.CreateFromFile(systemDrive + @":\" + new string('x', 1000)));
Assert.Throws<IOException>(() => ModuleMetadata.CreateFromFile(Environment.GetFolderPath(Environment.SpecialFolder.Windows)));
}
[Fact]
public void Disposal()
{
var md = ModuleMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
md.Dispose();
Assert.Throws<ObjectDisposedException>(() => md.Module);
md.Dispose();
}
[Fact]
public void ImageOwnership()
{
var m = ModuleMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
var copy1 = m.Copy();
var copy2 = copy1.Copy();
Assert.True(m.IsImageOwner, "Metadata should own the image");
Assert.False(copy1.IsImageOwner, "Copy should not own the image");
Assert.False(copy2.IsImageOwner, "Copy should not own the image");
// the image is shared
Assert.NotNull(m.Module);
Assert.Equal(copy1.Module, m.Module);
Assert.Equal(copy2.Module, m.Module);
// dispose copy - no effect on the underlying image or other copies:
copy1.Dispose();
Assert.Throws<ObjectDisposedException>(() => copy1.Module);
Assert.NotNull(m.Module);
Assert.NotNull(copy2.Module);
// dispose the owner - all copies are invalidated:
m.Dispose();
Assert.Throws<ObjectDisposedException>(() => m.Module);
Assert.Throws<ObjectDisposedException>(() => copy1.Module);
Assert.Throws<ObjectDisposedException>(() => copy2.Module);
}
[Fact, WorkItem(2988, "https://github.com/dotnet/roslyn/issues/2988")]
public void EmptyStream()
{
ModuleMetadata.CreateFromStream(new MemoryStream(), PEStreamOptions.Default);
Assert.Throws<BadImageFormatException>(() => ModuleMetadata.CreateFromStream(new MemoryStream(), PEStreamOptions.PrefetchMetadata));
Assert.Throws<BadImageFormatException>(() => ModuleMetadata.CreateFromStream(new MemoryStream(), PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage));
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/Core/Def/HACK_ThemeColorFixer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ObjectModel;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices
{
/// <summary>
/// This class works around the fact that shell theme changes are not fully propagated into an
/// editor classification format map unless a classification type is registered as a font and
/// color item in that format map's font and color category. So, for example, the "Keyword"
/// classification type in the "tooltip" classification format map is never is never updated
/// from its default blue. As a work around, we listen to <see cref="IClassificationFormatMap.ClassificationFormatMappingChanged"/>
/// and update the classification format maps that we care about.
/// </summary>
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(ContentTypeNames.RoslynContentType)]
[TextViewRole(PredefinedTextViewRoles.Analyzable)]
internal sealed class HACK_ThemeColorFixer : IWpfTextViewConnectionListener
{
private readonly IClassificationTypeRegistryService _classificationTypeRegistryService;
private readonly IClassificationFormatMapService _classificationFormatMapService;
private bool _done;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public HACK_ThemeColorFixer(
IClassificationTypeRegistryService classificationTypeRegistryService,
IClassificationFormatMapService classificationFormatMapService)
{
_classificationTypeRegistryService = classificationTypeRegistryService;
_classificationFormatMapService = classificationFormatMapService;
// Note: We never unsubscribe from this event. This service lives for the lifetime of VS.
_classificationFormatMapService.GetClassificationFormatMap("text").ClassificationFormatMappingChanged += TextFormatMap_ClassificationFormatMappingChanged;
}
private void TextFormatMap_ClassificationFormatMappingChanged(object sender, EventArgs e)
=> VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors);
public void RefreshThemeColors()
{
var textFormatMap = _classificationFormatMapService.GetClassificationFormatMap("text");
var tooltipFormatMap = _classificationFormatMapService.GetClassificationFormatMap("tooltip");
UpdateForegroundColors(textFormatMap, tooltipFormatMap);
}
private void UpdateForegroundColors(
IClassificationFormatMap sourceFormatMap,
IClassificationFormatMap targetFormatMap)
{
UpdateForegroundColor(ClassificationTypeNames.Comment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ExcludedCode, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Identifier, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Keyword, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ControlKeyword, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.NumericLiteral, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.StringLiteral, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeQuotes, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeValue, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentDelimiter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentComment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentCDataSection, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexComment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexCharacterClass, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexQuantifier, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexAnchor, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexAlternation, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexGrouping, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexOtherEscape, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexSelfEscapedCharacter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.PreprocessorKeyword, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.PreprocessorText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Operator, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.OperatorOverloaded, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Punctuation, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ClassName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RecordClassName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.StructName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.InterfaceName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.DelegateName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.EnumName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.TypeParameterName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ModuleName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.FieldName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.EnumMemberName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ConstantName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.LocalName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ParameterName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.MethodName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ExtensionMethodName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.PropertyName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.EventName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.NamespaceName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.LabelName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.VerbatimStringLiteral, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.StringEscapeCharacter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralProcessingInstruction, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEmbeddedExpression, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralDelimiter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralComment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralCDataSection, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeValue, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeQuotes, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEntityReference, sourceFormatMap, targetFormatMap);
}
private void UpdateForegroundColor(
string classificationTypeName,
IClassificationFormatMap sourceFormatMap,
IClassificationFormatMap targetFormatMap)
{
var classificationType = _classificationTypeRegistryService.GetClassificationType(classificationTypeName);
if (classificationType == null)
{
return;
}
var sourceProps = sourceFormatMap.GetTextProperties(classificationType);
var targetProps = targetFormatMap.GetTextProperties(classificationType);
targetProps = targetProps.SetForegroundBrush(sourceProps.ForegroundBrush);
targetFormatMap.SetTextProperties(classificationType, targetProps);
}
public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
// DevDiv https://devdiv.visualstudio.com/DevDiv/_workitems/edit/130129:
//
// This needs to be scheduled after editor has been composed. Otherwise
// it may cause UI delays by composing the editor before it is needed
// by the rest of VS.
if (!_done)
{
_done = true;
VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors);
}
}
public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ObjectModel;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices
{
/// <summary>
/// This class works around the fact that shell theme changes are not fully propagated into an
/// editor classification format map unless a classification type is registered as a font and
/// color item in that format map's font and color category. So, for example, the "Keyword"
/// classification type in the "tooltip" classification format map is never is never updated
/// from its default blue. As a work around, we listen to <see cref="IClassificationFormatMap.ClassificationFormatMappingChanged"/>
/// and update the classification format maps that we care about.
/// </summary>
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(ContentTypeNames.RoslynContentType)]
[TextViewRole(PredefinedTextViewRoles.Analyzable)]
internal sealed class HACK_ThemeColorFixer : IWpfTextViewConnectionListener
{
private readonly IClassificationTypeRegistryService _classificationTypeRegistryService;
private readonly IClassificationFormatMapService _classificationFormatMapService;
private bool _done;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public HACK_ThemeColorFixer(
IClassificationTypeRegistryService classificationTypeRegistryService,
IClassificationFormatMapService classificationFormatMapService)
{
_classificationTypeRegistryService = classificationTypeRegistryService;
_classificationFormatMapService = classificationFormatMapService;
// Note: We never unsubscribe from this event. This service lives for the lifetime of VS.
_classificationFormatMapService.GetClassificationFormatMap("text").ClassificationFormatMappingChanged += TextFormatMap_ClassificationFormatMappingChanged;
}
private void TextFormatMap_ClassificationFormatMappingChanged(object sender, EventArgs e)
=> VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors);
public void RefreshThemeColors()
{
var textFormatMap = _classificationFormatMapService.GetClassificationFormatMap("text");
var tooltipFormatMap = _classificationFormatMapService.GetClassificationFormatMap("tooltip");
UpdateForegroundColors(textFormatMap, tooltipFormatMap);
}
private void UpdateForegroundColors(
IClassificationFormatMap sourceFormatMap,
IClassificationFormatMap targetFormatMap)
{
UpdateForegroundColor(ClassificationTypeNames.Comment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ExcludedCode, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Identifier, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Keyword, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ControlKeyword, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.NumericLiteral, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.StringLiteral, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeQuotes, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeValue, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentDelimiter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentComment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentCDataSection, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexComment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexCharacterClass, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexQuantifier, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexAnchor, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexAlternation, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexGrouping, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexOtherEscape, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RegexSelfEscapedCharacter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.PreprocessorKeyword, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.PreprocessorText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Operator, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.OperatorOverloaded, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.Punctuation, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ClassName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.RecordClassName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.StructName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.InterfaceName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.DelegateName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.EnumName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.TypeParameterName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ModuleName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.FieldName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.EnumMemberName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ConstantName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.LocalName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ParameterName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.MethodName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.ExtensionMethodName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.PropertyName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.EventName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.NamespaceName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.LabelName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.VerbatimStringLiteral, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.StringEscapeCharacter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralText, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralProcessingInstruction, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEmbeddedExpression, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralDelimiter, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralComment, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralCDataSection, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeValue, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeQuotes, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeName, sourceFormatMap, targetFormatMap);
UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEntityReference, sourceFormatMap, targetFormatMap);
}
private void UpdateForegroundColor(
string classificationTypeName,
IClassificationFormatMap sourceFormatMap,
IClassificationFormatMap targetFormatMap)
{
var classificationType = _classificationTypeRegistryService.GetClassificationType(classificationTypeName);
if (classificationType == null)
{
return;
}
var sourceProps = sourceFormatMap.GetTextProperties(classificationType);
var targetProps = targetFormatMap.GetTextProperties(classificationType);
targetProps = targetProps.SetForegroundBrush(sourceProps.ForegroundBrush);
targetFormatMap.SetTextProperties(classificationType, targetProps);
}
public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
// DevDiv https://devdiv.visualstudio.com/DevDiv/_workitems/edit/130129:
//
// This needs to be scheduled after editor has been composed. Otherwise
// it may cause UI delays by composing the editor before it is needed
// by the rest of VS.
if (!_done)
{
_done = true;
VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors);
}
}
public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/CodeAnalysisTest/Symbols/NullabilityInfoTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis
{
[CompilerTrait(CompilerFeature.NullableReferenceTypes)]
public class NullabilityInfoTests
{
[Fact]
public void Equality()
{
assertEqualsAndHashCode(default(NullabilityInfo), default(NullabilityInfo), equal: true);
assertEqualsAndHashCode(new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
equal: true);
assertEqualsAndHashCode(new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
new NullabilityInfo(NullableAnnotation.NotAnnotated, NullableFlowState.NotNull),
equal: false);
assertEqualsAndHashCode(new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.MaybeNull),
new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
equal: false);
void assertEqualsAndHashCode(NullabilityInfo n1, NullabilityInfo n2, bool equal)
{
if (equal)
{
Assert.Equal(n1, n2);
Assert.Equal(n1.GetHashCode(), n2.GetHashCode());
}
else
{
Assert.NotEqual(n1, n2);
Assert.NotEqual(n1.GetHashCode(), n2.GetHashCode());
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis
{
[CompilerTrait(CompilerFeature.NullableReferenceTypes)]
public class NullabilityInfoTests
{
[Fact]
public void Equality()
{
assertEqualsAndHashCode(default(NullabilityInfo), default(NullabilityInfo), equal: true);
assertEqualsAndHashCode(new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
equal: true);
assertEqualsAndHashCode(new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
new NullabilityInfo(NullableAnnotation.NotAnnotated, NullableFlowState.NotNull),
equal: false);
assertEqualsAndHashCode(new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.MaybeNull),
new NullabilityInfo(NullableAnnotation.Annotated, NullableFlowState.NotNull),
equal: false);
void assertEqualsAndHashCode(NullabilityInfo n1, NullabilityInfo n2, bool equal)
{
if (equal)
{
Assert.Equal(n1, n2);
Assert.Equal(n1.GetHashCode(), n2.GetHashCode());
}
else
{
Assert.NotEqual(n1, n2);
Assert.NotEqual(n1.GetHashCode(), n2.GetHashCode());
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_Declarations_AllDeclarations.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync(
Project project, string name, bool ignoreCase, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.Create(name, ignoreCase);
var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync(
project, query, SymbolFilter.All, cancellationToken).ConfigureAwait(false);
return declarations;
}
/// <summary>
/// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync(
Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.Create(name, ignoreCase);
var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync(
project, query, filter, cancellationToken).ConfigureAwait(false);
return declarations;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync(
Project project, string name, bool ignoreCase, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.Create(name, ignoreCase);
var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync(
project, query, SymbolFilter.All, cancellationToken).ConfigureAwait(false);
return declarations;
}
/// <summary>
/// Find the declared symbols from either source, referenced projects or metadata assemblies with the specified name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindDeclarationsAsync(
Project project, string name, bool ignoreCase, SymbolFilter filter, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.Create(name, ignoreCase);
var declarations = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync(
project, query, filter, cancellationToken).ConfigureAwait(false);
return declarations;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal partial class TriviaDataFactory
{
private struct CodeShapeAnalyzer
{
private readonly FormattingContext _context;
private readonly AnalyzerConfigOptions _options;
private readonly TriviaList _triviaList;
private int _indentation;
private bool _hasTrailingSpace;
private int _lastLineBreakIndex;
private bool _touchedNoisyCharacterOnCurrentLine;
public static bool ShouldFormatMultiLine(FormattingContext context, bool firstTriviaInTree, TriviaList triviaList)
{
var analyzer = new CodeShapeAnalyzer(context, firstTriviaInTree, triviaList);
return analyzer.ShouldFormat();
}
public static bool ShouldFormatSingleLine(TriviaList list)
{
foreach (var trivia in list)
{
Contract.ThrowIfTrue(trivia.Kind() == SyntaxKind.EndOfLineTrivia);
Contract.ThrowIfTrue(trivia.Kind() == SyntaxKind.SkippedTokensTrivia);
Contract.ThrowIfTrue(trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia);
// if it contains elastic trivia, always format
if (trivia.IsElastic())
{
return true;
}
if (trivia.Kind() == SyntaxKind.WhitespaceTrivia)
{
Debug.Assert(trivia.ToString() == trivia.ToFullString());
var text = trivia.ToString();
if (text.IndexOf('\t') >= 0)
{
return true;
}
}
// we don't touch space between two tokens on a single line that contains
// multiline comments between them
if (trivia.IsRegularOrDocComment())
{
return false;
}
if (trivia.Kind() == SyntaxKind.RegionDirectiveTrivia ||
trivia.Kind() == SyntaxKind.EndRegionDirectiveTrivia ||
SyntaxFacts.IsPreprocessorDirective(trivia.Kind()))
{
return false;
}
}
return true;
}
public static bool ContainsSkippedTokensOrText(TriviaList list)
{
foreach (var trivia in list)
{
if (trivia.Kind() == SyntaxKind.SkippedTokensTrivia ||
trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia)
{
return true;
}
}
return false;
}
private CodeShapeAnalyzer(FormattingContext context, bool firstTriviaInTree, TriviaList triviaList)
{
_context = context;
_options = context.Options;
_triviaList = triviaList;
_indentation = 0;
_hasTrailingSpace = false;
_lastLineBreakIndex = firstTriviaInTree ? 0 : -1;
_touchedNoisyCharacterOnCurrentLine = false;
}
private bool UseIndentation
{
get { return _lastLineBreakIndex >= 0; }
}
private static bool OnElastic(SyntaxTrivia trivia)
{
// if it contains elastic trivia, always format
return trivia.IsElastic();
}
private bool OnWhitespace(SyntaxTrivia trivia)
{
if (trivia.Kind() != SyntaxKind.WhitespaceTrivia)
{
return false;
}
// there was noisy char after end of line trivia
if (!this.UseIndentation || _touchedNoisyCharacterOnCurrentLine)
{
_hasTrailingSpace = true;
return false;
}
// right after end of line trivia. calculate indentation for current line
Debug.Assert(trivia.ToString() == trivia.ToFullString());
var text = trivia.ToString();
// if text contains tab, we will give up perf optimization and use more expensive one to see whether we need to replace this trivia
if (text.IndexOf('\t') >= 0)
{
return true;
}
_indentation += text.ConvertTabToSpace(_options.GetOption(FormattingOptions2.TabSize), _indentation, text.Length);
return false;
}
private bool OnEndOfLine(SyntaxTrivia trivia, int currentIndex)
{
if (trivia.Kind() != SyntaxKind.EndOfLineTrivia)
{
return false;
}
// end of line trivia right after whitespace trivia
if (_hasTrailingSpace)
{
// has trailing whitespace
return true;
}
// empty line with spaces. remove it.
if (_indentation > 0 && !_touchedNoisyCharacterOnCurrentLine)
{
return true;
}
ResetStateAfterNewLine(currentIndex);
return false;
}
private void ResetStateAfterNewLine(int currentIndex)
{
// reset states for current line
_indentation = 0;
_touchedNoisyCharacterOnCurrentLine = false;
_hasTrailingSpace = false;
// remember last line break index
_lastLineBreakIndex = currentIndex;
}
private bool OnComment(SyntaxTrivia trivia)
{
if (!trivia.IsRegularOrDocComment())
{
return false;
}
// check whether indentation are right
if (this.UseIndentation && _indentation != _context.GetBaseIndentation(trivia.SpanStart))
{
// comment has wrong indentation
return true;
}
// go deep down for single line documentation comment
if (trivia.IsSingleLineDocComment() &&
ShouldFormatSingleLineDocumentationComment(_indentation, _options.GetOption(FormattingOptions2.TabSize), trivia))
{
return true;
}
return false;
}
private static bool OnSkippedTokensOrText(SyntaxTrivia trivia)
{
if (trivia.Kind() != SyntaxKind.SkippedTokensTrivia &&
trivia.Kind() != SyntaxKind.PreprocessingMessageTrivia)
{
return false;
}
throw ExceptionUtilities.Unreachable;
}
private bool OnRegion(SyntaxTrivia trivia, int currentIndex)
{
if (trivia.Kind() != SyntaxKind.RegionDirectiveTrivia &&
trivia.Kind() != SyntaxKind.EndRegionDirectiveTrivia)
{
return false;
}
if (!this.UseIndentation)
{
return true;
}
if (_indentation != _context.GetBaseIndentation(trivia.SpanStart))
{
return true;
}
ResetStateAfterNewLine(currentIndex);
return false;
}
private bool OnPreprocessor(SyntaxTrivia trivia, int currentIndex)
{
if (!SyntaxFacts.IsPreprocessorDirective(trivia.Kind()))
{
return false;
}
if (!this.UseIndentation)
{
return true;
}
// preprocessor must be at from column 0
if (_indentation != 0)
{
return true;
}
ResetStateAfterNewLine(currentIndex);
return false;
}
private bool OnTouchedNoisyCharacter(SyntaxTrivia trivia)
{
if (trivia.IsElastic() ||
trivia.Kind() == SyntaxKind.WhitespaceTrivia ||
trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return false;
}
_touchedNoisyCharacterOnCurrentLine = true;
_hasTrailingSpace = false;
return false;
}
private bool ShouldFormat()
{
var index = -1;
foreach (var trivia in _triviaList)
{
index++;
// order in which these methods run has a side effect. don't change the order
// each method run
if (OnElastic(trivia) ||
OnWhitespace(trivia) ||
OnEndOfLine(trivia, index) ||
OnTouchedNoisyCharacter(trivia) ||
OnComment(trivia) ||
OnSkippedTokensOrText(trivia) ||
OnRegion(trivia, index) ||
OnPreprocessor(trivia, index) ||
OnDisabledTextTrivia(trivia, index))
{
return true;
}
}
return false;
}
private bool OnDisabledTextTrivia(SyntaxTrivia trivia, int index)
{
if (trivia.IsKind(SyntaxKind.DisabledTextTrivia))
{
var triviaString = trivia.ToString();
if (!string.IsNullOrEmpty(triviaString) && SyntaxFacts.IsNewLine(triviaString.Last()))
{
ResetStateAfterNewLine(index);
}
}
return false;
}
private static bool ShouldFormatSingleLineDocumentationComment(int indentation, int tabSize, SyntaxTrivia trivia)
{
Debug.Assert(trivia.HasStructure);
var xmlComment = (DocumentationCommentTriviaSyntax)trivia.GetStructure()!;
var sawFirstOne = false;
foreach (var token in xmlComment.DescendantTokens())
{
foreach (var xmlTrivia in token.LeadingTrivia)
{
if (xmlTrivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia)
{
// skip first one since its leading whitespace will belong to syntax tree's syntax token
// not xml doc comment's token
if (!sawFirstOne)
{
sawFirstOne = true;
break;
}
var xmlCommentText = xmlTrivia.ToString();
// "///" == 3.
if (xmlCommentText.GetColumnFromLineOffset(xmlCommentText.Length - 3, tabSize) != indentation)
{
return true;
}
break;
}
}
}
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal partial class TriviaDataFactory
{
private struct CodeShapeAnalyzer
{
private readonly FormattingContext _context;
private readonly AnalyzerConfigOptions _options;
private readonly TriviaList _triviaList;
private int _indentation;
private bool _hasTrailingSpace;
private int _lastLineBreakIndex;
private bool _touchedNoisyCharacterOnCurrentLine;
public static bool ShouldFormatMultiLine(FormattingContext context, bool firstTriviaInTree, TriviaList triviaList)
{
var analyzer = new CodeShapeAnalyzer(context, firstTriviaInTree, triviaList);
return analyzer.ShouldFormat();
}
public static bool ShouldFormatSingleLine(TriviaList list)
{
foreach (var trivia in list)
{
Contract.ThrowIfTrue(trivia.Kind() == SyntaxKind.EndOfLineTrivia);
Contract.ThrowIfTrue(trivia.Kind() == SyntaxKind.SkippedTokensTrivia);
Contract.ThrowIfTrue(trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia);
// if it contains elastic trivia, always format
if (trivia.IsElastic())
{
return true;
}
if (trivia.Kind() == SyntaxKind.WhitespaceTrivia)
{
Debug.Assert(trivia.ToString() == trivia.ToFullString());
var text = trivia.ToString();
if (text.IndexOf('\t') >= 0)
{
return true;
}
}
// we don't touch space between two tokens on a single line that contains
// multiline comments between them
if (trivia.IsRegularOrDocComment())
{
return false;
}
if (trivia.Kind() == SyntaxKind.RegionDirectiveTrivia ||
trivia.Kind() == SyntaxKind.EndRegionDirectiveTrivia ||
SyntaxFacts.IsPreprocessorDirective(trivia.Kind()))
{
return false;
}
}
return true;
}
public static bool ContainsSkippedTokensOrText(TriviaList list)
{
foreach (var trivia in list)
{
if (trivia.Kind() == SyntaxKind.SkippedTokensTrivia ||
trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia)
{
return true;
}
}
return false;
}
private CodeShapeAnalyzer(FormattingContext context, bool firstTriviaInTree, TriviaList triviaList)
{
_context = context;
_options = context.Options;
_triviaList = triviaList;
_indentation = 0;
_hasTrailingSpace = false;
_lastLineBreakIndex = firstTriviaInTree ? 0 : -1;
_touchedNoisyCharacterOnCurrentLine = false;
}
private bool UseIndentation
{
get { return _lastLineBreakIndex >= 0; }
}
private static bool OnElastic(SyntaxTrivia trivia)
{
// if it contains elastic trivia, always format
return trivia.IsElastic();
}
private bool OnWhitespace(SyntaxTrivia trivia)
{
if (trivia.Kind() != SyntaxKind.WhitespaceTrivia)
{
return false;
}
// there was noisy char after end of line trivia
if (!this.UseIndentation || _touchedNoisyCharacterOnCurrentLine)
{
_hasTrailingSpace = true;
return false;
}
// right after end of line trivia. calculate indentation for current line
Debug.Assert(trivia.ToString() == trivia.ToFullString());
var text = trivia.ToString();
// if text contains tab, we will give up perf optimization and use more expensive one to see whether we need to replace this trivia
if (text.IndexOf('\t') >= 0)
{
return true;
}
_indentation += text.ConvertTabToSpace(_options.GetOption(FormattingOptions2.TabSize), _indentation, text.Length);
return false;
}
private bool OnEndOfLine(SyntaxTrivia trivia, int currentIndex)
{
if (trivia.Kind() != SyntaxKind.EndOfLineTrivia)
{
return false;
}
// end of line trivia right after whitespace trivia
if (_hasTrailingSpace)
{
// has trailing whitespace
return true;
}
// empty line with spaces. remove it.
if (_indentation > 0 && !_touchedNoisyCharacterOnCurrentLine)
{
return true;
}
ResetStateAfterNewLine(currentIndex);
return false;
}
private void ResetStateAfterNewLine(int currentIndex)
{
// reset states for current line
_indentation = 0;
_touchedNoisyCharacterOnCurrentLine = false;
_hasTrailingSpace = false;
// remember last line break index
_lastLineBreakIndex = currentIndex;
}
private bool OnComment(SyntaxTrivia trivia)
{
if (!trivia.IsRegularOrDocComment())
{
return false;
}
// check whether indentation are right
if (this.UseIndentation && _indentation != _context.GetBaseIndentation(trivia.SpanStart))
{
// comment has wrong indentation
return true;
}
// go deep down for single line documentation comment
if (trivia.IsSingleLineDocComment() &&
ShouldFormatSingleLineDocumentationComment(_indentation, _options.GetOption(FormattingOptions2.TabSize), trivia))
{
return true;
}
return false;
}
private static bool OnSkippedTokensOrText(SyntaxTrivia trivia)
{
if (trivia.Kind() != SyntaxKind.SkippedTokensTrivia &&
trivia.Kind() != SyntaxKind.PreprocessingMessageTrivia)
{
return false;
}
throw ExceptionUtilities.Unreachable;
}
private bool OnRegion(SyntaxTrivia trivia, int currentIndex)
{
if (trivia.Kind() != SyntaxKind.RegionDirectiveTrivia &&
trivia.Kind() != SyntaxKind.EndRegionDirectiveTrivia)
{
return false;
}
if (!this.UseIndentation)
{
return true;
}
if (_indentation != _context.GetBaseIndentation(trivia.SpanStart))
{
return true;
}
ResetStateAfterNewLine(currentIndex);
return false;
}
private bool OnPreprocessor(SyntaxTrivia trivia, int currentIndex)
{
if (!SyntaxFacts.IsPreprocessorDirective(trivia.Kind()))
{
return false;
}
if (!this.UseIndentation)
{
return true;
}
// preprocessor must be at from column 0
if (_indentation != 0)
{
return true;
}
ResetStateAfterNewLine(currentIndex);
return false;
}
private bool OnTouchedNoisyCharacter(SyntaxTrivia trivia)
{
if (trivia.IsElastic() ||
trivia.Kind() == SyntaxKind.WhitespaceTrivia ||
trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return false;
}
_touchedNoisyCharacterOnCurrentLine = true;
_hasTrailingSpace = false;
return false;
}
private bool ShouldFormat()
{
var index = -1;
foreach (var trivia in _triviaList)
{
index++;
// order in which these methods run has a side effect. don't change the order
// each method run
if (OnElastic(trivia) ||
OnWhitespace(trivia) ||
OnEndOfLine(trivia, index) ||
OnTouchedNoisyCharacter(trivia) ||
OnComment(trivia) ||
OnSkippedTokensOrText(trivia) ||
OnRegion(trivia, index) ||
OnPreprocessor(trivia, index) ||
OnDisabledTextTrivia(trivia, index))
{
return true;
}
}
return false;
}
private bool OnDisabledTextTrivia(SyntaxTrivia trivia, int index)
{
if (trivia.IsKind(SyntaxKind.DisabledTextTrivia))
{
var triviaString = trivia.ToString();
if (!string.IsNullOrEmpty(triviaString) && SyntaxFacts.IsNewLine(triviaString.Last()))
{
ResetStateAfterNewLine(index);
}
}
return false;
}
private static bool ShouldFormatSingleLineDocumentationComment(int indentation, int tabSize, SyntaxTrivia trivia)
{
Debug.Assert(trivia.HasStructure);
var xmlComment = (DocumentationCommentTriviaSyntax)trivia.GetStructure()!;
var sawFirstOne = false;
foreach (var token in xmlComment.DescendantTokens())
{
foreach (var xmlTrivia in token.LeadingTrivia)
{
if (xmlTrivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia)
{
// skip first one since its leading whitespace will belong to syntax tree's syntax token
// not xml doc comment's token
if (!sawFirstOne)
{
sawFirstOne = true;
break;
}
var xmlCommentText = xmlTrivia.ToString();
// "///" == 3.
if (xmlCommentText.GetColumnFromLineOffset(xmlCommentText.Length - 3, tabSize) != indentation)
{
return true;
}
break;
}
}
}
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/ConvertForEachToFor/AbstractConvertForEachToForCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ConvertForEachToFor
{
internal abstract class AbstractConvertForEachToForCodeRefactoringProvider<
TStatementSyntax,
TForEachStatement> : CodeRefactoringProvider
where TStatementSyntax : SyntaxNode
where TForEachStatement : TStatementSyntax
{
private const string get_Count = nameof(get_Count);
private const string get_Item = nameof(get_Item);
private const string Length = nameof(Array.Length);
private const string Count = nameof(IList.Count);
private static readonly ImmutableArray<string> s_KnownInterfaceNames =
ImmutableArray.Create(typeof(IList<>).FullName!, typeof(IReadOnlyList<>).FullName!, typeof(IList).FullName!);
protected bool IsForEachVariableWrittenInside { get; private set; }
protected abstract string Title { get; }
protected abstract bool ValidLocation(ForEachInfo foreachInfo);
protected abstract (SyntaxNode start, SyntaxNode end) GetForEachBody(TForEachStatement foreachStatement);
protected abstract void ConvertToForStatement(
SemanticModel model, ForEachInfo info, SyntaxEditor editor, CancellationToken cancellationToken);
protected abstract bool IsValid(TForEachStatement foreachNode);
/// <summary>
/// Perform language specific checks if the conversion is supported.
/// C#: Currently nothing blocking a conversion
/// VB: Nested foreach loops sharing a single Next statement, Next statements with multiple variables and next statements
/// not using the loop variable are not supported.
/// </summary>
protected abstract bool IsSupported(ILocalSymbol foreachVariable, IForEachLoopOperation forEachOperation, TForEachStatement foreachStatement);
protected static SyntaxAnnotation CreateWarningAnnotation()
=> WarningAnnotation.Create(FeaturesResources.Warning_colon_semantics_may_change_when_converting_statement);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, _, cancellationToken) = context;
var foreachStatement = await context.TryGetRelevantNodeAsync<TForEachStatement>().ConfigureAwait(false);
if (foreachStatement == null || !IsValid(foreachStatement))
{
return;
}
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var semanticFact = document.GetRequiredLanguageService<ISemanticFactsService>();
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var foreachInfo = GetForeachInfo(semanticFact, model, foreachStatement, cancellationToken);
if (foreachInfo == null || !ValidLocation(foreachInfo))
{
return;
}
context.RegisterRefactoring(
new ForEachToForCodeAction(
Title,
c => ConvertForeachToForAsync(document, foreachInfo, c)),
foreachStatement.Span);
}
protected static SyntaxToken CreateUniqueName(
ISemanticFactsService semanticFacts, SemanticModel model, SyntaxNode location, string baseName, CancellationToken cancellationToken)
=> semanticFacts.GenerateUniqueLocalName(model, location, containerOpt: null, baseName, cancellationToken);
protected static SyntaxNode GetCollectionVariableName(
SemanticModel model, SyntaxGenerator generator,
ForEachInfo foreachInfo, SyntaxNode foreachCollectionExpression, CancellationToken cancellationToken)
{
if (foreachInfo.RequireCollectionStatement)
{
return generator.IdentifierName(
CreateUniqueName(foreachInfo.SemanticFacts,
model, foreachInfo.ForEachStatement, foreachInfo.CollectionNameSuggestion, cancellationToken));
}
return foreachCollectionExpression.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation);
}
protected static void IntroduceCollectionStatement(
ForEachInfo foreachInfo, SyntaxEditor editor,
SyntaxNode type, SyntaxNode foreachCollectionExpression, SyntaxNode collectionVariable)
{
if (!foreachInfo.RequireCollectionStatement)
{
return;
}
// TODO: refactor introduce variable refactoring to real service and use that service here to introduce local variable
var generator = editor.Generator;
// attach rename annotation to control variable
var collectionVariableToken = generator.Identifier(collectionVariable.ToString()).WithAdditionalAnnotations(RenameAnnotation.Create());
// this expression is from user code. don't simplify this.
var expression = foreachCollectionExpression.WithoutAnnotations(SimplificationHelpers.DontSimplifyAnnotation);
var collectionStatement = generator.LocalDeclarationStatement(
type,
collectionVariableToken,
foreachInfo.RequireExplicitCastInterface
? generator.CastExpression(foreachInfo.ExplicitCastInterface, expression) : expression);
// attach trivia to right place
collectionStatement = collectionStatement.WithLeadingTrivia(foreachInfo.ForEachStatement.GetFirstToken().LeadingTrivia);
editor.InsertBefore(foreachInfo.ForEachStatement, collectionStatement);
}
protected static TStatementSyntax AddItemVariableDeclaration(
SyntaxGenerator generator, SyntaxNode type, SyntaxToken foreachVariable,
ITypeSymbol castType, SyntaxNode collectionVariable, SyntaxToken indexVariable)
{
var memberAccess = generator.ElementAccessExpression(
collectionVariable, generator.IdentifierName(indexVariable));
if (castType != null)
{
memberAccess = generator.CastExpression(castType, memberAccess);
}
var localDecl = generator.LocalDeclarationStatement(
type, foreachVariable, memberAccess);
return (TStatementSyntax)localDecl.WithAdditionalAnnotations(Formatter.Annotation);
}
private ForEachInfo? GetForeachInfo(
ISemanticFactsService semanticFact, SemanticModel model,
TForEachStatement foreachStatement, CancellationToken cancellationToken)
{
if (model.GetOperation(foreachStatement, cancellationToken) is not IForEachLoopOperation operation || operation.Locals.Length != 1)
{
return null;
}
var foreachVariable = operation.Locals[0];
if (foreachVariable == null)
{
return null;
}
// Perform language specific checks if the foreachStatement
// is using unsupported features
if (!IsSupported(foreachVariable, operation, foreachStatement))
{
return null;
}
IsForEachVariableWrittenInside = CheckIfForEachVariableIsWrittenInside(model, foreachVariable, foreachStatement);
var foreachCollection = RemoveImplicitConversion(operation.Collection);
if (foreachCollection == null)
{
return null;
}
GetInterfaceInfo(model, foreachVariable, foreachCollection,
out var explicitCastInterface, out var collectionNameSuggestion, out var countName);
if (collectionNameSuggestion == null || countName == null)
{
return null;
}
var requireCollectionStatement = CheckRequireCollectionStatement(foreachCollection);
return new ForEachInfo(
semanticFact, collectionNameSuggestion, countName, explicitCastInterface,
foreachVariable.Type, requireCollectionStatement, foreachStatement);
}
private static void GetInterfaceInfo(
SemanticModel model, ILocalSymbol foreachVariable, IOperation foreachCollection,
out ITypeSymbol? explicitCastInterface, out string? collectionNameSuggestion, out string? countName)
{
explicitCastInterface = null;
collectionNameSuggestion = null;
countName = null;
// go through list of types and interfaces to find out right set;
var foreachType = foreachVariable.Type;
if (IsNullOrErrorType(foreachType))
{
return;
}
var collectionType = foreachCollection.Type;
if (IsNullOrErrorType(collectionType))
{
return;
}
// go through explicit types first.
// check array case
if (collectionType is IArrayTypeSymbol array)
{
if (array.Rank != 1)
{
// array type supports IList and other interfaces, but implementation
// only supports Rank == 1 case. other case, it will throw on runtime
// even if there is no error on compile time.
// we explicitly mark that we only support Rank == 1 case
return;
}
if (!IsExchangable(array.ElementType, foreachType, model.Compilation))
{
return;
}
collectionNameSuggestion = "array";
explicitCastInterface = null;
countName = Length;
return;
}
// check string case
if (collectionType.SpecialType == SpecialType.System_String)
{
var charType = model.Compilation.GetSpecialType(SpecialType.System_Char);
if (!IsExchangable(charType, foreachType, model.Compilation))
{
return;
}
collectionNameSuggestion = "str";
explicitCastInterface = null;
countName = Length;
return;
}
// check ImmutableArray case
if (collectionType.OriginalDefinition.Equals(model.Compilation.GetTypeByMetadataName(typeof(ImmutableArray<>).FullName!)))
{
var indexer = GetInterfaceMember(collectionType, get_Item);
if (indexer != null)
{
if (!IsExchangable(indexer.ReturnType, foreachType, model.Compilation))
{
return;
}
collectionNameSuggestion = "array";
explicitCastInterface = null;
countName = Length;
return;
}
}
// go through all known interfaces we support next.
var knownCollectionInterfaces = s_KnownInterfaceNames.Select(
s => model.Compilation.GetTypeByMetadataName(s)).Where(t => !IsNullOrErrorType(t));
// for all interfaces, we suggest collection name as "list"
collectionNameSuggestion = "list";
// check type itself is interface case
if (collectionType.TypeKind == TypeKind.Interface && knownCollectionInterfaces.Contains(collectionType.OriginalDefinition))
{
var indexer = GetInterfaceMember(collectionType, get_Item);
if (indexer != null &&
IsExchangable(indexer.ReturnType, foreachType, model.Compilation))
{
explicitCastInterface = null;
countName = Count;
return;
}
}
// check regular cases (implicitly implemented)
ITypeSymbol? explicitInterface = null;
foreach (var current in collectionType.AllInterfaces)
{
if (!knownCollectionInterfaces.Contains(current.OriginalDefinition))
{
continue;
}
// see how the type implements the interface
var countSymbol = GetInterfaceMember(current, get_Count);
var indexerSymbol = GetInterfaceMember(current, get_Item);
if (countSymbol == null || indexerSymbol == null)
{
continue;
}
if (collectionType.FindImplementationForInterfaceMember(countSymbol) is not IMethodSymbol countImpl ||
collectionType.FindImplementationForInterfaceMember(indexerSymbol) is not IMethodSymbol indexerImpl)
{
continue;
}
if (!IsExchangable(indexerImpl.ReturnType, foreachType, model.Compilation))
{
continue;
}
// implicitly implemented!
if (countImpl.ExplicitInterfaceImplementations.IsEmpty &&
indexerImpl.ExplicitInterfaceImplementations.IsEmpty)
{
explicitCastInterface = null;
countName = Count;
return;
}
if (explicitInterface == null)
{
explicitInterface = current;
}
}
// okay, we don't have implicitly implemented one, but we do have explicitly implemented one
if (explicitInterface != null)
{
explicitCastInterface = explicitInterface;
countName = Count;
}
}
private static bool IsExchangable(
ITypeSymbol type1, ITypeSymbol type2, Compilation compilation)
{
return compilation.HasImplicitConversion(type1, type2) ||
compilation.HasImplicitConversion(type2, type1);
}
private static bool IsNullOrErrorType([NotNullWhen(false)] ITypeSymbol? type)
=> type is null or IErrorTypeSymbol;
private static IMethodSymbol? GetInterfaceMember(ITypeSymbol interfaceType, string memberName)
{
foreach (var current in interfaceType.GetAllInterfacesIncludingThis())
{
var members = current.GetMembers(memberName);
if (!members.IsEmpty && members[0] is IMethodSymbol method)
{
return method;
}
}
return null;
}
private static bool CheckRequireCollectionStatement(IOperation operation)
{
// this lists type of references in collection part of foreach we will use
// as it is in
// var element = reference[indexer];
//
// otherwise, we will introduce local variable for the expression first and then
// do "foreach to for" refactoring
//
// foreach(var a in new int[] {....})
// to
// var array = new int[] { ... }
// foreach(var a in array)
switch (operation.Kind)
{
case OperationKind.LocalReference:
case OperationKind.FieldReference:
case OperationKind.ParameterReference:
case OperationKind.PropertyReference:
case OperationKind.ArrayElementReference:
return false;
default:
return true;
}
}
private IOperation RemoveImplicitConversion(IOperation collection)
{
return (collection is IConversionOperation conversion && conversion.IsImplicit)
? RemoveImplicitConversion(conversion.Operand) : collection;
}
private bool CheckIfForEachVariableIsWrittenInside(SemanticModel semanticModel, ISymbol foreachVariable, TForEachStatement foreachStatement)
{
var (start, end) = GetForEachBody(foreachStatement);
if (start == null || end == null)
{
// empty body. this can happen in VB
return false;
}
var dataFlow = semanticModel.AnalyzeDataFlow(start, end);
if (!dataFlow.Succeeded)
{
// if we can't get good analysis, assume it is written
return true;
}
return dataFlow.WrittenInside.Contains(foreachVariable);
}
private async Task<Document> ConvertForeachToForAsync(
Document document,
ForEachInfo foreachInfo,
CancellationToken cancellationToken)
{
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var workspace = document.Project.Solution.Workspace;
var editor = new SyntaxEditor(model.SyntaxTree.GetRoot(cancellationToken), workspace);
ConvertToForStatement(model, foreachInfo, editor, cancellationToken);
var newRoot = editor.GetChangedRoot();
return document.WithSyntaxRoot(newRoot);
}
protected class ForEachInfo
{
public ForEachInfo(
ISemanticFactsService semanticFacts, string collectionNameSuggestion, string countName,
ITypeSymbol? explicitCastInterface, ITypeSymbol forEachElementType,
bool requireCollectionStatement, TForEachStatement forEachStatement)
{
SemanticFacts = semanticFacts;
RequireExplicitCastInterface = explicitCastInterface != null;
CollectionNameSuggestion = collectionNameSuggestion;
CountName = countName;
ExplicitCastInterface = explicitCastInterface;
ForEachElementType = forEachElementType;
RequireCollectionStatement = requireCollectionStatement || (explicitCastInterface != null);
ForEachStatement = forEachStatement;
}
public ISemanticFactsService SemanticFacts { get; }
public bool RequireExplicitCastInterface { get; }
public string CollectionNameSuggestion { get; }
public string CountName { get; }
public ITypeSymbol? ExplicitCastInterface { get; }
public ITypeSymbol ForEachElementType { get; }
public bool RequireCollectionStatement { get; }
public TForEachStatement ForEachStatement { get; }
}
private class ForEachToForCodeAction : CodeAction.DocumentChangeAction
{
public ForEachToForCodeAction(
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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ConvertForEachToFor
{
internal abstract class AbstractConvertForEachToForCodeRefactoringProvider<
TStatementSyntax,
TForEachStatement> : CodeRefactoringProvider
where TStatementSyntax : SyntaxNode
where TForEachStatement : TStatementSyntax
{
private const string get_Count = nameof(get_Count);
private const string get_Item = nameof(get_Item);
private const string Length = nameof(Array.Length);
private const string Count = nameof(IList.Count);
private static readonly ImmutableArray<string> s_KnownInterfaceNames =
ImmutableArray.Create(typeof(IList<>).FullName!, typeof(IReadOnlyList<>).FullName!, typeof(IList).FullName!);
protected bool IsForEachVariableWrittenInside { get; private set; }
protected abstract string Title { get; }
protected abstract bool ValidLocation(ForEachInfo foreachInfo);
protected abstract (SyntaxNode start, SyntaxNode end) GetForEachBody(TForEachStatement foreachStatement);
protected abstract void ConvertToForStatement(
SemanticModel model, ForEachInfo info, SyntaxEditor editor, CancellationToken cancellationToken);
protected abstract bool IsValid(TForEachStatement foreachNode);
/// <summary>
/// Perform language specific checks if the conversion is supported.
/// C#: Currently nothing blocking a conversion
/// VB: Nested foreach loops sharing a single Next statement, Next statements with multiple variables and next statements
/// not using the loop variable are not supported.
/// </summary>
protected abstract bool IsSupported(ILocalSymbol foreachVariable, IForEachLoopOperation forEachOperation, TForEachStatement foreachStatement);
protected static SyntaxAnnotation CreateWarningAnnotation()
=> WarningAnnotation.Create(FeaturesResources.Warning_colon_semantics_may_change_when_converting_statement);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, _, cancellationToken) = context;
var foreachStatement = await context.TryGetRelevantNodeAsync<TForEachStatement>().ConfigureAwait(false);
if (foreachStatement == null || !IsValid(foreachStatement))
{
return;
}
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var semanticFact = document.GetRequiredLanguageService<ISemanticFactsService>();
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var foreachInfo = GetForeachInfo(semanticFact, model, foreachStatement, cancellationToken);
if (foreachInfo == null || !ValidLocation(foreachInfo))
{
return;
}
context.RegisterRefactoring(
new ForEachToForCodeAction(
Title,
c => ConvertForeachToForAsync(document, foreachInfo, c)),
foreachStatement.Span);
}
protected static SyntaxToken CreateUniqueName(
ISemanticFactsService semanticFacts, SemanticModel model, SyntaxNode location, string baseName, CancellationToken cancellationToken)
=> semanticFacts.GenerateUniqueLocalName(model, location, containerOpt: null, baseName, cancellationToken);
protected static SyntaxNode GetCollectionVariableName(
SemanticModel model, SyntaxGenerator generator,
ForEachInfo foreachInfo, SyntaxNode foreachCollectionExpression, CancellationToken cancellationToken)
{
if (foreachInfo.RequireCollectionStatement)
{
return generator.IdentifierName(
CreateUniqueName(foreachInfo.SemanticFacts,
model, foreachInfo.ForEachStatement, foreachInfo.CollectionNameSuggestion, cancellationToken));
}
return foreachCollectionExpression.WithoutTrivia().WithAdditionalAnnotations(Formatter.Annotation);
}
protected static void IntroduceCollectionStatement(
ForEachInfo foreachInfo, SyntaxEditor editor,
SyntaxNode type, SyntaxNode foreachCollectionExpression, SyntaxNode collectionVariable)
{
if (!foreachInfo.RequireCollectionStatement)
{
return;
}
// TODO: refactor introduce variable refactoring to real service and use that service here to introduce local variable
var generator = editor.Generator;
// attach rename annotation to control variable
var collectionVariableToken = generator.Identifier(collectionVariable.ToString()).WithAdditionalAnnotations(RenameAnnotation.Create());
// this expression is from user code. don't simplify this.
var expression = foreachCollectionExpression.WithoutAnnotations(SimplificationHelpers.DontSimplifyAnnotation);
var collectionStatement = generator.LocalDeclarationStatement(
type,
collectionVariableToken,
foreachInfo.RequireExplicitCastInterface
? generator.CastExpression(foreachInfo.ExplicitCastInterface, expression) : expression);
// attach trivia to right place
collectionStatement = collectionStatement.WithLeadingTrivia(foreachInfo.ForEachStatement.GetFirstToken().LeadingTrivia);
editor.InsertBefore(foreachInfo.ForEachStatement, collectionStatement);
}
protected static TStatementSyntax AddItemVariableDeclaration(
SyntaxGenerator generator, SyntaxNode type, SyntaxToken foreachVariable,
ITypeSymbol castType, SyntaxNode collectionVariable, SyntaxToken indexVariable)
{
var memberAccess = generator.ElementAccessExpression(
collectionVariable, generator.IdentifierName(indexVariable));
if (castType != null)
{
memberAccess = generator.CastExpression(castType, memberAccess);
}
var localDecl = generator.LocalDeclarationStatement(
type, foreachVariable, memberAccess);
return (TStatementSyntax)localDecl.WithAdditionalAnnotations(Formatter.Annotation);
}
private ForEachInfo? GetForeachInfo(
ISemanticFactsService semanticFact, SemanticModel model,
TForEachStatement foreachStatement, CancellationToken cancellationToken)
{
if (model.GetOperation(foreachStatement, cancellationToken) is not IForEachLoopOperation operation || operation.Locals.Length != 1)
{
return null;
}
var foreachVariable = operation.Locals[0];
if (foreachVariable == null)
{
return null;
}
// Perform language specific checks if the foreachStatement
// is using unsupported features
if (!IsSupported(foreachVariable, operation, foreachStatement))
{
return null;
}
IsForEachVariableWrittenInside = CheckIfForEachVariableIsWrittenInside(model, foreachVariable, foreachStatement);
var foreachCollection = RemoveImplicitConversion(operation.Collection);
if (foreachCollection == null)
{
return null;
}
GetInterfaceInfo(model, foreachVariable, foreachCollection,
out var explicitCastInterface, out var collectionNameSuggestion, out var countName);
if (collectionNameSuggestion == null || countName == null)
{
return null;
}
var requireCollectionStatement = CheckRequireCollectionStatement(foreachCollection);
return new ForEachInfo(
semanticFact, collectionNameSuggestion, countName, explicitCastInterface,
foreachVariable.Type, requireCollectionStatement, foreachStatement);
}
private static void GetInterfaceInfo(
SemanticModel model, ILocalSymbol foreachVariable, IOperation foreachCollection,
out ITypeSymbol? explicitCastInterface, out string? collectionNameSuggestion, out string? countName)
{
explicitCastInterface = null;
collectionNameSuggestion = null;
countName = null;
// go through list of types and interfaces to find out right set;
var foreachType = foreachVariable.Type;
if (IsNullOrErrorType(foreachType))
{
return;
}
var collectionType = foreachCollection.Type;
if (IsNullOrErrorType(collectionType))
{
return;
}
// go through explicit types first.
// check array case
if (collectionType is IArrayTypeSymbol array)
{
if (array.Rank != 1)
{
// array type supports IList and other interfaces, but implementation
// only supports Rank == 1 case. other case, it will throw on runtime
// even if there is no error on compile time.
// we explicitly mark that we only support Rank == 1 case
return;
}
if (!IsExchangable(array.ElementType, foreachType, model.Compilation))
{
return;
}
collectionNameSuggestion = "array";
explicitCastInterface = null;
countName = Length;
return;
}
// check string case
if (collectionType.SpecialType == SpecialType.System_String)
{
var charType = model.Compilation.GetSpecialType(SpecialType.System_Char);
if (!IsExchangable(charType, foreachType, model.Compilation))
{
return;
}
collectionNameSuggestion = "str";
explicitCastInterface = null;
countName = Length;
return;
}
// check ImmutableArray case
if (collectionType.OriginalDefinition.Equals(model.Compilation.GetTypeByMetadataName(typeof(ImmutableArray<>).FullName!)))
{
var indexer = GetInterfaceMember(collectionType, get_Item);
if (indexer != null)
{
if (!IsExchangable(indexer.ReturnType, foreachType, model.Compilation))
{
return;
}
collectionNameSuggestion = "array";
explicitCastInterface = null;
countName = Length;
return;
}
}
// go through all known interfaces we support next.
var knownCollectionInterfaces = s_KnownInterfaceNames.Select(
s => model.Compilation.GetTypeByMetadataName(s)).Where(t => !IsNullOrErrorType(t));
// for all interfaces, we suggest collection name as "list"
collectionNameSuggestion = "list";
// check type itself is interface case
if (collectionType.TypeKind == TypeKind.Interface && knownCollectionInterfaces.Contains(collectionType.OriginalDefinition))
{
var indexer = GetInterfaceMember(collectionType, get_Item);
if (indexer != null &&
IsExchangable(indexer.ReturnType, foreachType, model.Compilation))
{
explicitCastInterface = null;
countName = Count;
return;
}
}
// check regular cases (implicitly implemented)
ITypeSymbol? explicitInterface = null;
foreach (var current in collectionType.AllInterfaces)
{
if (!knownCollectionInterfaces.Contains(current.OriginalDefinition))
{
continue;
}
// see how the type implements the interface
var countSymbol = GetInterfaceMember(current, get_Count);
var indexerSymbol = GetInterfaceMember(current, get_Item);
if (countSymbol == null || indexerSymbol == null)
{
continue;
}
if (collectionType.FindImplementationForInterfaceMember(countSymbol) is not IMethodSymbol countImpl ||
collectionType.FindImplementationForInterfaceMember(indexerSymbol) is not IMethodSymbol indexerImpl)
{
continue;
}
if (!IsExchangable(indexerImpl.ReturnType, foreachType, model.Compilation))
{
continue;
}
// implicitly implemented!
if (countImpl.ExplicitInterfaceImplementations.IsEmpty &&
indexerImpl.ExplicitInterfaceImplementations.IsEmpty)
{
explicitCastInterface = null;
countName = Count;
return;
}
if (explicitInterface == null)
{
explicitInterface = current;
}
}
// okay, we don't have implicitly implemented one, but we do have explicitly implemented one
if (explicitInterface != null)
{
explicitCastInterface = explicitInterface;
countName = Count;
}
}
private static bool IsExchangable(
ITypeSymbol type1, ITypeSymbol type2, Compilation compilation)
{
return compilation.HasImplicitConversion(type1, type2) ||
compilation.HasImplicitConversion(type2, type1);
}
private static bool IsNullOrErrorType([NotNullWhen(false)] ITypeSymbol? type)
=> type is null or IErrorTypeSymbol;
private static IMethodSymbol? GetInterfaceMember(ITypeSymbol interfaceType, string memberName)
{
foreach (var current in interfaceType.GetAllInterfacesIncludingThis())
{
var members = current.GetMembers(memberName);
if (!members.IsEmpty && members[0] is IMethodSymbol method)
{
return method;
}
}
return null;
}
private static bool CheckRequireCollectionStatement(IOperation operation)
{
// this lists type of references in collection part of foreach we will use
// as it is in
// var element = reference[indexer];
//
// otherwise, we will introduce local variable for the expression first and then
// do "foreach to for" refactoring
//
// foreach(var a in new int[] {....})
// to
// var array = new int[] { ... }
// foreach(var a in array)
switch (operation.Kind)
{
case OperationKind.LocalReference:
case OperationKind.FieldReference:
case OperationKind.ParameterReference:
case OperationKind.PropertyReference:
case OperationKind.ArrayElementReference:
return false;
default:
return true;
}
}
private IOperation RemoveImplicitConversion(IOperation collection)
{
return (collection is IConversionOperation conversion && conversion.IsImplicit)
? RemoveImplicitConversion(conversion.Operand) : collection;
}
private bool CheckIfForEachVariableIsWrittenInside(SemanticModel semanticModel, ISymbol foreachVariable, TForEachStatement foreachStatement)
{
var (start, end) = GetForEachBody(foreachStatement);
if (start == null || end == null)
{
// empty body. this can happen in VB
return false;
}
var dataFlow = semanticModel.AnalyzeDataFlow(start, end);
if (!dataFlow.Succeeded)
{
// if we can't get good analysis, assume it is written
return true;
}
return dataFlow.WrittenInside.Contains(foreachVariable);
}
private async Task<Document> ConvertForeachToForAsync(
Document document,
ForEachInfo foreachInfo,
CancellationToken cancellationToken)
{
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var workspace = document.Project.Solution.Workspace;
var editor = new SyntaxEditor(model.SyntaxTree.GetRoot(cancellationToken), workspace);
ConvertToForStatement(model, foreachInfo, editor, cancellationToken);
var newRoot = editor.GetChangedRoot();
return document.WithSyntaxRoot(newRoot);
}
protected class ForEachInfo
{
public ForEachInfo(
ISemanticFactsService semanticFacts, string collectionNameSuggestion, string countName,
ITypeSymbol? explicitCastInterface, ITypeSymbol forEachElementType,
bool requireCollectionStatement, TForEachStatement forEachStatement)
{
SemanticFacts = semanticFacts;
RequireExplicitCastInterface = explicitCastInterface != null;
CollectionNameSuggestion = collectionNameSuggestion;
CountName = countName;
ExplicitCastInterface = explicitCastInterface;
ForEachElementType = forEachElementType;
RequireCollectionStatement = requireCollectionStatement || (explicitCastInterface != null);
ForEachStatement = forEachStatement;
}
public ISemanticFactsService SemanticFacts { get; }
public bool RequireExplicitCastInterface { get; }
public string CollectionNameSuggestion { get; }
public string CountName { get; }
public ITypeSymbol? ExplicitCastInterface { get; }
public ITypeSymbol ForEachElementType { get; }
public bool RequireCollectionStatement { get; }
public TForEachStatement ForEachStatement { get; }
}
private class ForEachToForCodeAction : CodeAction.DocumentChangeAction
{
public ForEachToForCodeAction(
string title,
Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/ExpressionEvaluator/CSharp/Test/ResultProvider/Properties/launchSettings.json | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/Errors/ErrorCode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum ErrorCode
{
Void = InternalErrorCode.Void,
Unknown = InternalErrorCode.Unknown,
#region diagnostics introduced in C# 4 and earlier
//FTL_InternalError = 1,
//FTL_FailedToLoadResource = 2,
//FTL_NoMemory = 3,
//ERR_WarningAsError = 4,
//ERR_MissingOptionArg = 5,
ERR_NoMetadataFile = 6,
//FTL_ComPlusInit = 7,
//FTL_MetadataImportFailure = 8, no longer used in Roslyn.
FTL_MetadataCantOpenFile = 9,
//ERR_FatalError = 10,
//ERR_CantImportBase = 11,
ERR_NoTypeDef = 12,
//FTL_MetadataEmitFailure = 13, Roslyn does not catch stream writing exceptions. Those are propagated to the caller.
//FTL_RequiredFileNotFound = 14,
//ERR_ClassNameTooLong = 15, Deprecated in favor of ERR_MetadataNameTooLong.
ERR_OutputWriteFailed = 16,
ERR_MultipleEntryPoints = 17,
//ERR_UnimplementedOp = 18,
ERR_BadBinaryOps = 19,
ERR_IntDivByZero = 20,
ERR_BadIndexLHS = 21,
ERR_BadIndexCount = 22,
ERR_BadUnaryOp = 23,
//ERR_NoStdLib = 25, not used in Roslyn
ERR_ThisInStaticMeth = 26,
ERR_ThisInBadContext = 27,
WRN_InvalidMainSig = 28,
ERR_NoImplicitConv = 29, // Requires SymbolDistinguisher.
ERR_NoExplicitConv = 30, // Requires SymbolDistinguisher.
ERR_ConstOutOfRange = 31,
ERR_AmbigBinaryOps = 34,
ERR_AmbigUnaryOp = 35,
ERR_InAttrOnOutParam = 36,
ERR_ValueCantBeNull = 37,
//ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired "An object reference is required for the non-static..."
ERR_NoExplicitBuiltinConv = 39, // Requires SymbolDistinguisher.
//FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
FTL_DebugEmitFailure = 41,
//FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info.
//FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
ERR_BadVisReturnType = 50,
ERR_BadVisParamType = 51,
ERR_BadVisFieldType = 52,
ERR_BadVisPropertyType = 53,
ERR_BadVisIndexerReturn = 54,
ERR_BadVisIndexerParam = 55,
ERR_BadVisOpReturn = 56,
ERR_BadVisOpParam = 57,
ERR_BadVisDelegateReturn = 58,
ERR_BadVisDelegateParam = 59,
ERR_BadVisBaseClass = 60,
ERR_BadVisBaseInterface = 61,
ERR_EventNeedsBothAccessors = 65,
ERR_EventNotDelegate = 66,
WRN_UnreferencedEvent = 67,
ERR_InterfaceEventInitializer = 68,
//ERR_EventPropertyInInterface = 69,
ERR_BadEventUsage = 70,
ERR_ExplicitEventFieldImpl = 71,
ERR_CantOverrideNonEvent = 72,
ERR_AddRemoveMustHaveBody = 73,
ERR_AbstractEventInitializer = 74,
ERR_PossibleBadNegCast = 75,
ERR_ReservedEnumerator = 76,
ERR_AsMustHaveReferenceType = 77,
WRN_LowercaseEllSuffix = 78,
ERR_BadEventUsageNoField = 79,
ERR_ConstraintOnlyAllowedOnGenericDecl = 80,
ERR_TypeParamMustBeIdentifier = 81,
ERR_MemberReserved = 82,
ERR_DuplicateParamName = 100,
ERR_DuplicateNameInNS = 101,
ERR_DuplicateNameInClass = 102,
ERR_NameNotInContext = 103,
ERR_AmbigContext = 104,
WRN_DuplicateUsing = 105,
ERR_BadMemberFlag = 106,
ERR_BadMemberProtection = 107,
WRN_NewRequired = 108,
WRN_NewNotRequired = 109,
ERR_CircConstValue = 110,
ERR_MemberAlreadyExists = 111,
ERR_StaticNotVirtual = 112,
ERR_OverrideNotNew = 113,
WRN_NewOrOverrideExpected = 114,
ERR_OverrideNotExpected = 115,
ERR_NamespaceUnexpected = 116,
ERR_NoSuchMember = 117,
ERR_BadSKknown = 118,
ERR_BadSKunknown = 119,
ERR_ObjectRequired = 120,
ERR_AmbigCall = 121,
ERR_BadAccess = 122,
ERR_MethDelegateMismatch = 123,
ERR_RetObjectRequired = 126,
ERR_RetNoObjectRequired = 127,
ERR_LocalDuplicate = 128,
ERR_AssgLvalueExpected = 131,
ERR_StaticConstParam = 132,
ERR_NotConstantExpression = 133,
ERR_NotNullConstRefField = 134,
// ERR_NameIllegallyOverrides = 135, // Not used in Roslyn anymore due to 'Single Meaning' relaxation changes
ERR_LocalIllegallyOverrides = 136,
ERR_BadUsingNamespace = 138,
ERR_NoBreakOrCont = 139,
ERR_DuplicateLabel = 140,
ERR_NoConstructors = 143,
ERR_NoNewAbstract = 144,
ERR_ConstValueRequired = 145,
ERR_CircularBase = 146,
ERR_BadDelegateConstructor = 148,
ERR_MethodNameExpected = 149,
ERR_ConstantExpected = 150,
// ERR_V6SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler.
// However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future
// we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used.
ERR_V6SwitchGoverningTypeValueExpected = 151,
ERR_DuplicateCaseLabel = 152,
ERR_InvalidGotoCase = 153,
ERR_PropertyLacksGet = 154,
ERR_BadExceptionType = 155,
ERR_BadEmptyThrow = 156,
ERR_BadFinallyLeave = 157,
ERR_LabelShadow = 158,
ERR_LabelNotFound = 159,
ERR_UnreachableCatch = 160,
ERR_ReturnExpected = 161,
WRN_UnreachableCode = 162,
ERR_SwitchFallThrough = 163,
WRN_UnreferencedLabel = 164,
ERR_UseDefViolation = 165,
//ERR_NoInvoke = 167,
WRN_UnreferencedVar = 168,
WRN_UnreferencedField = 169,
ERR_UseDefViolationField = 170,
ERR_UnassignedThis = 171,
ERR_AmbigQM = 172,
ERR_InvalidQM = 173, // Requires SymbolDistinguisher.
ERR_NoBaseClass = 174,
ERR_BaseIllegal = 175,
ERR_ObjectProhibited = 176,
ERR_ParamUnassigned = 177,
ERR_InvalidArray = 178,
ERR_ExternHasBody = 179,
ERR_AbstractAndExtern = 180,
ERR_BadAttributeParamType = 181,
ERR_BadAttributeArgument = 182,
WRN_IsAlwaysTrue = 183,
WRN_IsAlwaysFalse = 184,
ERR_LockNeedsReference = 185,
ERR_NullNotValid = 186,
ERR_UseDefViolationThis = 188,
ERR_ArgsInvalid = 190,
ERR_AssgReadonly = 191,
ERR_RefReadonly = 192,
ERR_PtrExpected = 193,
ERR_PtrIndexSingle = 196,
WRN_ByRefNonAgileField = 197,
ERR_AssgReadonlyStatic = 198,
ERR_RefReadonlyStatic = 199,
ERR_AssgReadonlyProp = 200,
ERR_IllegalStatement = 201,
ERR_BadGetEnumerator = 202,
ERR_TooManyLocals = 204,
ERR_AbstractBaseCall = 205,
ERR_RefProperty = 206,
// WRN_OldWarning_UnsafeProp = 207, // This error code is unused.
ERR_ManagedAddr = 208,
ERR_BadFixedInitType = 209,
ERR_FixedMustInit = 210,
ERR_InvalidAddrOp = 211,
ERR_FixedNeeded = 212,
ERR_FixedNotNeeded = 213,
ERR_UnsafeNeeded = 214,
ERR_OpTFRetType = 215,
ERR_OperatorNeedsMatch = 216,
ERR_BadBoolOp = 217,
ERR_MustHaveOpTF = 218,
WRN_UnreferencedVarAssg = 219,
ERR_CheckedOverflow = 220,
ERR_ConstOutOfRangeChecked = 221,
ERR_BadVarargs = 224,
ERR_ParamsMustBeArray = 225,
ERR_IllegalArglist = 226,
ERR_IllegalUnsafe = 227,
//ERR_NoAccessibleMember = 228,
ERR_AmbigMember = 229,
ERR_BadForeachDecl = 230,
ERR_ParamsLast = 231,
ERR_SizeofUnsafe = 233,
ERR_DottedTypeNameNotFoundInNS = 234,
ERR_FieldInitRefNonstatic = 236,
ERR_SealedNonOverride = 238,
ERR_CantOverrideSealed = 239,
//ERR_NoDefaultArgs = 241,
ERR_VoidError = 242,
ERR_ConditionalOnOverride = 243,
ERR_PointerInAsOrIs = 244,
ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated
ERR_SingleTypeNameNotFound = 246,
ERR_NegativeStackAllocSize = 247,
ERR_NegativeArraySize = 248,
ERR_OverrideFinalizeDeprecated = 249,
ERR_CallingBaseFinalizeDeprecated = 250,
WRN_NegativeArrayIndex = 251,
WRN_BadRefCompareLeft = 252,
WRN_BadRefCompareRight = 253,
ERR_BadCastInFixed = 254,
ERR_StackallocInCatchFinally = 255,
ERR_VarargsLast = 257,
ERR_MissingPartial = 260,
ERR_PartialTypeKindConflict = 261,
ERR_PartialModifierConflict = 262,
ERR_PartialMultipleBases = 263,
ERR_PartialWrongTypeParams = 264,
ERR_PartialWrongConstraints = 265,
ERR_NoImplicitConvCast = 266, // Requires SymbolDistinguisher.
ERR_PartialMisplaced = 267,
ERR_ImportedCircularBase = 268,
ERR_UseDefViolationOut = 269,
ERR_ArraySizeInDeclaration = 270,
ERR_InaccessibleGetter = 271,
ERR_InaccessibleSetter = 272,
ERR_InvalidPropertyAccessMod = 273,
ERR_DuplicatePropertyAccessMods = 274,
//ERR_PropertyAccessModInInterface = 275,
ERR_AccessModMissingAccessor = 276,
ERR_UnimplementedInterfaceAccessor = 277,
WRN_PatternIsAmbiguous = 278,
WRN_PatternNotPublicOrNotInstance = 279,
WRN_PatternBadSignature = 280,
ERR_FriendRefNotEqualToThis = 281,
WRN_SequentialOnPartialClass = 282,
ERR_BadConstType = 283,
ERR_NoNewTyvar = 304,
ERR_BadArity = 305,
ERR_BadTypeArgument = 306,
ERR_TypeArgsNotAllowed = 307,
ERR_HasNoTypeVars = 308,
ERR_NewConstraintNotSatisfied = 310,
ERR_GenericConstraintNotSatisfiedRefType = 311, // Requires SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedNullableEnum = 312, // Uses (but doesn't require) SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedNullableInterface = 313, // Uses (but doesn't require) SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedTyVar = 314, // Requires SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedValType = 315, // Requires SymbolDistinguisher.
ERR_DuplicateGeneratedName = 316,
// unused 317-399
ERR_GlobalSingleTypeNameNotFound = 400,
ERR_NewBoundMustBeLast = 401,
WRN_MainCantBeGeneric = 402,
ERR_TypeVarCantBeNull = 403,
// ERR_AttributeCantBeGeneric = 404,
ERR_DuplicateBound = 405,
ERR_ClassBoundNotFirst = 406,
ERR_BadRetType = 407,
ERR_DuplicateConstraintClause = 409,
//ERR_WrongSignature = 410, unused in Roslyn
ERR_CantInferMethTypeArgs = 411,
ERR_LocalSameNameAsTypeParam = 412,
ERR_AsWithTypeVar = 413,
WRN_UnreferencedFieldAssg = 414,
ERR_BadIndexerNameAttr = 415,
ERR_AttrArgWithTypeVars = 416,
ERR_NewTyvarWithArgs = 417,
ERR_AbstractSealedStatic = 418,
WRN_AmbiguousXMLReference = 419,
WRN_VolatileByRef = 420,
// WRN_IncrSwitchObsolete = 422, // This error code is unused.
ERR_ComImportWithImpl = 423,
ERR_ComImportWithBase = 424,
ERR_ImplBadConstraints = 425,
ERR_DottedTypeNameNotFoundInAgg = 426,
ERR_MethGrpToNonDel = 428,
// WRN_UnreachableExpr = 429, // This error code is unused.
ERR_BadExternAlias = 430,
ERR_ColColWithTypeAlias = 431,
ERR_AliasNotFound = 432,
ERR_SameFullNameAggAgg = 433,
ERR_SameFullNameNsAgg = 434,
WRN_SameFullNameThisNsAgg = 435,
WRN_SameFullNameThisAggAgg = 436,
WRN_SameFullNameThisAggNs = 437,
ERR_SameFullNameThisAggThisNs = 438,
ERR_ExternAfterElements = 439,
WRN_GlobalAliasDefn = 440,
ERR_SealedStaticClass = 441,
ERR_PrivateAbstractAccessor = 442,
ERR_ValueExpected = 443,
// WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused.
ERR_UnboxNotLValue = 445,
ERR_AnonMethGrpInForEach = 446,
//ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error.
ERR_BadIncDecRetType = 448,
ERR_TypeConstraintsMustBeUniqueAndFirst = 449,
ERR_RefValBoundWithClass = 450,
ERR_NewBoundWithVal = 451,
ERR_RefConstraintNotSatisfied = 452,
ERR_ValConstraintNotSatisfied = 453,
ERR_CircularConstraint = 454,
ERR_BaseConstraintConflict = 455,
ERR_ConWithValCon = 456,
ERR_AmbigUDConv = 457,
WRN_AlwaysNull = 458,
// ERR_AddrOnReadOnlyLocal = 459, // no longer an error
ERR_OverrideWithConstraints = 460,
ERR_AmbigOverride = 462,
ERR_DecConstError = 463,
WRN_CmpAlwaysFalse = 464,
WRN_FinalizeMethod = 465,
ERR_ExplicitImplParams = 466,
// WRN_AmbigLookupMeth = 467, //no longer issued in Roslyn
//ERR_SameFullNameThisAggThisAgg = 468, no longer used in Roslyn
WRN_GotoCaseShouldConvert = 469,
ERR_MethodImplementingAccessor = 470,
//ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn
WRN_NubExprIsConstBool = 472,
WRN_ExplicitImplCollision = 473,
// unused 474-499
ERR_AbstractHasBody = 500,
ERR_ConcreteMissingBody = 501,
ERR_AbstractAndSealed = 502,
ERR_AbstractNotVirtual = 503,
ERR_StaticConstant = 504,
ERR_CantOverrideNonFunction = 505,
ERR_CantOverrideNonVirtual = 506,
ERR_CantChangeAccessOnOverride = 507,
ERR_CantChangeReturnTypeOnOverride = 508,
ERR_CantDeriveFromSealedType = 509,
ERR_AbstractInConcreteClass = 513,
ERR_StaticConstructorWithExplicitConstructorCall = 514,
ERR_StaticConstructorWithAccessModifiers = 515,
ERR_RecursiveConstructorCall = 516,
ERR_ObjectCallingBaseConstructor = 517,
ERR_PredefinedTypeNotFound = 518,
//ERR_PredefinedTypeBadType = 520,
ERR_StructWithBaseConstructorCall = 522,
ERR_StructLayoutCycle = 523,
//ERR_InterfacesCannotContainTypes = 524,
ERR_InterfacesCantContainFields = 525,
ERR_InterfacesCantContainConstructors = 526,
ERR_NonInterfaceInInterfaceList = 527,
ERR_DuplicateInterfaceInBaseList = 528,
ERR_CycleInInterfaceInheritance = 529,
//ERR_InterfaceMemberHasBody = 531,
ERR_HidingAbstractMethod = 533,
ERR_UnimplementedAbstractMethod = 534,
ERR_UnimplementedInterfaceMember = 535,
ERR_ObjectCantHaveBases = 537,
ERR_ExplicitInterfaceImplementationNotInterface = 538,
ERR_InterfaceMemberNotFound = 539,
ERR_ClassDoesntImplementInterface = 540,
ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541,
ERR_MemberNameSameAsType = 542,
ERR_EnumeratorOverflow = 543,
ERR_CantOverrideNonProperty = 544,
ERR_NoGetToOverride = 545,
ERR_NoSetToOverride = 546,
ERR_PropertyCantHaveVoidType = 547,
ERR_PropertyWithNoAccessors = 548,
ERR_NewVirtualInSealed = 549,
ERR_ExplicitPropertyAddingAccessor = 550,
ERR_ExplicitPropertyMissingAccessor = 551,
ERR_ConversionWithInterface = 552,
ERR_ConversionWithBase = 553,
ERR_ConversionWithDerived = 554,
ERR_IdentityConversion = 555,
ERR_ConversionNotInvolvingContainedType = 556,
ERR_DuplicateConversionInClass = 557,
ERR_OperatorsMustBeStatic = 558,
ERR_BadIncDecSignature = 559,
ERR_BadUnaryOperatorSignature = 562,
ERR_BadBinaryOperatorSignature = 563,
ERR_BadShiftOperatorSignature = 564,
ERR_InterfacesCantContainConversionOrEqualityOperators = 567,
//ERR_StructsCantContainDefaultConstructor = 568,
ERR_CantOverrideBogusMethod = 569,
ERR_BindToBogus = 570,
ERR_CantCallSpecialMethod = 571,
ERR_BadTypeReference = 572,
//ERR_FieldInitializerInStruct = 573,
ERR_BadDestructorName = 574,
ERR_OnlyClassesCanContainDestructors = 575,
ERR_ConflictAliasAndMember = 576,
ERR_ConditionalOnSpecialMethod = 577,
ERR_ConditionalMustReturnVoid = 578,
ERR_DuplicateAttribute = 579,
ERR_ConditionalOnInterfaceMethod = 582,
//ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused
//ERR_ICE_Symbol = 584,
//ERR_ICE_Node = 585,
//ERR_ICE_File = 586,
//ERR_ICE_Stage = 587,
//ERR_ICE_Lexer = 588,
//ERR_ICE_Parser = 589,
ERR_OperatorCantReturnVoid = 590,
ERR_InvalidAttributeArgument = 591,
ERR_AttributeOnBadSymbolType = 592,
ERR_FloatOverflow = 594,
ERR_InvalidReal = 595,
ERR_ComImportWithoutUuidAttribute = 596,
ERR_InvalidNamedArgument = 599,
ERR_DllImportOnInvalidMethod = 601,
// WRN_FeatureDeprecated = 602, // This error code is unused.
// ERR_NameAttributeOnOverride = 609, // removed in Roslyn
ERR_FieldCantBeRefAny = 610,
ERR_ArrayElementCantBeRefAny = 611,
WRN_DeprecatedSymbol = 612,
ERR_NotAnAttributeClass = 616,
ERR_BadNamedAttributeArgument = 617,
WRN_DeprecatedSymbolStr = 618,
ERR_DeprecatedSymbolStr = 619,
ERR_IndexerCantHaveVoidType = 620,
ERR_VirtualPrivate = 621,
ERR_ArrayInitToNonArrayType = 622,
ERR_ArrayInitInBadPlace = 623,
ERR_MissingStructOffset = 625,
WRN_ExternMethodNoImplementation = 626,
WRN_ProtectedInSealed = 628,
ERR_InterfaceImplementedByConditional = 629,
ERR_InterfaceImplementedImplicitlyByVariadic = 630,
ERR_IllegalRefParam = 631,
ERR_BadArgumentToAttribute = 633,
//ERR_MissingComTypeOrMarshaller = 635,
ERR_StructOffsetOnBadStruct = 636,
ERR_StructOffsetOnBadField = 637,
ERR_AttributeUsageOnNonAttributeClass = 641,
WRN_PossibleMistakenNullStatement = 642,
ERR_DuplicateNamedAttributeArgument = 643,
ERR_DeriveFromEnumOrValueType = 644,
//ERR_IdentifierTooLong = 645, //not used in Roslyn. See ERR_MetadataNameTooLong
ERR_DefaultMemberOnIndexedType = 646,
//ERR_CustomAttributeError = 647,
ERR_BogusType = 648,
WRN_UnassignedInternalField = 649,
ERR_CStyleArray = 650,
WRN_VacuousIntegralComp = 652,
ERR_AbstractAttributeClass = 653,
ERR_BadNamedAttributeArgumentType = 655,
ERR_MissingPredefinedMember = 656,
WRN_AttributeLocationOnBadDeclaration = 657,
WRN_InvalidAttributeLocation = 658,
WRN_EqualsWithoutGetHashCode = 659,
WRN_EqualityOpWithoutEquals = 660,
WRN_EqualityOpWithoutGetHashCode = 661,
ERR_OutAttrOnRefParam = 662,
ERR_OverloadRefKind = 663,
ERR_LiteralDoubleCast = 664,
WRN_IncorrectBooleanAssg = 665,
ERR_ProtectedInStruct = 666,
//ERR_FeatureDeprecated = 667,
ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler
ERR_ComImportWithUserCtor = 669,
ERR_FieldCantHaveVoidType = 670,
WRN_NonObsoleteOverridingObsolete = 672,
ERR_SystemVoid = 673,
ERR_ExplicitParamArray = 674,
WRN_BitwiseOrSignExtend = 675,
ERR_VolatileStruct = 677,
ERR_VolatileAndReadonly = 678,
// WRN_OldWarning_ProtectedInternal = 679, // This error code is unused.
// WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused.
ERR_AbstractField = 681,
ERR_BogusExplicitImpl = 682,
ERR_ExplicitMethodImplAccessor = 683,
WRN_CoClassWithoutComImport = 684,
ERR_ConditionalWithOutParam = 685,
ERR_AccessorImplementingMethod = 686,
ERR_AliasQualAsExpression = 687,
ERR_DerivingFromATyVar = 689,
//FTL_MalformedMetadata = 690,
ERR_DuplicateTypeParameter = 692,
WRN_TypeParameterSameAsOuterTypeParameter = 693,
ERR_TypeVariableSameAsParent = 694,
ERR_UnifyingInterfaceInstantiations = 695,
// ERR_GenericDerivingFromAttribute = 698,
ERR_TyVarNotFoundInConstraint = 699,
ERR_BadBoundType = 701,
ERR_SpecialTypeAsBound = 702,
ERR_BadVisBound = 703,
ERR_LookupInTypeVariable = 704,
ERR_BadConstraintType = 706,
ERR_InstanceMemberInStaticClass = 708,
ERR_StaticBaseClass = 709,
ERR_ConstructorInStaticClass = 710,
ERR_DestructorInStaticClass = 711,
ERR_InstantiatingStaticClass = 712,
ERR_StaticDerivedFromNonObject = 713,
ERR_StaticClassInterfaceImpl = 714,
ERR_OperatorInStaticClass = 715,
ERR_ConvertToStaticClass = 716,
ERR_ConstraintIsStaticClass = 717,
ERR_GenericArgIsStaticClass = 718,
ERR_ArrayOfStaticClass = 719,
ERR_IndexerInStaticClass = 720,
ERR_ParameterIsStaticClass = 721,
ERR_ReturnTypeIsStaticClass = 722,
ERR_VarDeclIsStaticClass = 723,
ERR_BadEmptyThrowInFinally = 724,
//ERR_InvalidDecl = 725,
ERR_InvalidSpecifier = 726,
//ERR_InvalidSpecifierUnk = 727,
WRN_AssignmentToLockOrDispose = 728,
ERR_ForwardedTypeInThisAssembly = 729,
ERR_ForwardedTypeIsNested = 730,
ERR_CycleInTypeForwarder = 731,
//ERR_FwdedGeneric = 733,
ERR_AssemblyNameOnNonModule = 734,
ERR_InvalidFwdType = 735,
ERR_CloseUnimplementedInterfaceMemberStatic = 736,
ERR_CloseUnimplementedInterfaceMemberNotPublic = 737,
ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738,
ERR_DuplicateTypeForwarder = 739,
ERR_ExpectedSelectOrGroup = 742,
ERR_ExpectedContextualKeywordOn = 743,
ERR_ExpectedContextualKeywordEquals = 744,
ERR_ExpectedContextualKeywordBy = 745,
ERR_InvalidAnonymousTypeMemberDeclarator = 746,
ERR_InvalidInitializerElementInitializer = 747,
ERR_InconsistentLambdaParameterUsage = 748,
ERR_PartialMethodInvalidModifier = 750,
ERR_PartialMethodOnlyInPartialClass = 751,
// ERR_PartialMethodCannotHaveOutParameters = 752, Removed as part of 'extended partial methods' feature
// ERR_PartialMethodOnlyMethods = 753, Removed as it is subsumed by ERR_PartialMisplaced
ERR_PartialMethodNotExplicit = 754,
ERR_PartialMethodExtensionDifference = 755,
ERR_PartialMethodOnlyOneLatent = 756,
ERR_PartialMethodOnlyOneActual = 757,
ERR_PartialMethodParamsDifference = 758,
ERR_PartialMethodMustHaveLatent = 759,
ERR_PartialMethodInconsistentConstraints = 761,
ERR_PartialMethodToDelegate = 762,
ERR_PartialMethodStaticDifference = 763,
ERR_PartialMethodUnsafeDifference = 764,
ERR_PartialMethodInExpressionTree = 765,
// ERR_PartialMethodMustReturnVoid = 766, Removed as part of 'extended partial methods' feature
ERR_ExplicitImplCollisionOnRefOut = 767,
ERR_IndirectRecursiveConstructorCall = 768,
// unused 769-799
//ERR_NoEmptyArrayRanges = 800,
//ERR_IntegerSpecifierOnOneDimArrays = 801,
//ERR_IntegerSpecifierMustBePositive = 802,
//ERR_ArrayRangeDimensionsMustMatch = 803,
//ERR_ArrayRangeDimensionsWrong = 804,
//ERR_IntegerSpecifierValidOnlyOnArrays = 805,
//ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806,
//ERR_UseAdditionalSquareBrackets = 807,
//ERR_DotDotNotAssociative = 808,
WRN_ObsoleteOverridingNonObsolete = 809,
WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong
ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue
ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer
ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator
ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer
ERR_ImplicitlyTypedLocalCannotBeFixed = 821,
ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst
WRN_ExternCtorNoImplementation = 824,
ERR_TypeVarNotFound = 825,
ERR_ImplicitlyTypedArrayNoBestType = 826,
ERR_AnonymousTypePropertyAssignedBadValue = 828,
ERR_ExpressionTreeContainsBaseAccess = 831,
ERR_ExpressionTreeContainsAssignment = 832,
ERR_AnonymousTypeDuplicatePropertyName = 833,
ERR_StatementLambdaToExpressionTree = 834,
ERR_ExpressionTreeMustHaveDelegate = 835,
ERR_AnonymousTypeNotAvailable = 836,
ERR_LambdaInIsAs = 837,
ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838,
ERR_MissingArgument = 839,
//ERR_AutoPropertiesMustHaveBothAccessors = 840,
ERR_VariableUsedBeforeDeclaration = 841,
//ERR_ExplicitLayoutAndAutoImplementedProperty = 842,
ERR_UnassignedThisAutoProperty = 843,
ERR_VariableUsedBeforeDeclarationAndHidesField = 844,
ERR_ExpressionTreeContainsBadCoalesce = 845,
ERR_ArrayInitializerExpected = 846,
ERR_ArrayInitializerIncorrectLength = 847,
// ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind
ERR_ExpressionTreeContainsNamedArgument = 853,
ERR_ExpressionTreeContainsOptionalArgument = 854,
ERR_ExpressionTreeContainsIndexedProperty = 855,
ERR_IndexedPropertyRequiresParams = 856,
ERR_IndexedPropertyMustHaveAllOptionalParams = 857,
//ERR_FusionConfigFileNameTooLong = 858, unused in Roslyn. We give ERR_CantReadConfigFile now.
// unused 859-1000
ERR_IdentifierExpected = 1001,
ERR_SemicolonExpected = 1002,
ERR_SyntaxError = 1003,
ERR_DuplicateModifier = 1004,
ERR_DuplicateAccessor = 1007,
ERR_IntegralTypeExpected = 1008,
ERR_IllegalEscape = 1009,
ERR_NewlineInConst = 1010,
ERR_EmptyCharConst = 1011,
ERR_TooManyCharsInConst = 1012,
ERR_InvalidNumber = 1013,
ERR_GetOrSetExpected = 1014,
ERR_ClassTypeExpected = 1015,
ERR_NamedArgumentExpected = 1016,
ERR_TooManyCatches = 1017,
ERR_ThisOrBaseExpected = 1018,
ERR_OvlUnaryOperatorExpected = 1019,
ERR_OvlBinaryOperatorExpected = 1020,
ERR_IntOverflow = 1021,
ERR_EOFExpected = 1022,
ERR_BadEmbeddedStmt = 1023,
ERR_PPDirectiveExpected = 1024,
ERR_EndOfPPLineExpected = 1025,
ERR_CloseParenExpected = 1026,
ERR_EndifDirectiveExpected = 1027,
ERR_UnexpectedDirective = 1028,
ERR_ErrorDirective = 1029,
WRN_WarningDirective = 1030,
ERR_TypeExpected = 1031,
ERR_PPDefFollowsToken = 1032,
//ERR_TooManyLines = 1033, unused in Roslyn.
//ERR_LineTooLong = 1034, unused in Roslyn.
ERR_OpenEndedComment = 1035,
ERR_OvlOperatorExpected = 1037,
ERR_EndRegionDirectiveExpected = 1038,
ERR_UnterminatedStringLit = 1039,
ERR_BadDirectivePlacement = 1040,
ERR_IdentifierExpectedKW = 1041,
ERR_SemiOrLBraceExpected = 1043,
ERR_MultiTypeInDeclaration = 1044,
ERR_AddOrRemoveExpected = 1055,
ERR_UnexpectedCharacter = 1056,
ERR_ProtectedInStatic = 1057,
WRN_UnreachableGeneralCatch = 1058,
ERR_IncrementLvalueExpected = 1059,
// WRN_UninitializedField = 1060, // unused in Roslyn.
ERR_NoSuchMemberOrExtension = 1061,
WRN_DeprecatedCollectionInitAddStr = 1062,
ERR_DeprecatedCollectionInitAddStr = 1063,
WRN_DeprecatedCollectionInitAdd = 1064,
ERR_DefaultValueNotAllowed = 1065,
WRN_DefaultValueForUnconsumedLocation = 1066,
ERR_PartialWrongTypeParamsVariance = 1067,
ERR_GlobalSingleTypeNameNotFoundFwd = 1068,
ERR_DottedTypeNameNotFoundInNSFwd = 1069,
ERR_SingleTypeNameNotFoundFwd = 1070,
//ERR_NoSuchMemberOnNoPIAType = 1071, //EE
WRN_IdentifierOrNumericLiteralExpected = 1072,
ERR_UnexpectedToken = 1073,
// unused 1074-1098
// ERR_EOLExpected = 1099, // EE
// ERR_NotSupportedinEE = 1100, // EE
ERR_BadThisParam = 1100,
// ERR_BadRefWithThis = 1101, replaced by ERR_BadParameterModifiers
// ERR_BadOutWithThis = 1102, replaced by ERR_BadParameterModifiers
ERR_BadTypeforThis = 1103,
ERR_BadParamModThis = 1104,
ERR_BadExtensionMeth = 1105,
ERR_BadExtensionAgg = 1106,
ERR_DupParamMod = 1107,
// ERR_MultiParamMod = 1108, replaced by ERR_BadParameterModifiers
ERR_ExtensionMethodsDecl = 1109,
ERR_ExtensionAttrNotFound = 1110,
//ERR_ExtensionTypeParam = 1111,
ERR_ExplicitExtension = 1112,
ERR_ValueTypeExtDelegate = 1113,
// unused 1114-1199
// Below five error codes are unused.
// WRN_FeatureDeprecated2 = 1200,
// WRN_FeatureDeprecated3 = 1201,
// WRN_FeatureDeprecated4 = 1202,
// WRN_FeatureDeprecated5 = 1203,
// WRN_OldWarning_FeatureDefaultDeprecated = 1204,
// unused 1205-1500
ERR_BadArgCount = 1501,
//ERR_BadArgTypes = 1502,
ERR_BadArgType = 1503,
ERR_NoSourceFile = 1504,
ERR_CantRefResource = 1507,
ERR_ResourceNotUnique = 1508,
ERR_ImportNonAssembly = 1509,
ERR_RefLvalueExpected = 1510,
ERR_BaseInStaticMeth = 1511,
ERR_BaseInBadContext = 1512,
ERR_RbraceExpected = 1513,
ERR_LbraceExpected = 1514,
ERR_InExpected = 1515,
ERR_InvalidPreprocExpr = 1517,
//ERR_BadTokenInType = 1518, unused in Roslyn
ERR_InvalidMemberDecl = 1519,
ERR_MemberNeedsType = 1520,
ERR_BadBaseType = 1521,
WRN_EmptySwitch = 1522,
ERR_ExpectedEndTry = 1524,
ERR_InvalidExprTerm = 1525,
ERR_BadNewExpr = 1526,
ERR_NoNamespacePrivate = 1527,
ERR_BadVarDecl = 1528,
ERR_UsingAfterElements = 1529,
//ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this.
//ERR_DontUseInvoke = 1533,
ERR_BadBinOpArgs = 1534,
ERR_BadUnOpArgs = 1535,
ERR_NoVoidParameter = 1536,
ERR_DuplicateAlias = 1537,
ERR_BadProtectedAccess = 1540,
//ERR_CantIncludeDirectory = 1541,
ERR_AddModuleAssembly = 1542,
ERR_BindToBogusProp2 = 1545,
ERR_BindToBogusProp1 = 1546,
ERR_NoVoidHere = 1547,
//ERR_CryptoFailed = 1548,
//ERR_CryptoNotFound = 1549,
ERR_IndexerNeedsParam = 1551,
ERR_BadArraySyntax = 1552,
ERR_BadOperatorSyntax = 1553,
//ERR_BadOperatorSyntax2 = 1554, Not used in Roslyn.
ERR_MainClassNotFound = 1555,
ERR_MainClassNotClass = 1556,
//ERR_MainClassWrongFile = 1557, Not used in Roslyn. This was used only when compiling and producing two outputs.
ERR_NoMainInClass = 1558,
//ERR_MainClassIsImport = 1559, Not used in Roslyn. Scenario occurs so infrequently that it is not worth re-implementing.
//ERR_FileNameTooLong = 1560,
//ERR_OutputFileNameTooLong = 1561, Not used in Roslyn. We report a more generic error that doesn't mention "output file" but is fine.
ERR_OutputNeedsName = 1562,
//ERR_OutputNeedsInput = 1563,
ERR_CantHaveWin32ResAndManifest = 1564,
ERR_CantHaveWin32ResAndIcon = 1565,
ERR_CantReadResource = 1566,
//ERR_AutoResGen = 1567,
ERR_DocFileGen = 1569,
WRN_XMLParseError = 1570,
WRN_DuplicateParamTag = 1571,
WRN_UnmatchedParamTag = 1572,
WRN_MissingParamTag = 1573,
WRN_BadXMLRef = 1574,
ERR_BadStackAllocExpr = 1575,
ERR_InvalidLineNumber = 1576,
//ERR_ALinkFailed = 1577, No alink usage in Roslyn
ERR_MissingPPFile = 1578,
ERR_ForEachMissingMember = 1579,
WRN_BadXMLRefParamType = 1580,
WRN_BadXMLRefReturnType = 1581,
ERR_BadWin32Res = 1583,
WRN_BadXMLRefSyntax = 1584,
ERR_BadModifierLocation = 1585,
ERR_MissingArraySize = 1586,
WRN_UnprocessedXMLComment = 1587,
//ERR_CantGetCORSystemDir = 1588,
WRN_FailedInclude = 1589,
WRN_InvalidInclude = 1590,
WRN_MissingXMLComment = 1591,
WRN_XMLParseIncludeError = 1592,
ERR_BadDelArgCount = 1593,
//ERR_BadDelArgTypes = 1594,
// WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused.
// WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused.
ERR_UnexpectedSemicolon = 1597,
// WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time).
ERR_MethodReturnCantBeRefAny = 1599,
ERR_CompileCancelled = 1600,
ERR_MethodArgCantBeRefAny = 1601,
ERR_AssgReadonlyLocal = 1604,
ERR_RefReadonlyLocal = 1605,
//ERR_ALinkCloseFailed = 1606,
WRN_ALinkWarn = 1607,
ERR_CantUseRequiredAttribute = 1608,
ERR_NoModifiersOnAccessor = 1609,
// WRN_DeleteAutoResFailed = 1610, // Unused.
ERR_ParamsCantBeWithModifier = 1611,
ERR_ReturnNotLValue = 1612,
ERR_MissingCoClass = 1613,
ERR_AmbiguousAttribute = 1614,
ERR_BadArgExtraRef = 1615,
WRN_CmdOptionConflictsSource = 1616,
ERR_BadCompatMode = 1617,
ERR_DelegateOnConditional = 1618,
ERR_CantMakeTempFile = 1619, //changed to now accept only one argument
ERR_BadArgRef = 1620,
ERR_YieldInAnonMeth = 1621,
ERR_ReturnInIterator = 1622,
ERR_BadIteratorArgType = 1623,
ERR_BadIteratorReturn = 1624,
ERR_BadYieldInFinally = 1625,
ERR_BadYieldInTryOfCatch = 1626,
ERR_EmptyYield = 1627,
ERR_AnonDelegateCantUse = 1628,
ERR_IllegalInnerUnsafe = 1629,
//ERR_BadWatsonMode = 1630,
ERR_BadYieldInCatch = 1631,
ERR_BadDelegateLeave = 1632,
WRN_IllegalPragma = 1633,
WRN_IllegalPPWarning = 1634,
WRN_BadRestoreNumber = 1635,
ERR_VarargsIterator = 1636,
ERR_UnsafeIteratorArgType = 1637,
//ERR_ReservedIdentifier = 1638,
ERR_BadCoClassSig = 1639,
ERR_MultipleIEnumOfT = 1640,
ERR_FixedDimsRequired = 1641,
ERR_FixedNotInStruct = 1642,
ERR_AnonymousReturnExpected = 1643,
//ERR_NonECMAFeature = 1644,
WRN_NonECMAFeature = 1645,
ERR_ExpectedVerbatimLiteral = 1646,
//FTL_StackOverflow = 1647,
ERR_AssgReadonly2 = 1648,
ERR_RefReadonly2 = 1649,
ERR_AssgReadonlyStatic2 = 1650,
ERR_RefReadonlyStatic2 = 1651,
ERR_AssgReadonlyLocal2Cause = 1654,
ERR_RefReadonlyLocal2Cause = 1655,
ERR_AssgReadonlyLocalCause = 1656,
ERR_RefReadonlyLocalCause = 1657,
WRN_ErrorOverride = 1658,
// WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused.
ERR_AnonMethToNonDel = 1660,
ERR_CantConvAnonMethParams = 1661,
ERR_CantConvAnonMethReturns = 1662,
ERR_IllegalFixedType = 1663,
ERR_FixedOverflow = 1664,
ERR_InvalidFixedArraySize = 1665,
ERR_FixedBufferNotFixed = 1666,
ERR_AttributeNotOnAccessor = 1667,
WRN_InvalidSearchPathDir = 1668,
ERR_IllegalVarArgs = 1669,
ERR_IllegalParams = 1670,
ERR_BadModifiersOnNamespace = 1671,
ERR_BadPlatformType = 1672,
ERR_ThisStructNotInAnonMeth = 1673,
ERR_NoConvToIDisp = 1674,
// ERR_InvalidGenericEnum = 1675, replaced with 7002
ERR_BadParamRef = 1676,
ERR_BadParamExtraRef = 1677,
ERR_BadParamType = 1678, // Requires SymbolDistinguisher.
ERR_BadExternIdentifier = 1679,
ERR_AliasMissingFile = 1680,
ERR_GlobalExternAlias = 1681,
// WRN_MissingTypeNested = 1682, // unused in Roslyn.
// In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively.
// WRN_MissingTypeInSource = 1683,
// WRN_MissingTypeInAssembly = 1684,
WRN_MultiplePredefTypes = 1685,
ERR_LocalCantBeFixedAndHoisted = 1686,
WRN_TooManyLinesForDebugger = 1687,
ERR_CantConvAnonMethNoParams = 1688,
ERR_ConditionalOnNonAttributeClass = 1689,
WRN_CallOnNonAgileField = 1690,
// WRN_BadWarningNumber = 1691, // we no longer generate this warning for an unrecognized warning ID specified as an argument to /nowarn or /warnaserror.
WRN_InvalidNumber = 1692,
// WRN_FileNameTooLong = 1694, //unused.
WRN_IllegalPPChecksum = 1695,
WRN_EndOfPPLineExpected = 1696,
WRN_ConflictingChecksum = 1697,
// WRN_AssumedMatchThis = 1698, // This error code is unused.
// WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused.
WRN_InvalidAssemblyName = 1700,
WRN_UnifyReferenceMajMin = 1701,
WRN_UnifyReferenceBldRev = 1702,
ERR_DuplicateImport = 1703,
ERR_DuplicateImportSimple = 1704,
ERR_AssemblyMatchBadVersion = 1705,
//ERR_AnonMethNotAllowed = 1706, Unused in Roslyn. Previously given when a lambda was supplied as an attribute argument.
// WRN_DelegateNewMethBind = 1707, // This error code is unused.
ERR_FixedNeedsLvalue = 1708,
// WRN_EmptyFileName = 1709, // This error code is unused.
WRN_DuplicateTypeParamTag = 1710,
WRN_UnmatchedTypeParamTag = 1711,
WRN_MissingTypeParamTag = 1712,
//FTL_TypeNameBuilderError = 1713,
//ERR_ImportBadBase = 1714, // This error code is unused and replaced with ERR_NoTypeDef
ERR_CantChangeTypeOnOverride = 1715,
ERR_DoNotUseFixedBufferAttr = 1716,
WRN_AssignmentToSelf = 1717,
WRN_ComparisonToSelf = 1718,
ERR_CantOpenWin32Res = 1719,
WRN_DotOnDefault = 1720,
ERR_NoMultipleInheritance = 1721,
ERR_BaseClassMustBeFirst = 1722,
WRN_BadXMLRefTypeVar = 1723,
//ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn.
ERR_FriendAssemblyBadArgs = 1725,
ERR_FriendAssemblySNReq = 1726,
//ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings.
ERR_DelegateOnNullable = 1728,
ERR_BadCtorArgCount = 1729,
ERR_GlobalAttributesNotFirst = 1730,
//ERR_CantConvAnonMethReturnsNoDelegate = 1731, Not used in Roslyn. When there is no delegate, we reuse the message that contains a substitution string for the delegate type.
//ERR_ParameterExpected = 1732, Not used in Roslyn.
ERR_ExpressionExpected = 1733,
WRN_UnmatchedParamRefTag = 1734,
WRN_UnmatchedTypeParamRefTag = 1735,
ERR_DefaultValueMustBeConstant = 1736,
ERR_DefaultValueBeforeRequiredValue = 1737,
ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738,
ERR_BadNamedArgument = 1739,
ERR_DuplicateNamedArgument = 1740,
ERR_RefOutDefaultValue = 1741,
ERR_NamedArgumentForArray = 1742,
ERR_DefaultValueForExtensionParameter = 1743,
ERR_NamedArgumentUsedInPositional = 1744,
ERR_DefaultValueUsedWithAttributes = 1745,
ERR_BadNamedArgumentForDelegateInvoke = 1746,
ERR_NoPIAAssemblyMissingAttribute = 1747,
ERR_NoCanonicalView = 1748,
//ERR_TypeNotFoundForNoPIA = 1749,
ERR_NoConversionForDefaultParam = 1750,
ERR_DefaultValueForParamsParameter = 1751,
ERR_NewCoClassOnLink = 1752,
ERR_NoPIANestedType = 1754,
//ERR_InvalidTypeIdentifierConstructor = 1755,
ERR_InteropTypeMissingAttribute = 1756,
ERR_InteropStructContainsMethods = 1757,
ERR_InteropTypesWithSameNameAndGuid = 1758,
ERR_NoPIAAssemblyMissingAttributes = 1759,
ERR_AssemblySpecifiedForLinkAndRef = 1760,
ERR_LocalTypeNameClash = 1761,
WRN_ReferencedAssemblyReferencesLinkedPIA = 1762,
ERR_NotNullRefDefaultParameter = 1763,
ERR_FixedLocalInLambda = 1764,
// WRN_TypeNotFoundForNoPIAWarning = 1765, // This error code is unused.
ERR_MissingMethodOnSourceInterface = 1766,
ERR_MissingSourceInterface = 1767,
ERR_GenericsUsedInNoPIAType = 1768,
ERR_GenericsUsedAcrossAssemblies = 1769,
ERR_NoConversionForNubDefaultParam = 1770,
//ERR_MemberWithGenericsUsedAcrossAssemblies = 1771,
//ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772,
ERR_InvalidSubsystemVersion = 1773,
ERR_InteropMethodWithBody = 1774,
// unused 1775-1899
ERR_BadWarningLevel = 1900,
ERR_BadDebugType = 1902,
//ERR_UnknownTestSwitch = 1903,
ERR_BadResourceVis = 1906,
ERR_DefaultValueTypeMustMatch = 1908,
//ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn.
ERR_DefaultValueBadValueType = 1910,
ERR_MemberAlreadyInitialized = 1912,
ERR_MemberCannotBeInitialized = 1913,
ERR_StaticMemberInObjectInitializer = 1914,
ERR_ReadonlyValueTypeInObjectInitializer = 1917,
ERR_ValueTypePropertyInObjectInitializer = 1918,
ERR_UnsafeTypeInObjectCreation = 1919,
ERR_EmptyElementInitializer = 1920,
ERR_InitializerAddHasWrongSignature = 1921,
ERR_CollectionInitRequiresIEnumerable = 1922,
//ERR_InvalidCollectionInitializerType = 1925, unused in Roslyn. Occurs so infrequently in real usage that it is not worth reimplementing.
ERR_CantOpenWin32Manifest = 1926,
WRN_CantHaveManifestForModule = 1927,
//ERR_BadExtensionArgTypes = 1928, unused in Roslyn (replaced by ERR_BadInstanceArgType)
ERR_BadInstanceArgType = 1929,
ERR_QueryDuplicateRangeVariable = 1930,
ERR_QueryRangeVariableOverrides = 1931,
ERR_QueryRangeVariableAssignedBadValue = 1932,
//ERR_QueryNotAllowed = 1933, unused in Roslyn. This specific message is not necessary for correctness and adds little.
ERR_QueryNoProviderCastable = 1934,
ERR_QueryNoProviderStandard = 1935,
ERR_QueryNoProvider = 1936,
ERR_QueryOuterKey = 1937,
ERR_QueryInnerKey = 1938,
ERR_QueryOutRefRangeVariable = 1939,
ERR_QueryMultipleProviders = 1940,
ERR_QueryTypeInferenceFailedMulti = 1941,
ERR_QueryTypeInferenceFailed = 1942,
ERR_QueryTypeInferenceFailedSelectMany = 1943,
ERR_ExpressionTreeContainsPointerOp = 1944,
ERR_ExpressionTreeContainsAnonymousMethod = 1945,
ERR_AnonymousMethodToExpressionTree = 1946,
ERR_QueryRangeVariableReadOnly = 1947,
ERR_QueryRangeVariableSameAsTypeParam = 1948,
ERR_TypeVarNotFoundRangeVariable = 1949,
ERR_BadArgTypesForCollectionAdd = 1950,
ERR_ByRefParameterInExpressionTree = 1951,
ERR_VarArgsInExpressionTree = 1952,
// ERR_MemGroupInExpressionTree = 1953, unused in Roslyn (replaced by ERR_LambdaInIsAs)
ERR_InitializerAddHasParamModifiers = 1954,
ERR_NonInvocableMemberCalled = 1955,
WRN_MultipleRuntimeImplementationMatches = 1956,
WRN_MultipleRuntimeOverrideMatches = 1957,
ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958,
ERR_InvalidConstantDeclarationType = 1959,
ERR_IllegalVarianceSyntax = 1960,
ERR_UnexpectedVariance = 1961,
ERR_BadDynamicTypeof = 1962,
ERR_ExpressionTreeContainsDynamicOperation = 1963,
ERR_BadDynamicConversion = 1964,
ERR_DeriveFromDynamic = 1965,
ERR_DeriveFromConstructedDynamic = 1966,
ERR_DynamicTypeAsBound = 1967,
ERR_ConstructedDynamicTypeAsBound = 1968,
ERR_DynamicRequiredTypesMissing = 1969,
ERR_ExplicitDynamicAttr = 1970,
ERR_NoDynamicPhantomOnBase = 1971,
ERR_NoDynamicPhantomOnBaseIndexer = 1972,
ERR_BadArgTypeDynamicExtension = 1973,
WRN_DynamicDispatchToConditionalMethod = 1974,
ERR_NoDynamicPhantomOnBaseCtor = 1975,
ERR_BadDynamicMethodArgMemgrp = 1976,
ERR_BadDynamicMethodArgLambda = 1977,
ERR_BadDynamicMethodArg = 1978,
ERR_BadDynamicQuery = 1979,
ERR_DynamicAttributeMissing = 1980,
WRN_IsDynamicIsConfusing = 1981,
//ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn.
ERR_BadAsyncReturn = 1983,
ERR_BadAwaitInFinally = 1984,
ERR_BadAwaitInCatch = 1985,
ERR_BadAwaitArg = 1986,
ERR_BadAsyncArgType = 1988,
ERR_BadAsyncExpressionTree = 1989,
//ERR_WindowsRuntimeTypesMissing = 1990, // unused in Roslyn
ERR_MixingWinRTEventWithRegular = 1991,
ERR_BadAwaitWithoutAsync = 1992,
//ERR_MissingAsyncTypes = 1993, // unused in Roslyn
ERR_BadAsyncLacksBody = 1994,
ERR_BadAwaitInQuery = 1995,
ERR_BadAwaitInLock = 1996,
ERR_TaskRetNoObjectRequired = 1997,
WRN_AsyncLacksAwaits = 1998,
ERR_FileNotFound = 2001,
WRN_FileAlreadyIncluded = 2002,
//ERR_DuplicateResponseFile = 2003,
ERR_NoFileSpec = 2005,
ERR_SwitchNeedsString = 2006,
ERR_BadSwitch = 2007,
WRN_NoSources = 2008,
ERR_OpenResponseFile = 2011,
ERR_CantOpenFileWrite = 2012,
ERR_BadBaseNumber = 2013,
// WRN_UseNewSwitch = 2014, //unused.
ERR_BinaryFile = 2015,
FTL_BadCodepage = 2016,
ERR_NoMainOnDLL = 2017,
//FTL_NoMessagesDLL = 2018,
FTL_InvalidTarget = 2019,
//ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once!
FTL_InvalidInputFileName = 2021,
//ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once!
WRN_NoConfigNotOnCommandLine = 2023,
ERR_InvalidFileAlignment = 2024,
//ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn.
//ERR_SourceMapFileBinary = 2027,
WRN_DefineIdentifierRequired = 2029,
//ERR_InvalidSourceMap = 2030,
//ERR_NoSourceMapFile = 2031,
//ERR_IllegalOptionChar = 2032,
FTL_OutputFileExists = 2033,
ERR_OneAliasPerReference = 2034,
ERR_SwitchNeedsNumber = 2035,
ERR_MissingDebugSwitch = 2036,
ERR_ComRefCallInExpressionTree = 2037,
WRN_BadUILang = 2038,
ERR_InvalidFormatForGuidForOption = 2039,
ERR_MissingGuidForOption = 2040,
ERR_InvalidOutputName = 2041,
ERR_InvalidDebugInformationFormat = 2042,
ERR_LegacyObjectIdSyntax = 2043,
ERR_SourceLinkRequiresPdb = 2044,
ERR_CannotEmbedWithoutPdb = 2045,
ERR_BadSwitchValue = 2046,
// unused 2047-2999
WRN_CLS_NoVarArgs = 3000,
WRN_CLS_BadArgType = 3001, // Requires SymbolDistinguisher.
WRN_CLS_BadReturnType = 3002,
WRN_CLS_BadFieldPropType = 3003,
// WRN_CLS_BadUnicode = 3004, //unused
WRN_CLS_BadIdentifierCase = 3005,
WRN_CLS_OverloadRefOut = 3006,
WRN_CLS_OverloadUnnamed = 3007,
WRN_CLS_BadIdentifier = 3008,
WRN_CLS_BadBase = 3009,
WRN_CLS_BadInterfaceMember = 3010,
WRN_CLS_NoAbstractMembers = 3011,
WRN_CLS_NotOnModules = 3012,
WRN_CLS_ModuleMissingCLS = 3013,
WRN_CLS_AssemblyNotCLS = 3014,
WRN_CLS_BadAttributeType = 3015,
WRN_CLS_ArrayArgumentToAttribute = 3016,
WRN_CLS_NotOnModules2 = 3017,
WRN_CLS_IllegalTrueInFalse = 3018,
WRN_CLS_MeaninglessOnPrivateType = 3019,
WRN_CLS_AssemblyNotCLS2 = 3021,
WRN_CLS_MeaninglessOnParam = 3022,
WRN_CLS_MeaninglessOnReturn = 3023,
WRN_CLS_BadTypeVar = 3024,
WRN_CLS_VolatileField = 3026,
WRN_CLS_BadInterface = 3027,
FTL_BadChecksumAlgorithm = 3028,
#endregion diagnostics introduced in C# 4 and earlier
// unused 3029-3999
#region diagnostics introduced in C# 5
// 4000 unused
ERR_BadAwaitArgIntrinsic = 4001,
// 4002 unused
ERR_BadAwaitAsIdentifier = 4003,
ERR_AwaitInUnsafeContext = 4004,
ERR_UnsafeAsyncArgType = 4005,
ERR_VarargsAsync = 4006,
ERR_ByRefTypeAndAwait = 4007,
ERR_BadAwaitArgVoidCall = 4008,
ERR_NonTaskMainCantBeAsync = 4009,
ERR_CantConvAsyncAnonFuncReturns = 4010,
ERR_BadAwaiterPattern = 4011,
ERR_BadSpecialByRefLocal = 4012,
ERR_SpecialByRefInLambda = 4013,
WRN_UnobservedAwaitableExpression = 4014,
ERR_SynchronizedAsyncMethod = 4015,
ERR_BadAsyncReturnExpression = 4016,
ERR_NoConversionForCallerLineNumberParam = 4017,
ERR_NoConversionForCallerFilePathParam = 4018,
ERR_NoConversionForCallerMemberNameParam = 4019,
ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020,
ERR_BadCallerFilePathParamWithoutDefaultValue = 4021,
ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022,
ERR_BadPrefer32OnLib = 4023,
WRN_CallerLineNumberParamForUnconsumedLocation = 4024,
WRN_CallerFilePathParamForUnconsumedLocation = 4025,
WRN_CallerMemberNameParamForUnconsumedLocation = 4026,
ERR_DoesntImplementAwaitInterface = 4027,
ERR_BadAwaitArg_NeedSystem = 4028,
ERR_CantReturnVoid = 4029,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031,
ERR_BadAwaitWithoutAsyncMethod = 4032,
ERR_BadAwaitWithoutVoidAsyncMethod = 4033,
ERR_BadAwaitWithoutAsyncLambda = 4034,
// ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn
ERR_NoSuchMemberOrExtensionNeedUsing = 4036,
#endregion diagnostics introduced in C# 5
// unused 4037-4999
#region diagnostics introduced in C# 6
// WRN_UnknownOption = 5000, //unused in Roslyn
ERR_NoEntryPoint = 5001,
// huge gap here; available 5002-6999
ERR_UnexpectedAliasedName = 7000,
ERR_UnexpectedGenericName = 7002,
ERR_UnexpectedUnboundGenericName = 7003,
ERR_GlobalStatement = 7006,
ERR_BadUsingType = 7007,
ERR_ReservedAssemblyName = 7008,
ERR_PPReferenceFollowsToken = 7009,
ERR_ExpectedPPFile = 7010,
ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011,
ERR_NameNotInContextPossibleMissingReference = 7012,
ERR_MetadataNameTooLong = 7013,
ERR_AttributesNotAllowed = 7014,
ERR_ExternAliasNotAllowed = 7015,
ERR_ConflictingAliasAndDefinition = 7016,
ERR_GlobalDefinitionOrStatementExpected = 7017,
ERR_ExpectedSingleScript = 7018,
ERR_RecursivelyTypedVariable = 7019,
ERR_YieldNotAllowedInScript = 7020,
ERR_NamespaceNotAllowedInScript = 7021,
WRN_MainIgnored = 7022,
WRN_StaticInAsOrIs = 7023,
ERR_InvalidDelegateType = 7024,
ERR_BadVisEventType = 7025,
ERR_GlobalAttributesNotAllowed = 7026,
ERR_PublicKeyFileFailure = 7027,
ERR_PublicKeyContainerFailure = 7028,
ERR_FriendRefSigningMismatch = 7029,
ERR_CannotPassNullForFriendAssembly = 7030,
ERR_SignButNoPrivateKey = 7032,
WRN_DelaySignButNoKey = 7033,
ERR_InvalidVersionFormat = 7034,
WRN_InvalidVersionFormat = 7035,
ERR_NoCorrespondingArgument = 7036,
// Moot: WRN_DestructorIsNotFinalizer = 7037,
ERR_ModuleEmitFailure = 7038,
// ERR_NameIllegallyOverrides2 = 7039, // Not used anymore due to 'Single Meaning' relaxation changes
// ERR_NameIllegallyOverrides3 = 7040, // Not used anymore due to 'Single Meaning' relaxation changes
ERR_ResourceFileNameNotUnique = 7041,
ERR_DllImportOnGenericMethod = 7042,
ERR_EncUpdateFailedMissingAttribute = 7043,
ERR_ParameterNotValidForType = 7045,
ERR_AttributeParameterRequired1 = 7046,
ERR_AttributeParameterRequired2 = 7047,
ERR_SecurityAttributeMissingAction = 7048,
ERR_SecurityAttributeInvalidAction = 7049,
ERR_SecurityAttributeInvalidActionAssembly = 7050,
ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051,
ERR_PrincipalPermissionInvalidAction = 7052,
ERR_FeatureNotValidInExpressionTree = 7053,
ERR_MarshalUnmanagedTypeNotValidForFields = 7054,
ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055,
ERR_PermissionSetAttributeInvalidFile = 7056,
ERR_PermissionSetAttributeFileReadError = 7057,
ERR_InvalidVersionFormat2 = 7058,
ERR_InvalidAssemblyCultureForExe = 7059,
//ERR_AsyncBeforeVersionFive = 7060,
ERR_DuplicateAttributeInNetModule = 7061,
//WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning
ERR_CantOpenIcon = 7064,
ERR_ErrorBuildingWin32Resources = 7065,
// ERR_IteratorInInteractive = 7066,
ERR_BadAttributeParamDefaultArgument = 7067,
ERR_MissingTypeInSource = 7068,
ERR_MissingTypeInAssembly = 7069,
ERR_SecurityAttributeInvalidTarget = 7070,
ERR_InvalidAssemblyName = 7071,
//ERR_PartialTypesBeforeVersionTwo = 7072,
//ERR_PartialMethodsBeforeVersionThree = 7073,
//ERR_QueryBeforeVersionThree = 7074,
//ERR_AnonymousTypeBeforeVersionThree = 7075,
//ERR_ImplicitArrayBeforeVersionThree = 7076,
//ERR_ObjectInitializerBeforeVersionThree = 7077,
//ERR_LambdaBeforeVersionThree = 7078,
ERR_NoTypeDefFromModule = 7079,
WRN_CallerFilePathPreferredOverCallerMemberName = 7080,
WRN_CallerLineNumberPreferredOverCallerMemberName = 7081,
WRN_CallerLineNumberPreferredOverCallerFilePath = 7082,
ERR_InvalidDynamicCondition = 7083,
ERR_WinRtEventPassedByRef = 7084,
//ERR_ByRefReturnUnsupported = 7085,
ERR_NetModuleNameMismatch = 7086,
ERR_BadModuleName = 7087,
ERR_BadCompilationOptionValue = 7088,
ERR_BadAppConfigPath = 7089,
WRN_AssemblyAttributeFromModuleIsOverridden = 7090,
ERR_CmdOptionConflictsSource = 7091,
ERR_FixedBufferTooManyDimensions = 7092,
ERR_CantReadConfigFile = 7093,
ERR_BadAwaitInCatchFilter = 7094,
WRN_FilterIsConstantTrue = 7095,
ERR_EncNoPIAReference = 7096,
//ERR_EncNoDynamicOperation = 7097, // dynamic operations are now allowed
ERR_LinkedNetmoduleMetadataMustProvideFullPEImage = 7098,
ERR_MetadataReferencesNotSupported = 7099,
ERR_InvalidAssemblyCulture = 7100,
ERR_EncReferenceToAddedMember = 7101,
ERR_MutuallyExclusiveOptions = 7102,
ERR_InvalidDebugInfo = 7103,
#endregion diagnostics introduced in C# 6
// unused 7104-8000
#region more diagnostics introduced in Roslyn (C# 6)
WRN_UnimplementedCommandLineSwitch = 8001,
WRN_ReferencedAssemblyDoesNotHaveStrongName = 8002,
ERR_InvalidSignaturePublicKey = 8003,
ERR_ExportedTypeConflictsWithDeclaration = 8004,
ERR_ExportedTypesConflict = 8005,
ERR_ForwardedTypeConflictsWithDeclaration = 8006,
ERR_ForwardedTypesConflict = 8007,
ERR_ForwardedTypeConflictsWithExportedType = 8008,
WRN_RefCultureMismatch = 8009,
ERR_AgnosticToMachineModule = 8010,
ERR_ConflictingMachineModule = 8011,
WRN_ConflictingMachineAssembly = 8012,
ERR_CryptoHashFailed = 8013,
ERR_MissingNetModuleReference = 8014,
ERR_NetModuleNameMustBeUnique = 8015,
ERR_UnsupportedTransparentIdentifierAccess = 8016,
ERR_ParamDefaultValueDiffersFromAttribute = 8017,
WRN_UnqualifiedNestedTypeInCref = 8018,
HDN_UnusedUsingDirective = 8019,
HDN_UnusedExternAlias = 8020,
WRN_NoRuntimeMetadataVersion = 8021,
ERR_FeatureNotAvailableInVersion1 = 8022, // Note: one per version to make telemetry easier
ERR_FeatureNotAvailableInVersion2 = 8023,
ERR_FeatureNotAvailableInVersion3 = 8024,
ERR_FeatureNotAvailableInVersion4 = 8025,
ERR_FeatureNotAvailableInVersion5 = 8026,
// ERR_FeatureNotAvailableInVersion6 is below
ERR_FieldHasMultipleDistinctConstantValues = 8027,
ERR_ComImportWithInitializers = 8028,
WRN_PdbLocalNameTooLong = 8029,
ERR_RetNoObjectRequiredLambda = 8030,
ERR_TaskRetNoObjectRequiredLambda = 8031,
WRN_AnalyzerCannotBeCreated = 8032,
WRN_NoAnalyzerInAssembly = 8033,
WRN_UnableToLoadAnalyzer = 8034,
ERR_CantReadRulesetFile = 8035,
ERR_BadPdbData = 8036,
// available 8037-8039
INF_UnableToLoadSomeTypesInAnalyzer = 8040,
// available 8041-8049
ERR_InitializerOnNonAutoProperty = 8050,
ERR_AutoPropertyMustHaveGetAccessor = 8051,
// ERR_AutoPropertyInitializerInInterface = 8052,
ERR_InstancePropertyInitializerInInterface = 8053,
ERR_EnumsCantContainDefaultConstructor = 8054,
ERR_EncodinglessSyntaxTree = 8055,
// ERR_AccessorListAndExpressionBody = 8056, Deprecated in favor of ERR_BlockBodyAndExpressionBody
ERR_BlockBodyAndExpressionBody = 8057,
ERR_FeatureIsExperimental = 8058,
ERR_FeatureNotAvailableInVersion6 = 8059,
// available 8062-8069
ERR_SwitchFallOut = 8070,
// available = 8071,
ERR_NullPropagatingOpInExpressionTree = 8072,
WRN_NubExprIsConstBool2 = 8073,
ERR_DictionaryInitializerInExpressionTree = 8074,
ERR_ExtensionCollectionElementInitializerInExpressionTree = 8075,
ERR_UnclosedExpressionHole = 8076,
ERR_SingleLineCommentInExpressionHole = 8077,
ERR_InsufficientStack = 8078,
ERR_UseDefViolationProperty = 8079,
ERR_AutoPropertyMustOverrideSet = 8080,
ERR_ExpressionHasNoName = 8081,
ERR_SubexpressionNotInNameof = 8082,
ERR_AliasQualifiedNameNotAnExpression = 8083,
ERR_NameofMethodGroupWithTypeParameters = 8084,
ERR_NoAliasHere = 8085,
ERR_UnescapedCurly = 8086,
ERR_EscapedCurly = 8087,
ERR_TrailingWhitespaceInFormatSpecifier = 8088,
ERR_EmptyFormatSpecifier = 8089,
ERR_ErrorInReferencedAssembly = 8090,
ERR_ExternHasConstructorInitializer = 8091,
ERR_ExpressionOrDeclarationExpected = 8092,
ERR_NameofExtensionMethod = 8093,
WRN_AlignmentMagnitude = 8094,
ERR_ConstantStringTooLong = 8095,
ERR_DebugEntryPointNotSourceMethodDefinition = 8096,
ERR_LoadDirectiveOnlyAllowedInScripts = 8097,
ERR_PPLoadFollowsToken = 8098,
ERR_SourceFileReferencesNotSupported = 8099,
ERR_BadAwaitInStaticVariableInitializer = 8100,
ERR_InvalidPathMap = 8101,
ERR_PublicSignButNoKey = 8102,
ERR_TooManyUserStrings = 8103,
ERR_PeWritingFailure = 8104,
#endregion diagnostics introduced in Roslyn (C# 6)
#region diagnostics introduced in C# 6 updates
WRN_AttributeIgnoredWhenPublicSigning = 8105,
ERR_OptionMustBeAbsolutePath = 8106,
#endregion diagnostics introduced in C# 6 updates
ERR_FeatureNotAvailableInVersion7 = 8107,
#region diagnostics for local functions introduced in C# 7
ERR_DynamicLocalFunctionParamsParameter = 8108,
ERR_ExpressionTreeContainsLocalFunction = 8110,
#endregion diagnostics for local functions introduced in C# 7
#region diagnostics for instrumentation
ERR_InvalidInstrumentationKind = 8111,
#endregion
ERR_LocalFunctionMissingBody = 8112,
ERR_InvalidHashAlgorithmName = 8113,
// Unused 8113, 8114, 8115
#region diagnostics for pattern-matching introduced in C# 7
ERR_ThrowMisplaced = 8115,
ERR_PatternNullableType = 8116,
ERR_BadPatternExpression = 8117,
ERR_SwitchExpressionValueExpected = 8119,
ERR_SwitchCaseSubsumed = 8120,
ERR_PatternWrongType = 8121,
ERR_ExpressionTreeContainsIsMatch = 8122,
#endregion diagnostics for pattern-matching introduced in C# 7
#region tuple diagnostics introduced in C# 7
WRN_TupleLiteralNameMismatch = 8123,
ERR_TupleTooFewElements = 8124,
ERR_TupleReservedElementName = 8125,
ERR_TupleReservedElementNameAnyPosition = 8126,
ERR_TupleDuplicateElementName = 8127,
ERR_PredefinedTypeMemberNotFoundInAssembly = 8128,
ERR_MissingDeconstruct = 8129,
ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable = 8130,
ERR_DeconstructRequiresExpression = 8131,
ERR_DeconstructWrongCardinality = 8132,
ERR_CannotDeconstructDynamic = 8133,
ERR_DeconstructTooFewElements = 8134,
ERR_ConversionNotTupleCompatible = 8135,
ERR_DeconstructionVarFormDisallowsSpecificType = 8136,
ERR_TupleElementNamesAttributeMissing = 8137,
ERR_ExplicitTupleElementNamesAttribute = 8138,
ERR_CantChangeTupleNamesOnOverride = 8139,
ERR_DuplicateInterfaceWithTupleNamesInBaseList = 8140,
ERR_ImplBadTupleNames = 8141,
ERR_PartialMethodInconsistentTupleNames = 8142,
ERR_ExpressionTreeContainsTupleLiteral = 8143,
ERR_ExpressionTreeContainsTupleConversion = 8144,
#endregion tuple diagnostics introduced in C# 7
#region diagnostics for ref locals and ref returns introduced in C# 7
ERR_AutoPropertyCannotBeRefReturning = 8145,
ERR_RefPropertyMustHaveGetAccessor = 8146,
ERR_RefPropertyCannotHaveSetAccessor = 8147,
ERR_CantChangeRefReturnOnOverride = 8148,
ERR_MustNotHaveRefReturn = 8149,
ERR_MustHaveRefReturn = 8150,
ERR_RefReturnMustHaveIdentityConversion = 8151,
ERR_CloseUnimplementedInterfaceMemberWrongRefReturn = 8152,
ERR_RefReturningCallInExpressionTree = 8153,
ERR_BadIteratorReturnRef = 8154,
ERR_BadRefReturnExpressionTree = 8155,
ERR_RefReturnLvalueExpected = 8156,
ERR_RefReturnNonreturnableLocal = 8157,
ERR_RefReturnNonreturnableLocal2 = 8158,
ERR_RefReturnRangeVariable = 8159,
ERR_RefReturnReadonly = 8160,
ERR_RefReturnReadonlyStatic = 8161,
ERR_RefReturnReadonly2 = 8162,
ERR_RefReturnReadonlyStatic2 = 8163,
// ERR_RefReturnCall = 8164, we use more general ERR_EscapeCall now
// ERR_RefReturnCall2 = 8165, we use more general ERR_EscapeCall2 now
ERR_RefReturnParameter = 8166,
ERR_RefReturnParameter2 = 8167,
ERR_RefReturnLocal = 8168,
ERR_RefReturnLocal2 = 8169,
ERR_RefReturnStructThis = 8170,
ERR_InitializeByValueVariableWithReference = 8171,
ERR_InitializeByReferenceVariableWithValue = 8172,
ERR_RefAssignmentMustHaveIdentityConversion = 8173,
ERR_ByReferenceVariableMustBeInitialized = 8174,
ERR_AnonDelegateCantUseLocal = 8175,
ERR_BadIteratorLocalType = 8176,
ERR_BadAsyncLocalType = 8177,
ERR_RefReturningCallAndAwait = 8178,
#endregion diagnostics for ref locals and ref returns introduced in C# 7
#region stragglers for C# 7
ERR_PredefinedValueTupleTypeNotFound = 8179, // We need a specific error code for ValueTuple as an IDE codefix depends on it (AddNuget)
ERR_SemiOrLBraceOrArrowExpected = 8180,
ERR_NewWithTupleTypeSyntax = 8181,
ERR_PredefinedValueTupleTypeMustBeStruct = 8182,
ERR_DiscardTypeInferenceFailed = 8183,
// ERR_MixedDeconstructionUnsupported = 8184,
ERR_DeclarationExpressionNotPermitted = 8185,
ERR_MustDeclareForeachIteration = 8186,
ERR_TupleElementNamesInDeconstruction = 8187,
ERR_ExpressionTreeContainsThrowExpression = 8188,
ERR_DelegateRefMismatch = 8189,
#endregion stragglers for C# 7
#region diagnostics for parse options
ERR_BadSourceCodeKind = 8190,
ERR_BadDocumentationMode = 8191,
ERR_BadLanguageVersion = 8192,
#endregion
// Unused 8193-8195
#region diagnostics for out var
ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList = 8196,
ERR_TypeInferenceFailedForImplicitlyTypedOutVariable = 8197,
ERR_ExpressionTreeContainsOutVariable = 8198,
#endregion diagnostics for out var
#region more stragglers for C# 7
ERR_VarInvocationLvalueReserved = 8199,
//ERR_ExpressionVariableInConstructorOrFieldInitializer = 8200,
//ERR_ExpressionVariableInQueryClause = 8201,
ERR_PublicSignNetModule = 8202,
ERR_BadAssemblyName = 8203,
ERR_BadAsyncMethodBuilderTaskProperty = 8204,
// ERR_AttributesInLocalFuncDecl = 8205,
ERR_TypeForwardedToMultipleAssemblies = 8206,
ERR_ExpressionTreeContainsDiscard = 8207,
ERR_PatternDynamicType = 8208,
ERR_VoidAssignment = 8209,
ERR_VoidInTuple = 8210,
#endregion more stragglers for C# 7
#region diagnostics introduced for C# 7.1
ERR_Merge_conflict_marker_encountered = 8300,
ERR_InvalidPreprocessingSymbol = 8301,
ERR_FeatureNotAvailableInVersion7_1 = 8302,
ERR_LanguageVersionCannotHaveLeadingZeroes = 8303,
ERR_CompilerAndLanguageVersion = 8304,
WRN_Experimental = 8305,
ERR_TupleInferredNamesNotAvailable = 8306,
ERR_TypelessTupleInAs = 8307,
ERR_NoRefOutWhenRefOnly = 8308,
ERR_NoNetModuleOutputWhenRefOutOrRefOnly = 8309,
ERR_BadOpOnNullOrDefaultOrNew = 8310,
// ERR_BadDynamicMethodArgDefaultLiteral = 8311,
ERR_DefaultLiteralNotValid = 8312,
// ERR_DefaultInSwitch = 8313,
ERR_PatternWrongGenericTypeInVersion = 8314,
ERR_AmbigBinaryOpsOnDefault = 8315,
#endregion diagnostics introduced for C# 7.1
#region diagnostics introduced for C# 7.2
ERR_FeatureNotAvailableInVersion7_2 = 8320,
WRN_UnreferencedLocalFunction = 8321,
ERR_DynamicLocalFunctionTypeParameter = 8322,
ERR_BadNonTrailingNamedArgument = 8323,
ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation = 8324,
#endregion diagnostics introduced for C# 7.2
#region diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2
ERR_RefConditionalAndAwait = 8325,
ERR_RefConditionalNeedsTwoRefs = 8326,
ERR_RefConditionalDifferentTypes = 8327,
ERR_BadParameterModifiers = 8328,
ERR_RefReadonlyNotField = 8329,
ERR_RefReadonlyNotField2 = 8330,
ERR_AssignReadonlyNotField = 8331,
ERR_AssignReadonlyNotField2 = 8332,
ERR_RefReturnReadonlyNotField = 8333,
ERR_RefReturnReadonlyNotField2 = 8334,
ERR_ExplicitReservedAttr = 8335,
ERR_TypeReserved = 8336,
ERR_RefExtensionMustBeValueTypeOrConstrainedToOne = 8337,
ERR_InExtensionMustBeValueType = 8338,
// ERR_BadParameterModifiersOrder = 8339, // Modifier ordering is relaxed
ERR_FieldsInRoStruct = 8340,
ERR_AutoPropsInRoStruct = 8341,
ERR_FieldlikeEventsInRoStruct = 8342,
ERR_RefStructInterfaceImpl = 8343,
ERR_BadSpecialByRefIterator = 8344,
ERR_FieldAutoPropCantBeByRefLike = 8345,
ERR_StackAllocConversionNotPossible = 8346,
ERR_EscapeCall = 8347,
ERR_EscapeCall2 = 8348,
ERR_EscapeOther = 8349,
ERR_CallArgMixing = 8350,
ERR_MismatchedRefEscapeInTernary = 8351,
ERR_EscapeLocal = 8352,
ERR_EscapeStackAlloc = 8353,
ERR_RefReturnThis = 8354,
ERR_OutAttrOnInParam = 8355,
#endregion diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2
ERR_PredefinedValueTupleTypeAmbiguous3 = 8356,
ERR_InvalidVersionFormatDeterministic = 8357,
ERR_AttributeCtorInParameter = 8358,
#region diagnostics for FilterIsConstant warning message fix
WRN_FilterIsConstantFalse = 8359,
WRN_FilterIsConstantFalseRedundantTryCatch = 8360,
#endregion diagnostics for FilterIsConstant warning message fix
ERR_ConditionalInInterpolation = 8361,
ERR_CantUseVoidInArglist = 8362,
ERR_InDynamicMethodArg = 8364,
#region diagnostics introduced for C# 7.3
ERR_FeatureNotAvailableInVersion7_3 = 8370,
WRN_AttributesOnBackingFieldsNotAvailable = 8371,
ERR_DoNotUseFixedBufferAttrOnProperty = 8372,
ERR_RefLocalOrParamExpected = 8373,
ERR_RefAssignNarrower = 8374,
ERR_NewBoundWithUnmanaged = 8375,
//ERR_UnmanagedConstraintMustBeFirst = 8376,
ERR_UnmanagedConstraintNotSatisfied = 8377,
ERR_CantUseInOrOutInArglist = 8378,
ERR_ConWithUnmanagedCon = 8379,
ERR_UnmanagedBoundWithClass = 8380,
ERR_InvalidStackAllocArray = 8381,
ERR_ExpressionTreeContainsTupleBinOp = 8382,
WRN_TupleBinopLiteralNameMismatch = 8383,
ERR_TupleSizesMismatchForBinOps = 8384,
ERR_ExprCannotBeFixed = 8385,
ERR_InvalidObjectCreation = 8386,
#endregion diagnostics introduced for C# 7.3
WRN_TypeParameterSameAsOuterMethodTypeParameter = 8387,
ERR_OutVariableCannotBeByRef = 8388,
ERR_OmittedTypeArgument = 8389,
#region diagnostics introduced for C# 8.0
ERR_FeatureNotAvailableInVersion8 = 8400,
ERR_AltInterpolatedVerbatimStringsNotAvailable = 8401,
// Unused 8402
ERR_IteratorMustBeAsync = 8403,
ERR_NoConvToIAsyncDisp = 8410,
ERR_AwaitForEachMissingMember = 8411,
ERR_BadGetAsyncEnumerator = 8412,
ERR_MultipleIAsyncEnumOfT = 8413,
ERR_ForEachMissingMemberWrongAsync = 8414,
ERR_AwaitForEachMissingMemberWrongAsync = 8415,
ERR_BadDynamicAwaitForEach = 8416,
ERR_NoConvToIAsyncDispWrongAsync = 8417,
ERR_NoConvToIDispWrongAsync = 8418,
ERR_PossibleAsyncIteratorWithoutYield = 8419,
ERR_PossibleAsyncIteratorWithoutYieldOrAwait = 8420,
ERR_StaticLocalFunctionCannotCaptureVariable = 8421,
ERR_StaticLocalFunctionCannotCaptureThis = 8422,
ERR_AttributeNotOnEventAccessor = 8423,
WRN_UnconsumedEnumeratorCancellationAttributeUsage = 8424,
WRN_UndecoratedCancellationTokenParameter = 8425,
ERR_MultipleEnumeratorCancellationAttributes = 8426,
ERR_VarianceInterfaceNesting = 8427,
ERR_ImplicitIndexIndexerWithName = 8428,
ERR_ImplicitRangeIndexerWithName = 8429,
// available range
#region diagnostics introduced for recursive patterns
ERR_WrongNumberOfSubpatterns = 8502,
ERR_PropertyPatternNameMissing = 8503,
ERR_MissingPattern = 8504,
ERR_DefaultPattern = 8505,
ERR_SwitchExpressionNoBestType = 8506,
// ERR_SingleElementPositionalPatternRequiresDisambiguation = 8507, // Retired C# 8 diagnostic
ERR_VarMayNotBindToType = 8508,
WRN_SwitchExpressionNotExhaustive = 8509,
ERR_SwitchArmSubsumed = 8510,
ERR_ConstantPatternVsOpenType = 8511,
WRN_CaseConstantNamedUnderscore = 8512,
WRN_IsTypeNamedUnderscore = 8513,
ERR_ExpressionTreeContainsSwitchExpression = 8514,
ERR_SwitchGoverningExpressionRequiresParens = 8515,
ERR_TupleElementNameMismatch = 8516,
ERR_DeconstructParameterNameMismatch = 8517,
ERR_IsPatternImpossible = 8518,
WRN_GivenExpressionNeverMatchesPattern = 8519,
WRN_GivenExpressionAlwaysMatchesConstant = 8520,
ERR_PointerTypeInPatternMatching = 8521,
ERR_ArgumentNameInITuplePattern = 8522,
ERR_DiscardPatternInSwitchStatement = 8523,
WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue = 8524,
// available 8525-8596
#endregion diagnostics introduced for recursive patterns
WRN_ThrowPossibleNull = 8597,
ERR_IllegalSuppression = 8598,
// available 8599,
WRN_ConvertingNullableToNonNullable = 8600,
WRN_NullReferenceAssignment = 8601,
WRN_NullReferenceReceiver = 8602,
WRN_NullReferenceReturn = 8603,
WRN_NullReferenceArgument = 8604,
WRN_UnboxPossibleNull = 8605,
// WRN_NullReferenceIterationVariable = 8606 (unavailable, may be used in warning suppressions in early C# 8.0 code)
WRN_DisallowNullAttributeForbidsMaybeNullAssignment = 8607,
WRN_NullabilityMismatchInTypeOnOverride = 8608,
WRN_NullabilityMismatchInReturnTypeOnOverride = 8609,
WRN_NullabilityMismatchInParameterTypeOnOverride = 8610,
WRN_NullabilityMismatchInParameterTypeOnPartial = 8611,
WRN_NullabilityMismatchInTypeOnImplicitImplementation = 8612,
WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation = 8613,
WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation = 8614,
WRN_NullabilityMismatchInTypeOnExplicitImplementation = 8615,
WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation = 8616,
WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation = 8617,
WRN_UninitializedNonNullableField = 8618,
WRN_NullabilityMismatchInAssignment = 8619,
WRN_NullabilityMismatchInArgument = 8620,
WRN_NullabilityMismatchInReturnTypeOfTargetDelegate = 8621,
WRN_NullabilityMismatchInParameterTypeOfTargetDelegate = 8622,
ERR_ExplicitNullableAttribute = 8623,
WRN_NullabilityMismatchInArgumentForOutput = 8624,
WRN_NullAsNonNullable = 8625,
//WRN_AsOperatorMayReturnNull = 8626,
ERR_NullableUnconstrainedTypeParameter = 8627,
ERR_AnnotationDisallowedInObjectCreation = 8628,
WRN_NullableValueTypeMayBeNull = 8629,
ERR_NullableOptionNotAvailable = 8630,
WRN_NullabilityMismatchInTypeParameterConstraint = 8631,
WRN_MissingNonNullTypesContextForAnnotation = 8632,
WRN_NullabilityMismatchInConstraintsOnImplicitImplementation = 8633,
WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint = 8634,
ERR_TripleDotNotAllowed = 8635,
ERR_BadNullableContextOption = 8636,
ERR_NullableDirectiveQualifierExpected = 8637,
//WRN_ConditionalAccessMayReturnNull = 8638,
ERR_BadNullableTypeof = 8639,
ERR_ExpressionTreeCantContainRefStruct = 8640,
ERR_ElseCannotStartStatement = 8641,
ERR_ExpressionTreeCantContainNullCoalescingAssignment = 8642,
WRN_NullabilityMismatchInExplicitlyImplementedInterface = 8643,
WRN_NullabilityMismatchInInterfaceImplementedByBase = 8644,
WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList = 8645,
ERR_DuplicateExplicitImpl = 8646,
ERR_UsingVarInSwitchCase = 8647,
ERR_GoToForwardJumpOverUsingVar = 8648,
ERR_GoToBackwardJumpOverUsingVar = 8649,
ERR_IsNullableType = 8650,
ERR_AsNullableType = 8651,
ERR_FeatureInPreview = 8652,
//WRN_DefaultExpressionMayIntroduceNullT = 8653,
//WRN_NullLiteralMayIntroduceNullT = 8654,
WRN_SwitchExpressionNotExhaustiveForNull = 8655,
WRN_ImplicitCopyInReadOnlyMember = 8656,
ERR_StaticMemberCantBeReadOnly = 8657,
ERR_AutoSetterCantBeReadOnly = 8658,
ERR_AutoPropertyWithSetterCantBeReadOnly = 8659,
ERR_InvalidPropertyReadOnlyMods = 8660,
ERR_DuplicatePropertyReadOnlyMods = 8661,
ERR_FieldLikeEventCantBeReadOnly = 8662,
ERR_PartialMethodReadOnlyDifference = 8663,
ERR_ReadOnlyModMissingAccessor = 8664,
ERR_OverrideRefConstraintNotSatisfied = 8665,
ERR_OverrideValConstraintNotSatisfied = 8666,
WRN_NullabilityMismatchInConstraintsOnPartialImplementation = 8667,
ERR_NullableDirectiveTargetExpected = 8668,
WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode = 8669,
WRN_NullReferenceInitializer = 8670,
ERR_MultipleAnalyzerConfigsInSameDir = 8700,
ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation = 8701,
ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember = 8702,
ERR_InvalidModifierForLanguageVersion = 8703,
ERR_ImplicitImplementationOfNonPublicInterfaceMember = 8704,
ERR_MostSpecificImplementationIsNotFound = 8705,
ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember = 8706,
ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember = 8707,
//ERR_NotBaseOrImplementedInterface = 8708,
//ERR_NotImplementedInBase = 8709,
//ERR_NotDeclaredInBase = 8710,
ERR_DefaultInterfaceImplementationInNoPIAType = 8711,
ERR_AbstractEventHasAccessors = 8712,
//ERR_NotNullConstraintMustBeFirst = 8713,
WRN_NullabilityMismatchInTypeParameterNotNullConstraint = 8714,
ERR_DuplicateNullSuppression = 8715,
ERR_DefaultLiteralNoTargetType = 8716,
ERR_ReAbstractionInNoPIAType = 8750,
#endregion diagnostics introduced for C# 8.0
#region diagnostics introduced in C# 9.0
ERR_InternalError = 8751,
ERR_ImplicitObjectCreationIllegalTargetType = 8752,
ERR_ImplicitObjectCreationNotValid = 8753,
ERR_ImplicitObjectCreationNoTargetType = 8754,
ERR_BadFuncPointerParamModifier = 8755,
ERR_BadFuncPointerArgCount = 8756,
ERR_MethFuncPtrMismatch = 8757,
ERR_FuncPtrRefMismatch = 8758,
ERR_FuncPtrMethMustBeStatic = 8759,
ERR_ExternEventInitializer = 8760,
ERR_AmbigBinaryOpsOnUnconstrainedDefault = 8761,
WRN_ParameterConditionallyDisallowsNull = 8762,
WRN_ShouldNotReturn = 8763,
WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride = 8764,
WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride = 8765,
WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation = 8766,
WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation = 8767,
WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation = 8768,
WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation = 8769,
WRN_DoesNotReturnMismatch = 8770,
ERR_NoOutputDirectory = 8771,
ERR_StdInOptionProvidedButConsoleInputIsNotRedirected = 8772,
ERR_FeatureNotAvailableInVersion9 = 8773,
WRN_MemberNotNull = 8774,
WRN_MemberNotNullWhen = 8775,
WRN_MemberNotNullBadMember = 8776,
WRN_ParameterDisallowsNull = 8777,
WRN_ConstOutOfRangeChecked = 8778,
ERR_DuplicateInterfaceWithDifferencesInBaseList = 8779,
ERR_DesignatorBeneathPatternCombinator = 8780,
ERR_UnsupportedTypeForRelationalPattern = 8781,
ERR_RelationalPatternWithNaN = 8782,
ERR_ConditionalOnLocalFunction = 8783,
WRN_GeneratorFailedDuringInitialization = 8784,
WRN_GeneratorFailedDuringGeneration = 8785,
ERR_WrongFuncPtrCallingConvention = 8786,
ERR_MissingAddressOf = 8787,
ERR_CannotUseReducedExtensionMethodInAddressOf = 8788,
ERR_CannotUseFunctionPointerAsFixedLocal = 8789,
ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer = 8790,
ERR_ExpressionTreeContainsFromEndIndexExpression = 8791,
ERR_ExpressionTreeContainsRangeExpression = 8792,
WRN_GivenExpressionAlwaysMatchesPattern = 8793,
WRN_IsPatternAlways = 8794,
ERR_PartialMethodWithAccessibilityModsMustHaveImplementation = 8795,
ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods = 8796,
ERR_PartialMethodWithOutParamMustHaveAccessMods = 8797,
ERR_PartialMethodWithExtendedModMustHaveAccessMods = 8798,
ERR_PartialMethodAccessibilityDifference = 8799,
ERR_PartialMethodExtendedModDifference = 8800,
ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement = 8801,
ERR_SimpleProgramMultipleUnitsWithTopLevelStatements = 8802,
ERR_TopLevelStatementAfterNamespaceOrType = 8803,
ERR_SimpleProgramDisallowsMainType = 8804,
ERR_SimpleProgramNotAnExecutable = 8805,
ERR_UnsupportedCallingConvention = 8806,
ERR_InvalidFunctionPointerCallingConvention = 8807,
ERR_InvalidFuncPointerReturnTypeModifier = 8808,
ERR_DupReturnTypeMod = 8809,
ERR_AddressOfMethodGroupInExpressionTree = 8810,
ERR_CannotConvertAddressOfToDelegate = 8811,
ERR_AddressOfToNonFunctionPointer = 8812,
ERR_ModuleInitializerMethodMustBeOrdinary = 8813,
ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType = 8814,
ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid = 8815,
ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric = 8816,
ERR_PartialMethodReturnTypeDifference = 8817,
ERR_PartialMethodRefReturnDifference = 8818,
WRN_NullabilityMismatchInReturnTypeOnPartial = 8819,
ERR_StaticAnonymousFunctionCannotCaptureVariable = 8820,
ERR_StaticAnonymousFunctionCannotCaptureThis = 8821,
ERR_OverrideDefaultConstraintNotSatisfied = 8822,
ERR_DefaultConstraintOverrideOnly = 8823,
WRN_ParameterNotNullIfNotNull = 8824,
WRN_ReturnNotNullIfNotNull = 8825,
WRN_PartialMethodTypeDifference = 8826,
ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses = 8830,
ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses = 8831,
WRN_SwitchExpressionNotExhaustiveWithWhen = 8846,
WRN_SwitchExpressionNotExhaustiveForNullWithWhen = 8847,
WRN_PrecedenceInversion = 8848,
ERR_ExpressionTreeContainsWithExpression = 8849,
WRN_AnalyzerReferencesFramework = 8850,
// WRN_EqualsWithoutGetHashCode is for object.Equals and works for classes.
// WRN_RecordEqualsWithoutGetHashCode is for IEquatable<T>.Equals and works for records.
WRN_RecordEqualsWithoutGetHashCode = 8851,
ERR_AssignmentInitOnly = 8852,
ERR_CantChangeInitOnlyOnOverride = 8853,
ERR_CloseUnimplementedInterfaceMemberWrongInitOnly = 8854,
ERR_ExplicitPropertyMismatchInitOnly = 8855,
ERR_BadInitAccessor = 8856,
ERR_InvalidWithReceiverType = 8857,
ERR_CannotClone = 8858,
ERR_CloneDisallowedInRecord = 8859,
WRN_RecordNamedDisallowed = 8860,
ERR_UnexpectedArgumentList = 8861,
ERR_UnexpectedOrMissingConstructorInitializerInRecord = 8862,
ERR_MultipleRecordParameterLists = 8863,
ERR_BadRecordBase = 8864,
ERR_BadInheritanceFromRecord = 8865,
ERR_BadRecordMemberForPositionalParameter = 8866,
ERR_NoCopyConstructorInBaseType = 8867,
ERR_CopyConstructorMustInvokeBaseCopyConstructor = 8868,
ERR_DoesNotOverrideMethodFromObject = 8869,
ERR_SealedAPIInRecord = 8870,
ERR_DoesNotOverrideBaseMethod = 8871,
ERR_NotOverridableAPIInRecord = 8872,
ERR_NonPublicAPIInRecord = 8873,
ERR_SignatureMismatchInRecord = 8874,
ERR_NonProtectedAPIInRecord = 8875,
ERR_DoesNotOverrideBaseEqualityContract = 8876,
ERR_StaticAPIInRecord = 8877,
ERR_CopyConstructorWrongAccessibility = 8878,
ERR_NonPrivateAPIInRecord = 8879,
// The following warnings correspond to errors of the same name, but are reported
// when a definite assignment issue is reported due to private fields imported from metadata.
WRN_UnassignedThisAutoProperty = 8880,
WRN_UnassignedThis = 8881,
WRN_ParamUnassigned = 8882,
WRN_UseDefViolationProperty = 8883,
WRN_UseDefViolationField = 8884,
WRN_UseDefViolationThis = 8885,
WRN_UseDefViolationOut = 8886,
WRN_UseDefViolation = 8887,
ERR_CannotSpecifyManagedWithUnmanagedSpecifiers = 8888,
ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv = 8889,
ERR_TypeNotFound = 8890,
ERR_TypeMustBePublic = 8891,
WRN_SyncAndAsyncEntryPoints = 8892,
ERR_InvalidUnmanagedCallersOnlyCallConv = 8893,
ERR_CannotUseManagedTypeInUnmanagedCallersOnly = 8894,
ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric = 8895,
ERR_UnmanagedCallersOnlyRequiresStatic = 8896,
// The following warnings correspond to errors of the same name, but are reported
// as warnings on interface methods and properties due in warning level 5. They
// were not reported at all prior to level 5.
WRN_ParameterIsStaticClass = 8897,
WRN_ReturnTypeIsStaticClass = 8898,
ERR_EntryPointCannotBeUnmanagedCallersOnly = 8899,
ERR_ModuleInitializerCannotBeUnmanagedCallersOnly = 8900,
ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly = 8901,
ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate = 8902,
ERR_InitCannotBeReadonly = 8903,
ERR_UnexpectedVarianceStaticMember = 8904,
ERR_FunctionPointersCannotBeCalledWithNamedArguments = 8905,
ERR_EqualityContractRequiresGetter = 8906,
WRN_UnreadRecordParameter = 8907,
ERR_BadFieldTypeInRecord = 8908,
WRN_DoNotCompareFunctionPointers = 8909,
ERR_RecordAmbigCtor = 8910,
ERR_FunctionPointerTypesInAttributeNotSupported = 8911,
#endregion diagnostics introduced for C# 9.0
#region diagnostics introduced for C# 10.0
ERR_InheritingFromRecordWithSealedToString = 8912,
ERR_HiddenPositionalMember = 8913,
ERR_GlobalUsingInNamespace = 8914,
ERR_GlobalUsingOutOfOrder = 8915,
ERR_AttributesRequireParenthesizedLambdaExpression = 8916,
ERR_CannotInferDelegateType = 8917,
ERR_InvalidNameInSubpattern = 8918,
ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces = 8919,
ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers = 8920,
ERR_BadAbstractUnaryOperatorSignature = 8921,
ERR_BadAbstractIncDecSignature = 8922,
ERR_BadAbstractIncDecRetType = 8923,
ERR_BadAbstractBinaryOperatorSignature = 8924,
ERR_BadAbstractShiftOperatorSignature = 8925,
ERR_BadAbstractStaticMemberAccess = 8926,
ERR_ExpressionTreeContainsAbstractStaticMemberAccess = 8927,
ERR_CloseUnimplementedInterfaceMemberNotStatic = 8928,
ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember = 8929,
ERR_ExplicitImplementationOfOperatorsMustBeStatic = 8930,
ERR_AbstractConversionNotInvolvingContainedType = 8931,
ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod = 8932,
HDN_DuplicateWithGlobalUsing = 8933,
ERR_CantConvAnonMethReturnType = 8934,
ERR_BuilderAttributeDisallowed = 8935,
ERR_FeatureNotAvailableInVersion10 = 8936,
ERR_SimpleProgramIsEmpty = 8937,
ERR_LineSpanDirectiveInvalidValue = 8938,
ERR_LineSpanDirectiveEndLessThanStart = 8939,
ERR_WrongArityAsyncReturn = 8940,
ERR_InterpolatedStringHandlerMethodReturnMalformed = 8941,
ERR_InterpolatedStringHandlerMethodReturnInconsistent = 8942,
ERR_NullInvalidInterpolatedStringHandlerArgumentName = 8943,
ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName = 8944,
ERR_InvalidInterpolatedStringHandlerArgumentName = 8945,
ERR_TypeIsNotAnInterpolatedStringHandlerType = 8946,
WRN_ParameterOccursAfterInterpolatedStringHandlerParameter = 8947,
ERR_CannotUseSelfAsInterpolatedStringHandlerArgument = 8948,
ERR_InterpolatedStringHandlerArgumentAttributeMalformed = 8949,
ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString = 8950,
ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified = 8951,
ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion = 8952,
ERR_InterpolatedStringHandlerCreationCannotUseDynamic = 8953,
ERR_MultipleFileScopedNamespace = 8954,
ERR_FileScopedAndNormalNamespace = 8955,
ERR_FileScopedNamespaceNotBeforeAllMembers = 8956,
ERR_NoImplicitConvTargetTypedConditional = 8957,
ERR_NonPublicParameterlessStructConstructor = 8958,
ERR_NoConversionForCallerArgumentExpressionParam = 8959,
WRN_CallerLineNumberPreferredOverCallerArgumentExpression = 8960,
WRN_CallerFilePathPreferredOverCallerArgumentExpression = 8961,
WRN_CallerMemberNamePreferredOverCallerArgumentExpression = 8962,
WRN_CallerArgumentExpressionAttributeHasInvalidParameterName = 8963,
ERR_BadCallerArgumentExpressionParamWithoutDefaultValue = 8964,
WRN_CallerArgumentExpressionAttributeSelfReferential = 8965,
WRN_CallerArgumentExpressionParamForUnconsumedLocation = 8966,
ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString = 8967,
ERR_AttrTypeArgCannotBeTypeVar = 8968,
// WRN_AttrDependentTypeNotAllowed = 8969, // Backed out of of warning wave 6, may be reintroduced later
ERR_AttrDependentTypeNotAllowed = 8970,
WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters = 8971,
#endregion
// Note: you will need to re-generate compiler code after adding warnings (eng\generate-compiler-code.cmd)
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum ErrorCode
{
Void = InternalErrorCode.Void,
Unknown = InternalErrorCode.Unknown,
#region diagnostics introduced in C# 4 and earlier
//FTL_InternalError = 1,
//FTL_FailedToLoadResource = 2,
//FTL_NoMemory = 3,
//ERR_WarningAsError = 4,
//ERR_MissingOptionArg = 5,
ERR_NoMetadataFile = 6,
//FTL_ComPlusInit = 7,
//FTL_MetadataImportFailure = 8, no longer used in Roslyn.
FTL_MetadataCantOpenFile = 9,
//ERR_FatalError = 10,
//ERR_CantImportBase = 11,
ERR_NoTypeDef = 12,
//FTL_MetadataEmitFailure = 13, Roslyn does not catch stream writing exceptions. Those are propagated to the caller.
//FTL_RequiredFileNotFound = 14,
//ERR_ClassNameTooLong = 15, Deprecated in favor of ERR_MetadataNameTooLong.
ERR_OutputWriteFailed = 16,
ERR_MultipleEntryPoints = 17,
//ERR_UnimplementedOp = 18,
ERR_BadBinaryOps = 19,
ERR_IntDivByZero = 20,
ERR_BadIndexLHS = 21,
ERR_BadIndexCount = 22,
ERR_BadUnaryOp = 23,
//ERR_NoStdLib = 25, not used in Roslyn
ERR_ThisInStaticMeth = 26,
ERR_ThisInBadContext = 27,
WRN_InvalidMainSig = 28,
ERR_NoImplicitConv = 29, // Requires SymbolDistinguisher.
ERR_NoExplicitConv = 30, // Requires SymbolDistinguisher.
ERR_ConstOutOfRange = 31,
ERR_AmbigBinaryOps = 34,
ERR_AmbigUnaryOp = 35,
ERR_InAttrOnOutParam = 36,
ERR_ValueCantBeNull = 37,
//ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired "An object reference is required for the non-static..."
ERR_NoExplicitBuiltinConv = 39, // Requires SymbolDistinguisher.
//FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
FTL_DebugEmitFailure = 41,
//FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info.
//FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
ERR_BadVisReturnType = 50,
ERR_BadVisParamType = 51,
ERR_BadVisFieldType = 52,
ERR_BadVisPropertyType = 53,
ERR_BadVisIndexerReturn = 54,
ERR_BadVisIndexerParam = 55,
ERR_BadVisOpReturn = 56,
ERR_BadVisOpParam = 57,
ERR_BadVisDelegateReturn = 58,
ERR_BadVisDelegateParam = 59,
ERR_BadVisBaseClass = 60,
ERR_BadVisBaseInterface = 61,
ERR_EventNeedsBothAccessors = 65,
ERR_EventNotDelegate = 66,
WRN_UnreferencedEvent = 67,
ERR_InterfaceEventInitializer = 68,
//ERR_EventPropertyInInterface = 69,
ERR_BadEventUsage = 70,
ERR_ExplicitEventFieldImpl = 71,
ERR_CantOverrideNonEvent = 72,
ERR_AddRemoveMustHaveBody = 73,
ERR_AbstractEventInitializer = 74,
ERR_PossibleBadNegCast = 75,
ERR_ReservedEnumerator = 76,
ERR_AsMustHaveReferenceType = 77,
WRN_LowercaseEllSuffix = 78,
ERR_BadEventUsageNoField = 79,
ERR_ConstraintOnlyAllowedOnGenericDecl = 80,
ERR_TypeParamMustBeIdentifier = 81,
ERR_MemberReserved = 82,
ERR_DuplicateParamName = 100,
ERR_DuplicateNameInNS = 101,
ERR_DuplicateNameInClass = 102,
ERR_NameNotInContext = 103,
ERR_AmbigContext = 104,
WRN_DuplicateUsing = 105,
ERR_BadMemberFlag = 106,
ERR_BadMemberProtection = 107,
WRN_NewRequired = 108,
WRN_NewNotRequired = 109,
ERR_CircConstValue = 110,
ERR_MemberAlreadyExists = 111,
ERR_StaticNotVirtual = 112,
ERR_OverrideNotNew = 113,
WRN_NewOrOverrideExpected = 114,
ERR_OverrideNotExpected = 115,
ERR_NamespaceUnexpected = 116,
ERR_NoSuchMember = 117,
ERR_BadSKknown = 118,
ERR_BadSKunknown = 119,
ERR_ObjectRequired = 120,
ERR_AmbigCall = 121,
ERR_BadAccess = 122,
ERR_MethDelegateMismatch = 123,
ERR_RetObjectRequired = 126,
ERR_RetNoObjectRequired = 127,
ERR_LocalDuplicate = 128,
ERR_AssgLvalueExpected = 131,
ERR_StaticConstParam = 132,
ERR_NotConstantExpression = 133,
ERR_NotNullConstRefField = 134,
// ERR_NameIllegallyOverrides = 135, // Not used in Roslyn anymore due to 'Single Meaning' relaxation changes
ERR_LocalIllegallyOverrides = 136,
ERR_BadUsingNamespace = 138,
ERR_NoBreakOrCont = 139,
ERR_DuplicateLabel = 140,
ERR_NoConstructors = 143,
ERR_NoNewAbstract = 144,
ERR_ConstValueRequired = 145,
ERR_CircularBase = 146,
ERR_BadDelegateConstructor = 148,
ERR_MethodNameExpected = 149,
ERR_ConstantExpected = 150,
// ERR_V6SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler.
// However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future
// we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used.
ERR_V6SwitchGoverningTypeValueExpected = 151,
ERR_DuplicateCaseLabel = 152,
ERR_InvalidGotoCase = 153,
ERR_PropertyLacksGet = 154,
ERR_BadExceptionType = 155,
ERR_BadEmptyThrow = 156,
ERR_BadFinallyLeave = 157,
ERR_LabelShadow = 158,
ERR_LabelNotFound = 159,
ERR_UnreachableCatch = 160,
ERR_ReturnExpected = 161,
WRN_UnreachableCode = 162,
ERR_SwitchFallThrough = 163,
WRN_UnreferencedLabel = 164,
ERR_UseDefViolation = 165,
//ERR_NoInvoke = 167,
WRN_UnreferencedVar = 168,
WRN_UnreferencedField = 169,
ERR_UseDefViolationField = 170,
ERR_UnassignedThis = 171,
ERR_AmbigQM = 172,
ERR_InvalidQM = 173, // Requires SymbolDistinguisher.
ERR_NoBaseClass = 174,
ERR_BaseIllegal = 175,
ERR_ObjectProhibited = 176,
ERR_ParamUnassigned = 177,
ERR_InvalidArray = 178,
ERR_ExternHasBody = 179,
ERR_AbstractAndExtern = 180,
ERR_BadAttributeParamType = 181,
ERR_BadAttributeArgument = 182,
WRN_IsAlwaysTrue = 183,
WRN_IsAlwaysFalse = 184,
ERR_LockNeedsReference = 185,
ERR_NullNotValid = 186,
ERR_UseDefViolationThis = 188,
ERR_ArgsInvalid = 190,
ERR_AssgReadonly = 191,
ERR_RefReadonly = 192,
ERR_PtrExpected = 193,
ERR_PtrIndexSingle = 196,
WRN_ByRefNonAgileField = 197,
ERR_AssgReadonlyStatic = 198,
ERR_RefReadonlyStatic = 199,
ERR_AssgReadonlyProp = 200,
ERR_IllegalStatement = 201,
ERR_BadGetEnumerator = 202,
ERR_TooManyLocals = 204,
ERR_AbstractBaseCall = 205,
ERR_RefProperty = 206,
// WRN_OldWarning_UnsafeProp = 207, // This error code is unused.
ERR_ManagedAddr = 208,
ERR_BadFixedInitType = 209,
ERR_FixedMustInit = 210,
ERR_InvalidAddrOp = 211,
ERR_FixedNeeded = 212,
ERR_FixedNotNeeded = 213,
ERR_UnsafeNeeded = 214,
ERR_OpTFRetType = 215,
ERR_OperatorNeedsMatch = 216,
ERR_BadBoolOp = 217,
ERR_MustHaveOpTF = 218,
WRN_UnreferencedVarAssg = 219,
ERR_CheckedOverflow = 220,
ERR_ConstOutOfRangeChecked = 221,
ERR_BadVarargs = 224,
ERR_ParamsMustBeArray = 225,
ERR_IllegalArglist = 226,
ERR_IllegalUnsafe = 227,
//ERR_NoAccessibleMember = 228,
ERR_AmbigMember = 229,
ERR_BadForeachDecl = 230,
ERR_ParamsLast = 231,
ERR_SizeofUnsafe = 233,
ERR_DottedTypeNameNotFoundInNS = 234,
ERR_FieldInitRefNonstatic = 236,
ERR_SealedNonOverride = 238,
ERR_CantOverrideSealed = 239,
//ERR_NoDefaultArgs = 241,
ERR_VoidError = 242,
ERR_ConditionalOnOverride = 243,
ERR_PointerInAsOrIs = 244,
ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated
ERR_SingleTypeNameNotFound = 246,
ERR_NegativeStackAllocSize = 247,
ERR_NegativeArraySize = 248,
ERR_OverrideFinalizeDeprecated = 249,
ERR_CallingBaseFinalizeDeprecated = 250,
WRN_NegativeArrayIndex = 251,
WRN_BadRefCompareLeft = 252,
WRN_BadRefCompareRight = 253,
ERR_BadCastInFixed = 254,
ERR_StackallocInCatchFinally = 255,
ERR_VarargsLast = 257,
ERR_MissingPartial = 260,
ERR_PartialTypeKindConflict = 261,
ERR_PartialModifierConflict = 262,
ERR_PartialMultipleBases = 263,
ERR_PartialWrongTypeParams = 264,
ERR_PartialWrongConstraints = 265,
ERR_NoImplicitConvCast = 266, // Requires SymbolDistinguisher.
ERR_PartialMisplaced = 267,
ERR_ImportedCircularBase = 268,
ERR_UseDefViolationOut = 269,
ERR_ArraySizeInDeclaration = 270,
ERR_InaccessibleGetter = 271,
ERR_InaccessibleSetter = 272,
ERR_InvalidPropertyAccessMod = 273,
ERR_DuplicatePropertyAccessMods = 274,
//ERR_PropertyAccessModInInterface = 275,
ERR_AccessModMissingAccessor = 276,
ERR_UnimplementedInterfaceAccessor = 277,
WRN_PatternIsAmbiguous = 278,
WRN_PatternNotPublicOrNotInstance = 279,
WRN_PatternBadSignature = 280,
ERR_FriendRefNotEqualToThis = 281,
WRN_SequentialOnPartialClass = 282,
ERR_BadConstType = 283,
ERR_NoNewTyvar = 304,
ERR_BadArity = 305,
ERR_BadTypeArgument = 306,
ERR_TypeArgsNotAllowed = 307,
ERR_HasNoTypeVars = 308,
ERR_NewConstraintNotSatisfied = 310,
ERR_GenericConstraintNotSatisfiedRefType = 311, // Requires SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedNullableEnum = 312, // Uses (but doesn't require) SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedNullableInterface = 313, // Uses (but doesn't require) SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedTyVar = 314, // Requires SymbolDistinguisher.
ERR_GenericConstraintNotSatisfiedValType = 315, // Requires SymbolDistinguisher.
ERR_DuplicateGeneratedName = 316,
// unused 317-399
ERR_GlobalSingleTypeNameNotFound = 400,
ERR_NewBoundMustBeLast = 401,
WRN_MainCantBeGeneric = 402,
ERR_TypeVarCantBeNull = 403,
// ERR_AttributeCantBeGeneric = 404,
ERR_DuplicateBound = 405,
ERR_ClassBoundNotFirst = 406,
ERR_BadRetType = 407,
ERR_DuplicateConstraintClause = 409,
//ERR_WrongSignature = 410, unused in Roslyn
ERR_CantInferMethTypeArgs = 411,
ERR_LocalSameNameAsTypeParam = 412,
ERR_AsWithTypeVar = 413,
WRN_UnreferencedFieldAssg = 414,
ERR_BadIndexerNameAttr = 415,
ERR_AttrArgWithTypeVars = 416,
ERR_NewTyvarWithArgs = 417,
ERR_AbstractSealedStatic = 418,
WRN_AmbiguousXMLReference = 419,
WRN_VolatileByRef = 420,
// WRN_IncrSwitchObsolete = 422, // This error code is unused.
ERR_ComImportWithImpl = 423,
ERR_ComImportWithBase = 424,
ERR_ImplBadConstraints = 425,
ERR_DottedTypeNameNotFoundInAgg = 426,
ERR_MethGrpToNonDel = 428,
// WRN_UnreachableExpr = 429, // This error code is unused.
ERR_BadExternAlias = 430,
ERR_ColColWithTypeAlias = 431,
ERR_AliasNotFound = 432,
ERR_SameFullNameAggAgg = 433,
ERR_SameFullNameNsAgg = 434,
WRN_SameFullNameThisNsAgg = 435,
WRN_SameFullNameThisAggAgg = 436,
WRN_SameFullNameThisAggNs = 437,
ERR_SameFullNameThisAggThisNs = 438,
ERR_ExternAfterElements = 439,
WRN_GlobalAliasDefn = 440,
ERR_SealedStaticClass = 441,
ERR_PrivateAbstractAccessor = 442,
ERR_ValueExpected = 443,
// WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused.
ERR_UnboxNotLValue = 445,
ERR_AnonMethGrpInForEach = 446,
//ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error.
ERR_BadIncDecRetType = 448,
ERR_TypeConstraintsMustBeUniqueAndFirst = 449,
ERR_RefValBoundWithClass = 450,
ERR_NewBoundWithVal = 451,
ERR_RefConstraintNotSatisfied = 452,
ERR_ValConstraintNotSatisfied = 453,
ERR_CircularConstraint = 454,
ERR_BaseConstraintConflict = 455,
ERR_ConWithValCon = 456,
ERR_AmbigUDConv = 457,
WRN_AlwaysNull = 458,
// ERR_AddrOnReadOnlyLocal = 459, // no longer an error
ERR_OverrideWithConstraints = 460,
ERR_AmbigOverride = 462,
ERR_DecConstError = 463,
WRN_CmpAlwaysFalse = 464,
WRN_FinalizeMethod = 465,
ERR_ExplicitImplParams = 466,
// WRN_AmbigLookupMeth = 467, //no longer issued in Roslyn
//ERR_SameFullNameThisAggThisAgg = 468, no longer used in Roslyn
WRN_GotoCaseShouldConvert = 469,
ERR_MethodImplementingAccessor = 470,
//ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn
WRN_NubExprIsConstBool = 472,
WRN_ExplicitImplCollision = 473,
// unused 474-499
ERR_AbstractHasBody = 500,
ERR_ConcreteMissingBody = 501,
ERR_AbstractAndSealed = 502,
ERR_AbstractNotVirtual = 503,
ERR_StaticConstant = 504,
ERR_CantOverrideNonFunction = 505,
ERR_CantOverrideNonVirtual = 506,
ERR_CantChangeAccessOnOverride = 507,
ERR_CantChangeReturnTypeOnOverride = 508,
ERR_CantDeriveFromSealedType = 509,
ERR_AbstractInConcreteClass = 513,
ERR_StaticConstructorWithExplicitConstructorCall = 514,
ERR_StaticConstructorWithAccessModifiers = 515,
ERR_RecursiveConstructorCall = 516,
ERR_ObjectCallingBaseConstructor = 517,
ERR_PredefinedTypeNotFound = 518,
//ERR_PredefinedTypeBadType = 520,
ERR_StructWithBaseConstructorCall = 522,
ERR_StructLayoutCycle = 523,
//ERR_InterfacesCannotContainTypes = 524,
ERR_InterfacesCantContainFields = 525,
ERR_InterfacesCantContainConstructors = 526,
ERR_NonInterfaceInInterfaceList = 527,
ERR_DuplicateInterfaceInBaseList = 528,
ERR_CycleInInterfaceInheritance = 529,
//ERR_InterfaceMemberHasBody = 531,
ERR_HidingAbstractMethod = 533,
ERR_UnimplementedAbstractMethod = 534,
ERR_UnimplementedInterfaceMember = 535,
ERR_ObjectCantHaveBases = 537,
ERR_ExplicitInterfaceImplementationNotInterface = 538,
ERR_InterfaceMemberNotFound = 539,
ERR_ClassDoesntImplementInterface = 540,
ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541,
ERR_MemberNameSameAsType = 542,
ERR_EnumeratorOverflow = 543,
ERR_CantOverrideNonProperty = 544,
ERR_NoGetToOverride = 545,
ERR_NoSetToOverride = 546,
ERR_PropertyCantHaveVoidType = 547,
ERR_PropertyWithNoAccessors = 548,
ERR_NewVirtualInSealed = 549,
ERR_ExplicitPropertyAddingAccessor = 550,
ERR_ExplicitPropertyMissingAccessor = 551,
ERR_ConversionWithInterface = 552,
ERR_ConversionWithBase = 553,
ERR_ConversionWithDerived = 554,
ERR_IdentityConversion = 555,
ERR_ConversionNotInvolvingContainedType = 556,
ERR_DuplicateConversionInClass = 557,
ERR_OperatorsMustBeStatic = 558,
ERR_BadIncDecSignature = 559,
ERR_BadUnaryOperatorSignature = 562,
ERR_BadBinaryOperatorSignature = 563,
ERR_BadShiftOperatorSignature = 564,
ERR_InterfacesCantContainConversionOrEqualityOperators = 567,
//ERR_StructsCantContainDefaultConstructor = 568,
ERR_CantOverrideBogusMethod = 569,
ERR_BindToBogus = 570,
ERR_CantCallSpecialMethod = 571,
ERR_BadTypeReference = 572,
//ERR_FieldInitializerInStruct = 573,
ERR_BadDestructorName = 574,
ERR_OnlyClassesCanContainDestructors = 575,
ERR_ConflictAliasAndMember = 576,
ERR_ConditionalOnSpecialMethod = 577,
ERR_ConditionalMustReturnVoid = 578,
ERR_DuplicateAttribute = 579,
ERR_ConditionalOnInterfaceMethod = 582,
//ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused
//ERR_ICE_Symbol = 584,
//ERR_ICE_Node = 585,
//ERR_ICE_File = 586,
//ERR_ICE_Stage = 587,
//ERR_ICE_Lexer = 588,
//ERR_ICE_Parser = 589,
ERR_OperatorCantReturnVoid = 590,
ERR_InvalidAttributeArgument = 591,
ERR_AttributeOnBadSymbolType = 592,
ERR_FloatOverflow = 594,
ERR_InvalidReal = 595,
ERR_ComImportWithoutUuidAttribute = 596,
ERR_InvalidNamedArgument = 599,
ERR_DllImportOnInvalidMethod = 601,
// WRN_FeatureDeprecated = 602, // This error code is unused.
// ERR_NameAttributeOnOverride = 609, // removed in Roslyn
ERR_FieldCantBeRefAny = 610,
ERR_ArrayElementCantBeRefAny = 611,
WRN_DeprecatedSymbol = 612,
ERR_NotAnAttributeClass = 616,
ERR_BadNamedAttributeArgument = 617,
WRN_DeprecatedSymbolStr = 618,
ERR_DeprecatedSymbolStr = 619,
ERR_IndexerCantHaveVoidType = 620,
ERR_VirtualPrivate = 621,
ERR_ArrayInitToNonArrayType = 622,
ERR_ArrayInitInBadPlace = 623,
ERR_MissingStructOffset = 625,
WRN_ExternMethodNoImplementation = 626,
WRN_ProtectedInSealed = 628,
ERR_InterfaceImplementedByConditional = 629,
ERR_InterfaceImplementedImplicitlyByVariadic = 630,
ERR_IllegalRefParam = 631,
ERR_BadArgumentToAttribute = 633,
//ERR_MissingComTypeOrMarshaller = 635,
ERR_StructOffsetOnBadStruct = 636,
ERR_StructOffsetOnBadField = 637,
ERR_AttributeUsageOnNonAttributeClass = 641,
WRN_PossibleMistakenNullStatement = 642,
ERR_DuplicateNamedAttributeArgument = 643,
ERR_DeriveFromEnumOrValueType = 644,
//ERR_IdentifierTooLong = 645, //not used in Roslyn. See ERR_MetadataNameTooLong
ERR_DefaultMemberOnIndexedType = 646,
//ERR_CustomAttributeError = 647,
ERR_BogusType = 648,
WRN_UnassignedInternalField = 649,
ERR_CStyleArray = 650,
WRN_VacuousIntegralComp = 652,
ERR_AbstractAttributeClass = 653,
ERR_BadNamedAttributeArgumentType = 655,
ERR_MissingPredefinedMember = 656,
WRN_AttributeLocationOnBadDeclaration = 657,
WRN_InvalidAttributeLocation = 658,
WRN_EqualsWithoutGetHashCode = 659,
WRN_EqualityOpWithoutEquals = 660,
WRN_EqualityOpWithoutGetHashCode = 661,
ERR_OutAttrOnRefParam = 662,
ERR_OverloadRefKind = 663,
ERR_LiteralDoubleCast = 664,
WRN_IncorrectBooleanAssg = 665,
ERR_ProtectedInStruct = 666,
//ERR_FeatureDeprecated = 667,
ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler
ERR_ComImportWithUserCtor = 669,
ERR_FieldCantHaveVoidType = 670,
WRN_NonObsoleteOverridingObsolete = 672,
ERR_SystemVoid = 673,
ERR_ExplicitParamArray = 674,
WRN_BitwiseOrSignExtend = 675,
ERR_VolatileStruct = 677,
ERR_VolatileAndReadonly = 678,
// WRN_OldWarning_ProtectedInternal = 679, // This error code is unused.
// WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused.
ERR_AbstractField = 681,
ERR_BogusExplicitImpl = 682,
ERR_ExplicitMethodImplAccessor = 683,
WRN_CoClassWithoutComImport = 684,
ERR_ConditionalWithOutParam = 685,
ERR_AccessorImplementingMethod = 686,
ERR_AliasQualAsExpression = 687,
ERR_DerivingFromATyVar = 689,
//FTL_MalformedMetadata = 690,
ERR_DuplicateTypeParameter = 692,
WRN_TypeParameterSameAsOuterTypeParameter = 693,
ERR_TypeVariableSameAsParent = 694,
ERR_UnifyingInterfaceInstantiations = 695,
// ERR_GenericDerivingFromAttribute = 698,
ERR_TyVarNotFoundInConstraint = 699,
ERR_BadBoundType = 701,
ERR_SpecialTypeAsBound = 702,
ERR_BadVisBound = 703,
ERR_LookupInTypeVariable = 704,
ERR_BadConstraintType = 706,
ERR_InstanceMemberInStaticClass = 708,
ERR_StaticBaseClass = 709,
ERR_ConstructorInStaticClass = 710,
ERR_DestructorInStaticClass = 711,
ERR_InstantiatingStaticClass = 712,
ERR_StaticDerivedFromNonObject = 713,
ERR_StaticClassInterfaceImpl = 714,
ERR_OperatorInStaticClass = 715,
ERR_ConvertToStaticClass = 716,
ERR_ConstraintIsStaticClass = 717,
ERR_GenericArgIsStaticClass = 718,
ERR_ArrayOfStaticClass = 719,
ERR_IndexerInStaticClass = 720,
ERR_ParameterIsStaticClass = 721,
ERR_ReturnTypeIsStaticClass = 722,
ERR_VarDeclIsStaticClass = 723,
ERR_BadEmptyThrowInFinally = 724,
//ERR_InvalidDecl = 725,
ERR_InvalidSpecifier = 726,
//ERR_InvalidSpecifierUnk = 727,
WRN_AssignmentToLockOrDispose = 728,
ERR_ForwardedTypeInThisAssembly = 729,
ERR_ForwardedTypeIsNested = 730,
ERR_CycleInTypeForwarder = 731,
//ERR_FwdedGeneric = 733,
ERR_AssemblyNameOnNonModule = 734,
ERR_InvalidFwdType = 735,
ERR_CloseUnimplementedInterfaceMemberStatic = 736,
ERR_CloseUnimplementedInterfaceMemberNotPublic = 737,
ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738,
ERR_DuplicateTypeForwarder = 739,
ERR_ExpectedSelectOrGroup = 742,
ERR_ExpectedContextualKeywordOn = 743,
ERR_ExpectedContextualKeywordEquals = 744,
ERR_ExpectedContextualKeywordBy = 745,
ERR_InvalidAnonymousTypeMemberDeclarator = 746,
ERR_InvalidInitializerElementInitializer = 747,
ERR_InconsistentLambdaParameterUsage = 748,
ERR_PartialMethodInvalidModifier = 750,
ERR_PartialMethodOnlyInPartialClass = 751,
// ERR_PartialMethodCannotHaveOutParameters = 752, Removed as part of 'extended partial methods' feature
// ERR_PartialMethodOnlyMethods = 753, Removed as it is subsumed by ERR_PartialMisplaced
ERR_PartialMethodNotExplicit = 754,
ERR_PartialMethodExtensionDifference = 755,
ERR_PartialMethodOnlyOneLatent = 756,
ERR_PartialMethodOnlyOneActual = 757,
ERR_PartialMethodParamsDifference = 758,
ERR_PartialMethodMustHaveLatent = 759,
ERR_PartialMethodInconsistentConstraints = 761,
ERR_PartialMethodToDelegate = 762,
ERR_PartialMethodStaticDifference = 763,
ERR_PartialMethodUnsafeDifference = 764,
ERR_PartialMethodInExpressionTree = 765,
// ERR_PartialMethodMustReturnVoid = 766, Removed as part of 'extended partial methods' feature
ERR_ExplicitImplCollisionOnRefOut = 767,
ERR_IndirectRecursiveConstructorCall = 768,
// unused 769-799
//ERR_NoEmptyArrayRanges = 800,
//ERR_IntegerSpecifierOnOneDimArrays = 801,
//ERR_IntegerSpecifierMustBePositive = 802,
//ERR_ArrayRangeDimensionsMustMatch = 803,
//ERR_ArrayRangeDimensionsWrong = 804,
//ERR_IntegerSpecifierValidOnlyOnArrays = 805,
//ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806,
//ERR_UseAdditionalSquareBrackets = 807,
//ERR_DotDotNotAssociative = 808,
WRN_ObsoleteOverridingNonObsolete = 809,
WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong
ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue
ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer
ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator
ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer
ERR_ImplicitlyTypedLocalCannotBeFixed = 821,
ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst
WRN_ExternCtorNoImplementation = 824,
ERR_TypeVarNotFound = 825,
ERR_ImplicitlyTypedArrayNoBestType = 826,
ERR_AnonymousTypePropertyAssignedBadValue = 828,
ERR_ExpressionTreeContainsBaseAccess = 831,
ERR_ExpressionTreeContainsAssignment = 832,
ERR_AnonymousTypeDuplicatePropertyName = 833,
ERR_StatementLambdaToExpressionTree = 834,
ERR_ExpressionTreeMustHaveDelegate = 835,
ERR_AnonymousTypeNotAvailable = 836,
ERR_LambdaInIsAs = 837,
ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838,
ERR_MissingArgument = 839,
//ERR_AutoPropertiesMustHaveBothAccessors = 840,
ERR_VariableUsedBeforeDeclaration = 841,
//ERR_ExplicitLayoutAndAutoImplementedProperty = 842,
ERR_UnassignedThisAutoProperty = 843,
ERR_VariableUsedBeforeDeclarationAndHidesField = 844,
ERR_ExpressionTreeContainsBadCoalesce = 845,
ERR_ArrayInitializerExpected = 846,
ERR_ArrayInitializerIncorrectLength = 847,
// ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind
ERR_ExpressionTreeContainsNamedArgument = 853,
ERR_ExpressionTreeContainsOptionalArgument = 854,
ERR_ExpressionTreeContainsIndexedProperty = 855,
ERR_IndexedPropertyRequiresParams = 856,
ERR_IndexedPropertyMustHaveAllOptionalParams = 857,
//ERR_FusionConfigFileNameTooLong = 858, unused in Roslyn. We give ERR_CantReadConfigFile now.
// unused 859-1000
ERR_IdentifierExpected = 1001,
ERR_SemicolonExpected = 1002,
ERR_SyntaxError = 1003,
ERR_DuplicateModifier = 1004,
ERR_DuplicateAccessor = 1007,
ERR_IntegralTypeExpected = 1008,
ERR_IllegalEscape = 1009,
ERR_NewlineInConst = 1010,
ERR_EmptyCharConst = 1011,
ERR_TooManyCharsInConst = 1012,
ERR_InvalidNumber = 1013,
ERR_GetOrSetExpected = 1014,
ERR_ClassTypeExpected = 1015,
ERR_NamedArgumentExpected = 1016,
ERR_TooManyCatches = 1017,
ERR_ThisOrBaseExpected = 1018,
ERR_OvlUnaryOperatorExpected = 1019,
ERR_OvlBinaryOperatorExpected = 1020,
ERR_IntOverflow = 1021,
ERR_EOFExpected = 1022,
ERR_BadEmbeddedStmt = 1023,
ERR_PPDirectiveExpected = 1024,
ERR_EndOfPPLineExpected = 1025,
ERR_CloseParenExpected = 1026,
ERR_EndifDirectiveExpected = 1027,
ERR_UnexpectedDirective = 1028,
ERR_ErrorDirective = 1029,
WRN_WarningDirective = 1030,
ERR_TypeExpected = 1031,
ERR_PPDefFollowsToken = 1032,
//ERR_TooManyLines = 1033, unused in Roslyn.
//ERR_LineTooLong = 1034, unused in Roslyn.
ERR_OpenEndedComment = 1035,
ERR_OvlOperatorExpected = 1037,
ERR_EndRegionDirectiveExpected = 1038,
ERR_UnterminatedStringLit = 1039,
ERR_BadDirectivePlacement = 1040,
ERR_IdentifierExpectedKW = 1041,
ERR_SemiOrLBraceExpected = 1043,
ERR_MultiTypeInDeclaration = 1044,
ERR_AddOrRemoveExpected = 1055,
ERR_UnexpectedCharacter = 1056,
ERR_ProtectedInStatic = 1057,
WRN_UnreachableGeneralCatch = 1058,
ERR_IncrementLvalueExpected = 1059,
// WRN_UninitializedField = 1060, // unused in Roslyn.
ERR_NoSuchMemberOrExtension = 1061,
WRN_DeprecatedCollectionInitAddStr = 1062,
ERR_DeprecatedCollectionInitAddStr = 1063,
WRN_DeprecatedCollectionInitAdd = 1064,
ERR_DefaultValueNotAllowed = 1065,
WRN_DefaultValueForUnconsumedLocation = 1066,
ERR_PartialWrongTypeParamsVariance = 1067,
ERR_GlobalSingleTypeNameNotFoundFwd = 1068,
ERR_DottedTypeNameNotFoundInNSFwd = 1069,
ERR_SingleTypeNameNotFoundFwd = 1070,
//ERR_NoSuchMemberOnNoPIAType = 1071, //EE
WRN_IdentifierOrNumericLiteralExpected = 1072,
ERR_UnexpectedToken = 1073,
// unused 1074-1098
// ERR_EOLExpected = 1099, // EE
// ERR_NotSupportedinEE = 1100, // EE
ERR_BadThisParam = 1100,
// ERR_BadRefWithThis = 1101, replaced by ERR_BadParameterModifiers
// ERR_BadOutWithThis = 1102, replaced by ERR_BadParameterModifiers
ERR_BadTypeforThis = 1103,
ERR_BadParamModThis = 1104,
ERR_BadExtensionMeth = 1105,
ERR_BadExtensionAgg = 1106,
ERR_DupParamMod = 1107,
// ERR_MultiParamMod = 1108, replaced by ERR_BadParameterModifiers
ERR_ExtensionMethodsDecl = 1109,
ERR_ExtensionAttrNotFound = 1110,
//ERR_ExtensionTypeParam = 1111,
ERR_ExplicitExtension = 1112,
ERR_ValueTypeExtDelegate = 1113,
// unused 1114-1199
// Below five error codes are unused.
// WRN_FeatureDeprecated2 = 1200,
// WRN_FeatureDeprecated3 = 1201,
// WRN_FeatureDeprecated4 = 1202,
// WRN_FeatureDeprecated5 = 1203,
// WRN_OldWarning_FeatureDefaultDeprecated = 1204,
// unused 1205-1500
ERR_BadArgCount = 1501,
//ERR_BadArgTypes = 1502,
ERR_BadArgType = 1503,
ERR_NoSourceFile = 1504,
ERR_CantRefResource = 1507,
ERR_ResourceNotUnique = 1508,
ERR_ImportNonAssembly = 1509,
ERR_RefLvalueExpected = 1510,
ERR_BaseInStaticMeth = 1511,
ERR_BaseInBadContext = 1512,
ERR_RbraceExpected = 1513,
ERR_LbraceExpected = 1514,
ERR_InExpected = 1515,
ERR_InvalidPreprocExpr = 1517,
//ERR_BadTokenInType = 1518, unused in Roslyn
ERR_InvalidMemberDecl = 1519,
ERR_MemberNeedsType = 1520,
ERR_BadBaseType = 1521,
WRN_EmptySwitch = 1522,
ERR_ExpectedEndTry = 1524,
ERR_InvalidExprTerm = 1525,
ERR_BadNewExpr = 1526,
ERR_NoNamespacePrivate = 1527,
ERR_BadVarDecl = 1528,
ERR_UsingAfterElements = 1529,
//ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this.
//ERR_DontUseInvoke = 1533,
ERR_BadBinOpArgs = 1534,
ERR_BadUnOpArgs = 1535,
ERR_NoVoidParameter = 1536,
ERR_DuplicateAlias = 1537,
ERR_BadProtectedAccess = 1540,
//ERR_CantIncludeDirectory = 1541,
ERR_AddModuleAssembly = 1542,
ERR_BindToBogusProp2 = 1545,
ERR_BindToBogusProp1 = 1546,
ERR_NoVoidHere = 1547,
//ERR_CryptoFailed = 1548,
//ERR_CryptoNotFound = 1549,
ERR_IndexerNeedsParam = 1551,
ERR_BadArraySyntax = 1552,
ERR_BadOperatorSyntax = 1553,
//ERR_BadOperatorSyntax2 = 1554, Not used in Roslyn.
ERR_MainClassNotFound = 1555,
ERR_MainClassNotClass = 1556,
//ERR_MainClassWrongFile = 1557, Not used in Roslyn. This was used only when compiling and producing two outputs.
ERR_NoMainInClass = 1558,
//ERR_MainClassIsImport = 1559, Not used in Roslyn. Scenario occurs so infrequently that it is not worth re-implementing.
//ERR_FileNameTooLong = 1560,
//ERR_OutputFileNameTooLong = 1561, Not used in Roslyn. We report a more generic error that doesn't mention "output file" but is fine.
ERR_OutputNeedsName = 1562,
//ERR_OutputNeedsInput = 1563,
ERR_CantHaveWin32ResAndManifest = 1564,
ERR_CantHaveWin32ResAndIcon = 1565,
ERR_CantReadResource = 1566,
//ERR_AutoResGen = 1567,
ERR_DocFileGen = 1569,
WRN_XMLParseError = 1570,
WRN_DuplicateParamTag = 1571,
WRN_UnmatchedParamTag = 1572,
WRN_MissingParamTag = 1573,
WRN_BadXMLRef = 1574,
ERR_BadStackAllocExpr = 1575,
ERR_InvalidLineNumber = 1576,
//ERR_ALinkFailed = 1577, No alink usage in Roslyn
ERR_MissingPPFile = 1578,
ERR_ForEachMissingMember = 1579,
WRN_BadXMLRefParamType = 1580,
WRN_BadXMLRefReturnType = 1581,
ERR_BadWin32Res = 1583,
WRN_BadXMLRefSyntax = 1584,
ERR_BadModifierLocation = 1585,
ERR_MissingArraySize = 1586,
WRN_UnprocessedXMLComment = 1587,
//ERR_CantGetCORSystemDir = 1588,
WRN_FailedInclude = 1589,
WRN_InvalidInclude = 1590,
WRN_MissingXMLComment = 1591,
WRN_XMLParseIncludeError = 1592,
ERR_BadDelArgCount = 1593,
//ERR_BadDelArgTypes = 1594,
// WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused.
// WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused.
ERR_UnexpectedSemicolon = 1597,
// WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time).
ERR_MethodReturnCantBeRefAny = 1599,
ERR_CompileCancelled = 1600,
ERR_MethodArgCantBeRefAny = 1601,
ERR_AssgReadonlyLocal = 1604,
ERR_RefReadonlyLocal = 1605,
//ERR_ALinkCloseFailed = 1606,
WRN_ALinkWarn = 1607,
ERR_CantUseRequiredAttribute = 1608,
ERR_NoModifiersOnAccessor = 1609,
// WRN_DeleteAutoResFailed = 1610, // Unused.
ERR_ParamsCantBeWithModifier = 1611,
ERR_ReturnNotLValue = 1612,
ERR_MissingCoClass = 1613,
ERR_AmbiguousAttribute = 1614,
ERR_BadArgExtraRef = 1615,
WRN_CmdOptionConflictsSource = 1616,
ERR_BadCompatMode = 1617,
ERR_DelegateOnConditional = 1618,
ERR_CantMakeTempFile = 1619, //changed to now accept only one argument
ERR_BadArgRef = 1620,
ERR_YieldInAnonMeth = 1621,
ERR_ReturnInIterator = 1622,
ERR_BadIteratorArgType = 1623,
ERR_BadIteratorReturn = 1624,
ERR_BadYieldInFinally = 1625,
ERR_BadYieldInTryOfCatch = 1626,
ERR_EmptyYield = 1627,
ERR_AnonDelegateCantUse = 1628,
ERR_IllegalInnerUnsafe = 1629,
//ERR_BadWatsonMode = 1630,
ERR_BadYieldInCatch = 1631,
ERR_BadDelegateLeave = 1632,
WRN_IllegalPragma = 1633,
WRN_IllegalPPWarning = 1634,
WRN_BadRestoreNumber = 1635,
ERR_VarargsIterator = 1636,
ERR_UnsafeIteratorArgType = 1637,
//ERR_ReservedIdentifier = 1638,
ERR_BadCoClassSig = 1639,
ERR_MultipleIEnumOfT = 1640,
ERR_FixedDimsRequired = 1641,
ERR_FixedNotInStruct = 1642,
ERR_AnonymousReturnExpected = 1643,
//ERR_NonECMAFeature = 1644,
WRN_NonECMAFeature = 1645,
ERR_ExpectedVerbatimLiteral = 1646,
//FTL_StackOverflow = 1647,
ERR_AssgReadonly2 = 1648,
ERR_RefReadonly2 = 1649,
ERR_AssgReadonlyStatic2 = 1650,
ERR_RefReadonlyStatic2 = 1651,
ERR_AssgReadonlyLocal2Cause = 1654,
ERR_RefReadonlyLocal2Cause = 1655,
ERR_AssgReadonlyLocalCause = 1656,
ERR_RefReadonlyLocalCause = 1657,
WRN_ErrorOverride = 1658,
// WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused.
ERR_AnonMethToNonDel = 1660,
ERR_CantConvAnonMethParams = 1661,
ERR_CantConvAnonMethReturns = 1662,
ERR_IllegalFixedType = 1663,
ERR_FixedOverflow = 1664,
ERR_InvalidFixedArraySize = 1665,
ERR_FixedBufferNotFixed = 1666,
ERR_AttributeNotOnAccessor = 1667,
WRN_InvalidSearchPathDir = 1668,
ERR_IllegalVarArgs = 1669,
ERR_IllegalParams = 1670,
ERR_BadModifiersOnNamespace = 1671,
ERR_BadPlatformType = 1672,
ERR_ThisStructNotInAnonMeth = 1673,
ERR_NoConvToIDisp = 1674,
// ERR_InvalidGenericEnum = 1675, replaced with 7002
ERR_BadParamRef = 1676,
ERR_BadParamExtraRef = 1677,
ERR_BadParamType = 1678, // Requires SymbolDistinguisher.
ERR_BadExternIdentifier = 1679,
ERR_AliasMissingFile = 1680,
ERR_GlobalExternAlias = 1681,
// WRN_MissingTypeNested = 1682, // unused in Roslyn.
// In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively.
// WRN_MissingTypeInSource = 1683,
// WRN_MissingTypeInAssembly = 1684,
WRN_MultiplePredefTypes = 1685,
ERR_LocalCantBeFixedAndHoisted = 1686,
WRN_TooManyLinesForDebugger = 1687,
ERR_CantConvAnonMethNoParams = 1688,
ERR_ConditionalOnNonAttributeClass = 1689,
WRN_CallOnNonAgileField = 1690,
// WRN_BadWarningNumber = 1691, // we no longer generate this warning for an unrecognized warning ID specified as an argument to /nowarn or /warnaserror.
WRN_InvalidNumber = 1692,
// WRN_FileNameTooLong = 1694, //unused.
WRN_IllegalPPChecksum = 1695,
WRN_EndOfPPLineExpected = 1696,
WRN_ConflictingChecksum = 1697,
// WRN_AssumedMatchThis = 1698, // This error code is unused.
// WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused.
WRN_InvalidAssemblyName = 1700,
WRN_UnifyReferenceMajMin = 1701,
WRN_UnifyReferenceBldRev = 1702,
ERR_DuplicateImport = 1703,
ERR_DuplicateImportSimple = 1704,
ERR_AssemblyMatchBadVersion = 1705,
//ERR_AnonMethNotAllowed = 1706, Unused in Roslyn. Previously given when a lambda was supplied as an attribute argument.
// WRN_DelegateNewMethBind = 1707, // This error code is unused.
ERR_FixedNeedsLvalue = 1708,
// WRN_EmptyFileName = 1709, // This error code is unused.
WRN_DuplicateTypeParamTag = 1710,
WRN_UnmatchedTypeParamTag = 1711,
WRN_MissingTypeParamTag = 1712,
//FTL_TypeNameBuilderError = 1713,
//ERR_ImportBadBase = 1714, // This error code is unused and replaced with ERR_NoTypeDef
ERR_CantChangeTypeOnOverride = 1715,
ERR_DoNotUseFixedBufferAttr = 1716,
WRN_AssignmentToSelf = 1717,
WRN_ComparisonToSelf = 1718,
ERR_CantOpenWin32Res = 1719,
WRN_DotOnDefault = 1720,
ERR_NoMultipleInheritance = 1721,
ERR_BaseClassMustBeFirst = 1722,
WRN_BadXMLRefTypeVar = 1723,
//ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn.
ERR_FriendAssemblyBadArgs = 1725,
ERR_FriendAssemblySNReq = 1726,
//ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings.
ERR_DelegateOnNullable = 1728,
ERR_BadCtorArgCount = 1729,
ERR_GlobalAttributesNotFirst = 1730,
//ERR_CantConvAnonMethReturnsNoDelegate = 1731, Not used in Roslyn. When there is no delegate, we reuse the message that contains a substitution string for the delegate type.
//ERR_ParameterExpected = 1732, Not used in Roslyn.
ERR_ExpressionExpected = 1733,
WRN_UnmatchedParamRefTag = 1734,
WRN_UnmatchedTypeParamRefTag = 1735,
ERR_DefaultValueMustBeConstant = 1736,
ERR_DefaultValueBeforeRequiredValue = 1737,
ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738,
ERR_BadNamedArgument = 1739,
ERR_DuplicateNamedArgument = 1740,
ERR_RefOutDefaultValue = 1741,
ERR_NamedArgumentForArray = 1742,
ERR_DefaultValueForExtensionParameter = 1743,
ERR_NamedArgumentUsedInPositional = 1744,
ERR_DefaultValueUsedWithAttributes = 1745,
ERR_BadNamedArgumentForDelegateInvoke = 1746,
ERR_NoPIAAssemblyMissingAttribute = 1747,
ERR_NoCanonicalView = 1748,
//ERR_TypeNotFoundForNoPIA = 1749,
ERR_NoConversionForDefaultParam = 1750,
ERR_DefaultValueForParamsParameter = 1751,
ERR_NewCoClassOnLink = 1752,
ERR_NoPIANestedType = 1754,
//ERR_InvalidTypeIdentifierConstructor = 1755,
ERR_InteropTypeMissingAttribute = 1756,
ERR_InteropStructContainsMethods = 1757,
ERR_InteropTypesWithSameNameAndGuid = 1758,
ERR_NoPIAAssemblyMissingAttributes = 1759,
ERR_AssemblySpecifiedForLinkAndRef = 1760,
ERR_LocalTypeNameClash = 1761,
WRN_ReferencedAssemblyReferencesLinkedPIA = 1762,
ERR_NotNullRefDefaultParameter = 1763,
ERR_FixedLocalInLambda = 1764,
// WRN_TypeNotFoundForNoPIAWarning = 1765, // This error code is unused.
ERR_MissingMethodOnSourceInterface = 1766,
ERR_MissingSourceInterface = 1767,
ERR_GenericsUsedInNoPIAType = 1768,
ERR_GenericsUsedAcrossAssemblies = 1769,
ERR_NoConversionForNubDefaultParam = 1770,
//ERR_MemberWithGenericsUsedAcrossAssemblies = 1771,
//ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772,
ERR_InvalidSubsystemVersion = 1773,
ERR_InteropMethodWithBody = 1774,
// unused 1775-1899
ERR_BadWarningLevel = 1900,
ERR_BadDebugType = 1902,
//ERR_UnknownTestSwitch = 1903,
ERR_BadResourceVis = 1906,
ERR_DefaultValueTypeMustMatch = 1908,
//ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn.
ERR_DefaultValueBadValueType = 1910,
ERR_MemberAlreadyInitialized = 1912,
ERR_MemberCannotBeInitialized = 1913,
ERR_StaticMemberInObjectInitializer = 1914,
ERR_ReadonlyValueTypeInObjectInitializer = 1917,
ERR_ValueTypePropertyInObjectInitializer = 1918,
ERR_UnsafeTypeInObjectCreation = 1919,
ERR_EmptyElementInitializer = 1920,
ERR_InitializerAddHasWrongSignature = 1921,
ERR_CollectionInitRequiresIEnumerable = 1922,
//ERR_InvalidCollectionInitializerType = 1925, unused in Roslyn. Occurs so infrequently in real usage that it is not worth reimplementing.
ERR_CantOpenWin32Manifest = 1926,
WRN_CantHaveManifestForModule = 1927,
//ERR_BadExtensionArgTypes = 1928, unused in Roslyn (replaced by ERR_BadInstanceArgType)
ERR_BadInstanceArgType = 1929,
ERR_QueryDuplicateRangeVariable = 1930,
ERR_QueryRangeVariableOverrides = 1931,
ERR_QueryRangeVariableAssignedBadValue = 1932,
//ERR_QueryNotAllowed = 1933, unused in Roslyn. This specific message is not necessary for correctness and adds little.
ERR_QueryNoProviderCastable = 1934,
ERR_QueryNoProviderStandard = 1935,
ERR_QueryNoProvider = 1936,
ERR_QueryOuterKey = 1937,
ERR_QueryInnerKey = 1938,
ERR_QueryOutRefRangeVariable = 1939,
ERR_QueryMultipleProviders = 1940,
ERR_QueryTypeInferenceFailedMulti = 1941,
ERR_QueryTypeInferenceFailed = 1942,
ERR_QueryTypeInferenceFailedSelectMany = 1943,
ERR_ExpressionTreeContainsPointerOp = 1944,
ERR_ExpressionTreeContainsAnonymousMethod = 1945,
ERR_AnonymousMethodToExpressionTree = 1946,
ERR_QueryRangeVariableReadOnly = 1947,
ERR_QueryRangeVariableSameAsTypeParam = 1948,
ERR_TypeVarNotFoundRangeVariable = 1949,
ERR_BadArgTypesForCollectionAdd = 1950,
ERR_ByRefParameterInExpressionTree = 1951,
ERR_VarArgsInExpressionTree = 1952,
// ERR_MemGroupInExpressionTree = 1953, unused in Roslyn (replaced by ERR_LambdaInIsAs)
ERR_InitializerAddHasParamModifiers = 1954,
ERR_NonInvocableMemberCalled = 1955,
WRN_MultipleRuntimeImplementationMatches = 1956,
WRN_MultipleRuntimeOverrideMatches = 1957,
ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958,
ERR_InvalidConstantDeclarationType = 1959,
ERR_IllegalVarianceSyntax = 1960,
ERR_UnexpectedVariance = 1961,
ERR_BadDynamicTypeof = 1962,
ERR_ExpressionTreeContainsDynamicOperation = 1963,
ERR_BadDynamicConversion = 1964,
ERR_DeriveFromDynamic = 1965,
ERR_DeriveFromConstructedDynamic = 1966,
ERR_DynamicTypeAsBound = 1967,
ERR_ConstructedDynamicTypeAsBound = 1968,
ERR_DynamicRequiredTypesMissing = 1969,
ERR_ExplicitDynamicAttr = 1970,
ERR_NoDynamicPhantomOnBase = 1971,
ERR_NoDynamicPhantomOnBaseIndexer = 1972,
ERR_BadArgTypeDynamicExtension = 1973,
WRN_DynamicDispatchToConditionalMethod = 1974,
ERR_NoDynamicPhantomOnBaseCtor = 1975,
ERR_BadDynamicMethodArgMemgrp = 1976,
ERR_BadDynamicMethodArgLambda = 1977,
ERR_BadDynamicMethodArg = 1978,
ERR_BadDynamicQuery = 1979,
ERR_DynamicAttributeMissing = 1980,
WRN_IsDynamicIsConfusing = 1981,
//ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn.
ERR_BadAsyncReturn = 1983,
ERR_BadAwaitInFinally = 1984,
ERR_BadAwaitInCatch = 1985,
ERR_BadAwaitArg = 1986,
ERR_BadAsyncArgType = 1988,
ERR_BadAsyncExpressionTree = 1989,
//ERR_WindowsRuntimeTypesMissing = 1990, // unused in Roslyn
ERR_MixingWinRTEventWithRegular = 1991,
ERR_BadAwaitWithoutAsync = 1992,
//ERR_MissingAsyncTypes = 1993, // unused in Roslyn
ERR_BadAsyncLacksBody = 1994,
ERR_BadAwaitInQuery = 1995,
ERR_BadAwaitInLock = 1996,
ERR_TaskRetNoObjectRequired = 1997,
WRN_AsyncLacksAwaits = 1998,
ERR_FileNotFound = 2001,
WRN_FileAlreadyIncluded = 2002,
//ERR_DuplicateResponseFile = 2003,
ERR_NoFileSpec = 2005,
ERR_SwitchNeedsString = 2006,
ERR_BadSwitch = 2007,
WRN_NoSources = 2008,
ERR_OpenResponseFile = 2011,
ERR_CantOpenFileWrite = 2012,
ERR_BadBaseNumber = 2013,
// WRN_UseNewSwitch = 2014, //unused.
ERR_BinaryFile = 2015,
FTL_BadCodepage = 2016,
ERR_NoMainOnDLL = 2017,
//FTL_NoMessagesDLL = 2018,
FTL_InvalidTarget = 2019,
//ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once!
FTL_InvalidInputFileName = 2021,
//ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once!
WRN_NoConfigNotOnCommandLine = 2023,
ERR_InvalidFileAlignment = 2024,
//ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn.
//ERR_SourceMapFileBinary = 2027,
WRN_DefineIdentifierRequired = 2029,
//ERR_InvalidSourceMap = 2030,
//ERR_NoSourceMapFile = 2031,
//ERR_IllegalOptionChar = 2032,
FTL_OutputFileExists = 2033,
ERR_OneAliasPerReference = 2034,
ERR_SwitchNeedsNumber = 2035,
ERR_MissingDebugSwitch = 2036,
ERR_ComRefCallInExpressionTree = 2037,
WRN_BadUILang = 2038,
ERR_InvalidFormatForGuidForOption = 2039,
ERR_MissingGuidForOption = 2040,
ERR_InvalidOutputName = 2041,
ERR_InvalidDebugInformationFormat = 2042,
ERR_LegacyObjectIdSyntax = 2043,
ERR_SourceLinkRequiresPdb = 2044,
ERR_CannotEmbedWithoutPdb = 2045,
ERR_BadSwitchValue = 2046,
// unused 2047-2999
WRN_CLS_NoVarArgs = 3000,
WRN_CLS_BadArgType = 3001, // Requires SymbolDistinguisher.
WRN_CLS_BadReturnType = 3002,
WRN_CLS_BadFieldPropType = 3003,
// WRN_CLS_BadUnicode = 3004, //unused
WRN_CLS_BadIdentifierCase = 3005,
WRN_CLS_OverloadRefOut = 3006,
WRN_CLS_OverloadUnnamed = 3007,
WRN_CLS_BadIdentifier = 3008,
WRN_CLS_BadBase = 3009,
WRN_CLS_BadInterfaceMember = 3010,
WRN_CLS_NoAbstractMembers = 3011,
WRN_CLS_NotOnModules = 3012,
WRN_CLS_ModuleMissingCLS = 3013,
WRN_CLS_AssemblyNotCLS = 3014,
WRN_CLS_BadAttributeType = 3015,
WRN_CLS_ArrayArgumentToAttribute = 3016,
WRN_CLS_NotOnModules2 = 3017,
WRN_CLS_IllegalTrueInFalse = 3018,
WRN_CLS_MeaninglessOnPrivateType = 3019,
WRN_CLS_AssemblyNotCLS2 = 3021,
WRN_CLS_MeaninglessOnParam = 3022,
WRN_CLS_MeaninglessOnReturn = 3023,
WRN_CLS_BadTypeVar = 3024,
WRN_CLS_VolatileField = 3026,
WRN_CLS_BadInterface = 3027,
FTL_BadChecksumAlgorithm = 3028,
#endregion diagnostics introduced in C# 4 and earlier
// unused 3029-3999
#region diagnostics introduced in C# 5
// 4000 unused
ERR_BadAwaitArgIntrinsic = 4001,
// 4002 unused
ERR_BadAwaitAsIdentifier = 4003,
ERR_AwaitInUnsafeContext = 4004,
ERR_UnsafeAsyncArgType = 4005,
ERR_VarargsAsync = 4006,
ERR_ByRefTypeAndAwait = 4007,
ERR_BadAwaitArgVoidCall = 4008,
ERR_NonTaskMainCantBeAsync = 4009,
ERR_CantConvAsyncAnonFuncReturns = 4010,
ERR_BadAwaiterPattern = 4011,
ERR_BadSpecialByRefLocal = 4012,
ERR_SpecialByRefInLambda = 4013,
WRN_UnobservedAwaitableExpression = 4014,
ERR_SynchronizedAsyncMethod = 4015,
ERR_BadAsyncReturnExpression = 4016,
ERR_NoConversionForCallerLineNumberParam = 4017,
ERR_NoConversionForCallerFilePathParam = 4018,
ERR_NoConversionForCallerMemberNameParam = 4019,
ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020,
ERR_BadCallerFilePathParamWithoutDefaultValue = 4021,
ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022,
ERR_BadPrefer32OnLib = 4023,
WRN_CallerLineNumberParamForUnconsumedLocation = 4024,
WRN_CallerFilePathParamForUnconsumedLocation = 4025,
WRN_CallerMemberNameParamForUnconsumedLocation = 4026,
ERR_DoesntImplementAwaitInterface = 4027,
ERR_BadAwaitArg_NeedSystem = 4028,
ERR_CantReturnVoid = 4029,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031,
ERR_BadAwaitWithoutAsyncMethod = 4032,
ERR_BadAwaitWithoutVoidAsyncMethod = 4033,
ERR_BadAwaitWithoutAsyncLambda = 4034,
// ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn
ERR_NoSuchMemberOrExtensionNeedUsing = 4036,
#endregion diagnostics introduced in C# 5
// unused 4037-4999
#region diagnostics introduced in C# 6
// WRN_UnknownOption = 5000, //unused in Roslyn
ERR_NoEntryPoint = 5001,
// huge gap here; available 5002-6999
ERR_UnexpectedAliasedName = 7000,
ERR_UnexpectedGenericName = 7002,
ERR_UnexpectedUnboundGenericName = 7003,
ERR_GlobalStatement = 7006,
ERR_BadUsingType = 7007,
ERR_ReservedAssemblyName = 7008,
ERR_PPReferenceFollowsToken = 7009,
ERR_ExpectedPPFile = 7010,
ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011,
ERR_NameNotInContextPossibleMissingReference = 7012,
ERR_MetadataNameTooLong = 7013,
ERR_AttributesNotAllowed = 7014,
ERR_ExternAliasNotAllowed = 7015,
ERR_ConflictingAliasAndDefinition = 7016,
ERR_GlobalDefinitionOrStatementExpected = 7017,
ERR_ExpectedSingleScript = 7018,
ERR_RecursivelyTypedVariable = 7019,
ERR_YieldNotAllowedInScript = 7020,
ERR_NamespaceNotAllowedInScript = 7021,
WRN_MainIgnored = 7022,
WRN_StaticInAsOrIs = 7023,
ERR_InvalidDelegateType = 7024,
ERR_BadVisEventType = 7025,
ERR_GlobalAttributesNotAllowed = 7026,
ERR_PublicKeyFileFailure = 7027,
ERR_PublicKeyContainerFailure = 7028,
ERR_FriendRefSigningMismatch = 7029,
ERR_CannotPassNullForFriendAssembly = 7030,
ERR_SignButNoPrivateKey = 7032,
WRN_DelaySignButNoKey = 7033,
ERR_InvalidVersionFormat = 7034,
WRN_InvalidVersionFormat = 7035,
ERR_NoCorrespondingArgument = 7036,
// Moot: WRN_DestructorIsNotFinalizer = 7037,
ERR_ModuleEmitFailure = 7038,
// ERR_NameIllegallyOverrides2 = 7039, // Not used anymore due to 'Single Meaning' relaxation changes
// ERR_NameIllegallyOverrides3 = 7040, // Not used anymore due to 'Single Meaning' relaxation changes
ERR_ResourceFileNameNotUnique = 7041,
ERR_DllImportOnGenericMethod = 7042,
ERR_EncUpdateFailedMissingAttribute = 7043,
ERR_ParameterNotValidForType = 7045,
ERR_AttributeParameterRequired1 = 7046,
ERR_AttributeParameterRequired2 = 7047,
ERR_SecurityAttributeMissingAction = 7048,
ERR_SecurityAttributeInvalidAction = 7049,
ERR_SecurityAttributeInvalidActionAssembly = 7050,
ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051,
ERR_PrincipalPermissionInvalidAction = 7052,
ERR_FeatureNotValidInExpressionTree = 7053,
ERR_MarshalUnmanagedTypeNotValidForFields = 7054,
ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055,
ERR_PermissionSetAttributeInvalidFile = 7056,
ERR_PermissionSetAttributeFileReadError = 7057,
ERR_InvalidVersionFormat2 = 7058,
ERR_InvalidAssemblyCultureForExe = 7059,
//ERR_AsyncBeforeVersionFive = 7060,
ERR_DuplicateAttributeInNetModule = 7061,
//WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning
ERR_CantOpenIcon = 7064,
ERR_ErrorBuildingWin32Resources = 7065,
// ERR_IteratorInInteractive = 7066,
ERR_BadAttributeParamDefaultArgument = 7067,
ERR_MissingTypeInSource = 7068,
ERR_MissingTypeInAssembly = 7069,
ERR_SecurityAttributeInvalidTarget = 7070,
ERR_InvalidAssemblyName = 7071,
//ERR_PartialTypesBeforeVersionTwo = 7072,
//ERR_PartialMethodsBeforeVersionThree = 7073,
//ERR_QueryBeforeVersionThree = 7074,
//ERR_AnonymousTypeBeforeVersionThree = 7075,
//ERR_ImplicitArrayBeforeVersionThree = 7076,
//ERR_ObjectInitializerBeforeVersionThree = 7077,
//ERR_LambdaBeforeVersionThree = 7078,
ERR_NoTypeDefFromModule = 7079,
WRN_CallerFilePathPreferredOverCallerMemberName = 7080,
WRN_CallerLineNumberPreferredOverCallerMemberName = 7081,
WRN_CallerLineNumberPreferredOverCallerFilePath = 7082,
ERR_InvalidDynamicCondition = 7083,
ERR_WinRtEventPassedByRef = 7084,
//ERR_ByRefReturnUnsupported = 7085,
ERR_NetModuleNameMismatch = 7086,
ERR_BadModuleName = 7087,
ERR_BadCompilationOptionValue = 7088,
ERR_BadAppConfigPath = 7089,
WRN_AssemblyAttributeFromModuleIsOverridden = 7090,
ERR_CmdOptionConflictsSource = 7091,
ERR_FixedBufferTooManyDimensions = 7092,
ERR_CantReadConfigFile = 7093,
ERR_BadAwaitInCatchFilter = 7094,
WRN_FilterIsConstantTrue = 7095,
ERR_EncNoPIAReference = 7096,
//ERR_EncNoDynamicOperation = 7097, // dynamic operations are now allowed
ERR_LinkedNetmoduleMetadataMustProvideFullPEImage = 7098,
ERR_MetadataReferencesNotSupported = 7099,
ERR_InvalidAssemblyCulture = 7100,
ERR_EncReferenceToAddedMember = 7101,
ERR_MutuallyExclusiveOptions = 7102,
ERR_InvalidDebugInfo = 7103,
#endregion diagnostics introduced in C# 6
// unused 7104-8000
#region more diagnostics introduced in Roslyn (C# 6)
WRN_UnimplementedCommandLineSwitch = 8001,
WRN_ReferencedAssemblyDoesNotHaveStrongName = 8002,
ERR_InvalidSignaturePublicKey = 8003,
ERR_ExportedTypeConflictsWithDeclaration = 8004,
ERR_ExportedTypesConflict = 8005,
ERR_ForwardedTypeConflictsWithDeclaration = 8006,
ERR_ForwardedTypesConflict = 8007,
ERR_ForwardedTypeConflictsWithExportedType = 8008,
WRN_RefCultureMismatch = 8009,
ERR_AgnosticToMachineModule = 8010,
ERR_ConflictingMachineModule = 8011,
WRN_ConflictingMachineAssembly = 8012,
ERR_CryptoHashFailed = 8013,
ERR_MissingNetModuleReference = 8014,
ERR_NetModuleNameMustBeUnique = 8015,
ERR_UnsupportedTransparentIdentifierAccess = 8016,
ERR_ParamDefaultValueDiffersFromAttribute = 8017,
WRN_UnqualifiedNestedTypeInCref = 8018,
HDN_UnusedUsingDirective = 8019,
HDN_UnusedExternAlias = 8020,
WRN_NoRuntimeMetadataVersion = 8021,
ERR_FeatureNotAvailableInVersion1 = 8022, // Note: one per version to make telemetry easier
ERR_FeatureNotAvailableInVersion2 = 8023,
ERR_FeatureNotAvailableInVersion3 = 8024,
ERR_FeatureNotAvailableInVersion4 = 8025,
ERR_FeatureNotAvailableInVersion5 = 8026,
// ERR_FeatureNotAvailableInVersion6 is below
ERR_FieldHasMultipleDistinctConstantValues = 8027,
ERR_ComImportWithInitializers = 8028,
WRN_PdbLocalNameTooLong = 8029,
ERR_RetNoObjectRequiredLambda = 8030,
ERR_TaskRetNoObjectRequiredLambda = 8031,
WRN_AnalyzerCannotBeCreated = 8032,
WRN_NoAnalyzerInAssembly = 8033,
WRN_UnableToLoadAnalyzer = 8034,
ERR_CantReadRulesetFile = 8035,
ERR_BadPdbData = 8036,
// available 8037-8039
INF_UnableToLoadSomeTypesInAnalyzer = 8040,
// available 8041-8049
ERR_InitializerOnNonAutoProperty = 8050,
ERR_AutoPropertyMustHaveGetAccessor = 8051,
// ERR_AutoPropertyInitializerInInterface = 8052,
ERR_InstancePropertyInitializerInInterface = 8053,
ERR_EnumsCantContainDefaultConstructor = 8054,
ERR_EncodinglessSyntaxTree = 8055,
// ERR_AccessorListAndExpressionBody = 8056, Deprecated in favor of ERR_BlockBodyAndExpressionBody
ERR_BlockBodyAndExpressionBody = 8057,
ERR_FeatureIsExperimental = 8058,
ERR_FeatureNotAvailableInVersion6 = 8059,
// available 8062-8069
ERR_SwitchFallOut = 8070,
// available = 8071,
ERR_NullPropagatingOpInExpressionTree = 8072,
WRN_NubExprIsConstBool2 = 8073,
ERR_DictionaryInitializerInExpressionTree = 8074,
ERR_ExtensionCollectionElementInitializerInExpressionTree = 8075,
ERR_UnclosedExpressionHole = 8076,
ERR_SingleLineCommentInExpressionHole = 8077,
ERR_InsufficientStack = 8078,
ERR_UseDefViolationProperty = 8079,
ERR_AutoPropertyMustOverrideSet = 8080,
ERR_ExpressionHasNoName = 8081,
ERR_SubexpressionNotInNameof = 8082,
ERR_AliasQualifiedNameNotAnExpression = 8083,
ERR_NameofMethodGroupWithTypeParameters = 8084,
ERR_NoAliasHere = 8085,
ERR_UnescapedCurly = 8086,
ERR_EscapedCurly = 8087,
ERR_TrailingWhitespaceInFormatSpecifier = 8088,
ERR_EmptyFormatSpecifier = 8089,
ERR_ErrorInReferencedAssembly = 8090,
ERR_ExternHasConstructorInitializer = 8091,
ERR_ExpressionOrDeclarationExpected = 8092,
ERR_NameofExtensionMethod = 8093,
WRN_AlignmentMagnitude = 8094,
ERR_ConstantStringTooLong = 8095,
ERR_DebugEntryPointNotSourceMethodDefinition = 8096,
ERR_LoadDirectiveOnlyAllowedInScripts = 8097,
ERR_PPLoadFollowsToken = 8098,
ERR_SourceFileReferencesNotSupported = 8099,
ERR_BadAwaitInStaticVariableInitializer = 8100,
ERR_InvalidPathMap = 8101,
ERR_PublicSignButNoKey = 8102,
ERR_TooManyUserStrings = 8103,
ERR_PeWritingFailure = 8104,
#endregion diagnostics introduced in Roslyn (C# 6)
#region diagnostics introduced in C# 6 updates
WRN_AttributeIgnoredWhenPublicSigning = 8105,
ERR_OptionMustBeAbsolutePath = 8106,
#endregion diagnostics introduced in C# 6 updates
ERR_FeatureNotAvailableInVersion7 = 8107,
#region diagnostics for local functions introduced in C# 7
ERR_DynamicLocalFunctionParamsParameter = 8108,
ERR_ExpressionTreeContainsLocalFunction = 8110,
#endregion diagnostics for local functions introduced in C# 7
#region diagnostics for instrumentation
ERR_InvalidInstrumentationKind = 8111,
#endregion
ERR_LocalFunctionMissingBody = 8112,
ERR_InvalidHashAlgorithmName = 8113,
// Unused 8113, 8114, 8115
#region diagnostics for pattern-matching introduced in C# 7
ERR_ThrowMisplaced = 8115,
ERR_PatternNullableType = 8116,
ERR_BadPatternExpression = 8117,
ERR_SwitchExpressionValueExpected = 8119,
ERR_SwitchCaseSubsumed = 8120,
ERR_PatternWrongType = 8121,
ERR_ExpressionTreeContainsIsMatch = 8122,
#endregion diagnostics for pattern-matching introduced in C# 7
#region tuple diagnostics introduced in C# 7
WRN_TupleLiteralNameMismatch = 8123,
ERR_TupleTooFewElements = 8124,
ERR_TupleReservedElementName = 8125,
ERR_TupleReservedElementNameAnyPosition = 8126,
ERR_TupleDuplicateElementName = 8127,
ERR_PredefinedTypeMemberNotFoundInAssembly = 8128,
ERR_MissingDeconstruct = 8129,
ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable = 8130,
ERR_DeconstructRequiresExpression = 8131,
ERR_DeconstructWrongCardinality = 8132,
ERR_CannotDeconstructDynamic = 8133,
ERR_DeconstructTooFewElements = 8134,
ERR_ConversionNotTupleCompatible = 8135,
ERR_DeconstructionVarFormDisallowsSpecificType = 8136,
ERR_TupleElementNamesAttributeMissing = 8137,
ERR_ExplicitTupleElementNamesAttribute = 8138,
ERR_CantChangeTupleNamesOnOverride = 8139,
ERR_DuplicateInterfaceWithTupleNamesInBaseList = 8140,
ERR_ImplBadTupleNames = 8141,
ERR_PartialMethodInconsistentTupleNames = 8142,
ERR_ExpressionTreeContainsTupleLiteral = 8143,
ERR_ExpressionTreeContainsTupleConversion = 8144,
#endregion tuple diagnostics introduced in C# 7
#region diagnostics for ref locals and ref returns introduced in C# 7
ERR_AutoPropertyCannotBeRefReturning = 8145,
ERR_RefPropertyMustHaveGetAccessor = 8146,
ERR_RefPropertyCannotHaveSetAccessor = 8147,
ERR_CantChangeRefReturnOnOverride = 8148,
ERR_MustNotHaveRefReturn = 8149,
ERR_MustHaveRefReturn = 8150,
ERR_RefReturnMustHaveIdentityConversion = 8151,
ERR_CloseUnimplementedInterfaceMemberWrongRefReturn = 8152,
ERR_RefReturningCallInExpressionTree = 8153,
ERR_BadIteratorReturnRef = 8154,
ERR_BadRefReturnExpressionTree = 8155,
ERR_RefReturnLvalueExpected = 8156,
ERR_RefReturnNonreturnableLocal = 8157,
ERR_RefReturnNonreturnableLocal2 = 8158,
ERR_RefReturnRangeVariable = 8159,
ERR_RefReturnReadonly = 8160,
ERR_RefReturnReadonlyStatic = 8161,
ERR_RefReturnReadonly2 = 8162,
ERR_RefReturnReadonlyStatic2 = 8163,
// ERR_RefReturnCall = 8164, we use more general ERR_EscapeCall now
// ERR_RefReturnCall2 = 8165, we use more general ERR_EscapeCall2 now
ERR_RefReturnParameter = 8166,
ERR_RefReturnParameter2 = 8167,
ERR_RefReturnLocal = 8168,
ERR_RefReturnLocal2 = 8169,
ERR_RefReturnStructThis = 8170,
ERR_InitializeByValueVariableWithReference = 8171,
ERR_InitializeByReferenceVariableWithValue = 8172,
ERR_RefAssignmentMustHaveIdentityConversion = 8173,
ERR_ByReferenceVariableMustBeInitialized = 8174,
ERR_AnonDelegateCantUseLocal = 8175,
ERR_BadIteratorLocalType = 8176,
ERR_BadAsyncLocalType = 8177,
ERR_RefReturningCallAndAwait = 8178,
#endregion diagnostics for ref locals and ref returns introduced in C# 7
#region stragglers for C# 7
ERR_PredefinedValueTupleTypeNotFound = 8179, // We need a specific error code for ValueTuple as an IDE codefix depends on it (AddNuget)
ERR_SemiOrLBraceOrArrowExpected = 8180,
ERR_NewWithTupleTypeSyntax = 8181,
ERR_PredefinedValueTupleTypeMustBeStruct = 8182,
ERR_DiscardTypeInferenceFailed = 8183,
// ERR_MixedDeconstructionUnsupported = 8184,
ERR_DeclarationExpressionNotPermitted = 8185,
ERR_MustDeclareForeachIteration = 8186,
ERR_TupleElementNamesInDeconstruction = 8187,
ERR_ExpressionTreeContainsThrowExpression = 8188,
ERR_DelegateRefMismatch = 8189,
#endregion stragglers for C# 7
#region diagnostics for parse options
ERR_BadSourceCodeKind = 8190,
ERR_BadDocumentationMode = 8191,
ERR_BadLanguageVersion = 8192,
#endregion
// Unused 8193-8195
#region diagnostics for out var
ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList = 8196,
ERR_TypeInferenceFailedForImplicitlyTypedOutVariable = 8197,
ERR_ExpressionTreeContainsOutVariable = 8198,
#endregion diagnostics for out var
#region more stragglers for C# 7
ERR_VarInvocationLvalueReserved = 8199,
//ERR_ExpressionVariableInConstructorOrFieldInitializer = 8200,
//ERR_ExpressionVariableInQueryClause = 8201,
ERR_PublicSignNetModule = 8202,
ERR_BadAssemblyName = 8203,
ERR_BadAsyncMethodBuilderTaskProperty = 8204,
// ERR_AttributesInLocalFuncDecl = 8205,
ERR_TypeForwardedToMultipleAssemblies = 8206,
ERR_ExpressionTreeContainsDiscard = 8207,
ERR_PatternDynamicType = 8208,
ERR_VoidAssignment = 8209,
ERR_VoidInTuple = 8210,
#endregion more stragglers for C# 7
#region diagnostics introduced for C# 7.1
ERR_Merge_conflict_marker_encountered = 8300,
ERR_InvalidPreprocessingSymbol = 8301,
ERR_FeatureNotAvailableInVersion7_1 = 8302,
ERR_LanguageVersionCannotHaveLeadingZeroes = 8303,
ERR_CompilerAndLanguageVersion = 8304,
WRN_Experimental = 8305,
ERR_TupleInferredNamesNotAvailable = 8306,
ERR_TypelessTupleInAs = 8307,
ERR_NoRefOutWhenRefOnly = 8308,
ERR_NoNetModuleOutputWhenRefOutOrRefOnly = 8309,
ERR_BadOpOnNullOrDefaultOrNew = 8310,
// ERR_BadDynamicMethodArgDefaultLiteral = 8311,
ERR_DefaultLiteralNotValid = 8312,
// ERR_DefaultInSwitch = 8313,
ERR_PatternWrongGenericTypeInVersion = 8314,
ERR_AmbigBinaryOpsOnDefault = 8315,
#endregion diagnostics introduced for C# 7.1
#region diagnostics introduced for C# 7.2
ERR_FeatureNotAvailableInVersion7_2 = 8320,
WRN_UnreferencedLocalFunction = 8321,
ERR_DynamicLocalFunctionTypeParameter = 8322,
ERR_BadNonTrailingNamedArgument = 8323,
ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation = 8324,
#endregion diagnostics introduced for C# 7.2
#region diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2
ERR_RefConditionalAndAwait = 8325,
ERR_RefConditionalNeedsTwoRefs = 8326,
ERR_RefConditionalDifferentTypes = 8327,
ERR_BadParameterModifiers = 8328,
ERR_RefReadonlyNotField = 8329,
ERR_RefReadonlyNotField2 = 8330,
ERR_AssignReadonlyNotField = 8331,
ERR_AssignReadonlyNotField2 = 8332,
ERR_RefReturnReadonlyNotField = 8333,
ERR_RefReturnReadonlyNotField2 = 8334,
ERR_ExplicitReservedAttr = 8335,
ERR_TypeReserved = 8336,
ERR_RefExtensionMustBeValueTypeOrConstrainedToOne = 8337,
ERR_InExtensionMustBeValueType = 8338,
// ERR_BadParameterModifiersOrder = 8339, // Modifier ordering is relaxed
ERR_FieldsInRoStruct = 8340,
ERR_AutoPropsInRoStruct = 8341,
ERR_FieldlikeEventsInRoStruct = 8342,
ERR_RefStructInterfaceImpl = 8343,
ERR_BadSpecialByRefIterator = 8344,
ERR_FieldAutoPropCantBeByRefLike = 8345,
ERR_StackAllocConversionNotPossible = 8346,
ERR_EscapeCall = 8347,
ERR_EscapeCall2 = 8348,
ERR_EscapeOther = 8349,
ERR_CallArgMixing = 8350,
ERR_MismatchedRefEscapeInTernary = 8351,
ERR_EscapeLocal = 8352,
ERR_EscapeStackAlloc = 8353,
ERR_RefReturnThis = 8354,
ERR_OutAttrOnInParam = 8355,
#endregion diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2
ERR_PredefinedValueTupleTypeAmbiguous3 = 8356,
ERR_InvalidVersionFormatDeterministic = 8357,
ERR_AttributeCtorInParameter = 8358,
#region diagnostics for FilterIsConstant warning message fix
WRN_FilterIsConstantFalse = 8359,
WRN_FilterIsConstantFalseRedundantTryCatch = 8360,
#endregion diagnostics for FilterIsConstant warning message fix
ERR_ConditionalInInterpolation = 8361,
ERR_CantUseVoidInArglist = 8362,
ERR_InDynamicMethodArg = 8364,
#region diagnostics introduced for C# 7.3
ERR_FeatureNotAvailableInVersion7_3 = 8370,
WRN_AttributesOnBackingFieldsNotAvailable = 8371,
ERR_DoNotUseFixedBufferAttrOnProperty = 8372,
ERR_RefLocalOrParamExpected = 8373,
ERR_RefAssignNarrower = 8374,
ERR_NewBoundWithUnmanaged = 8375,
//ERR_UnmanagedConstraintMustBeFirst = 8376,
ERR_UnmanagedConstraintNotSatisfied = 8377,
ERR_CantUseInOrOutInArglist = 8378,
ERR_ConWithUnmanagedCon = 8379,
ERR_UnmanagedBoundWithClass = 8380,
ERR_InvalidStackAllocArray = 8381,
ERR_ExpressionTreeContainsTupleBinOp = 8382,
WRN_TupleBinopLiteralNameMismatch = 8383,
ERR_TupleSizesMismatchForBinOps = 8384,
ERR_ExprCannotBeFixed = 8385,
ERR_InvalidObjectCreation = 8386,
#endregion diagnostics introduced for C# 7.3
WRN_TypeParameterSameAsOuterMethodTypeParameter = 8387,
ERR_OutVariableCannotBeByRef = 8388,
ERR_OmittedTypeArgument = 8389,
#region diagnostics introduced for C# 8.0
ERR_FeatureNotAvailableInVersion8 = 8400,
ERR_AltInterpolatedVerbatimStringsNotAvailable = 8401,
// Unused 8402
ERR_IteratorMustBeAsync = 8403,
ERR_NoConvToIAsyncDisp = 8410,
ERR_AwaitForEachMissingMember = 8411,
ERR_BadGetAsyncEnumerator = 8412,
ERR_MultipleIAsyncEnumOfT = 8413,
ERR_ForEachMissingMemberWrongAsync = 8414,
ERR_AwaitForEachMissingMemberWrongAsync = 8415,
ERR_BadDynamicAwaitForEach = 8416,
ERR_NoConvToIAsyncDispWrongAsync = 8417,
ERR_NoConvToIDispWrongAsync = 8418,
ERR_PossibleAsyncIteratorWithoutYield = 8419,
ERR_PossibleAsyncIteratorWithoutYieldOrAwait = 8420,
ERR_StaticLocalFunctionCannotCaptureVariable = 8421,
ERR_StaticLocalFunctionCannotCaptureThis = 8422,
ERR_AttributeNotOnEventAccessor = 8423,
WRN_UnconsumedEnumeratorCancellationAttributeUsage = 8424,
WRN_UndecoratedCancellationTokenParameter = 8425,
ERR_MultipleEnumeratorCancellationAttributes = 8426,
ERR_VarianceInterfaceNesting = 8427,
ERR_ImplicitIndexIndexerWithName = 8428,
ERR_ImplicitRangeIndexerWithName = 8429,
// available range
#region diagnostics introduced for recursive patterns
ERR_WrongNumberOfSubpatterns = 8502,
ERR_PropertyPatternNameMissing = 8503,
ERR_MissingPattern = 8504,
ERR_DefaultPattern = 8505,
ERR_SwitchExpressionNoBestType = 8506,
// ERR_SingleElementPositionalPatternRequiresDisambiguation = 8507, // Retired C# 8 diagnostic
ERR_VarMayNotBindToType = 8508,
WRN_SwitchExpressionNotExhaustive = 8509,
ERR_SwitchArmSubsumed = 8510,
ERR_ConstantPatternVsOpenType = 8511,
WRN_CaseConstantNamedUnderscore = 8512,
WRN_IsTypeNamedUnderscore = 8513,
ERR_ExpressionTreeContainsSwitchExpression = 8514,
ERR_SwitchGoverningExpressionRequiresParens = 8515,
ERR_TupleElementNameMismatch = 8516,
ERR_DeconstructParameterNameMismatch = 8517,
ERR_IsPatternImpossible = 8518,
WRN_GivenExpressionNeverMatchesPattern = 8519,
WRN_GivenExpressionAlwaysMatchesConstant = 8520,
ERR_PointerTypeInPatternMatching = 8521,
ERR_ArgumentNameInITuplePattern = 8522,
ERR_DiscardPatternInSwitchStatement = 8523,
WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue = 8524,
// available 8525-8596
#endregion diagnostics introduced for recursive patterns
WRN_ThrowPossibleNull = 8597,
ERR_IllegalSuppression = 8598,
// available 8599,
WRN_ConvertingNullableToNonNullable = 8600,
WRN_NullReferenceAssignment = 8601,
WRN_NullReferenceReceiver = 8602,
WRN_NullReferenceReturn = 8603,
WRN_NullReferenceArgument = 8604,
WRN_UnboxPossibleNull = 8605,
// WRN_NullReferenceIterationVariable = 8606 (unavailable, may be used in warning suppressions in early C# 8.0 code)
WRN_DisallowNullAttributeForbidsMaybeNullAssignment = 8607,
WRN_NullabilityMismatchInTypeOnOverride = 8608,
WRN_NullabilityMismatchInReturnTypeOnOverride = 8609,
WRN_NullabilityMismatchInParameterTypeOnOverride = 8610,
WRN_NullabilityMismatchInParameterTypeOnPartial = 8611,
WRN_NullabilityMismatchInTypeOnImplicitImplementation = 8612,
WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation = 8613,
WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation = 8614,
WRN_NullabilityMismatchInTypeOnExplicitImplementation = 8615,
WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation = 8616,
WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation = 8617,
WRN_UninitializedNonNullableField = 8618,
WRN_NullabilityMismatchInAssignment = 8619,
WRN_NullabilityMismatchInArgument = 8620,
WRN_NullabilityMismatchInReturnTypeOfTargetDelegate = 8621,
WRN_NullabilityMismatchInParameterTypeOfTargetDelegate = 8622,
ERR_ExplicitNullableAttribute = 8623,
WRN_NullabilityMismatchInArgumentForOutput = 8624,
WRN_NullAsNonNullable = 8625,
//WRN_AsOperatorMayReturnNull = 8626,
ERR_NullableUnconstrainedTypeParameter = 8627,
ERR_AnnotationDisallowedInObjectCreation = 8628,
WRN_NullableValueTypeMayBeNull = 8629,
ERR_NullableOptionNotAvailable = 8630,
WRN_NullabilityMismatchInTypeParameterConstraint = 8631,
WRN_MissingNonNullTypesContextForAnnotation = 8632,
WRN_NullabilityMismatchInConstraintsOnImplicitImplementation = 8633,
WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint = 8634,
ERR_TripleDotNotAllowed = 8635,
ERR_BadNullableContextOption = 8636,
ERR_NullableDirectiveQualifierExpected = 8637,
//WRN_ConditionalAccessMayReturnNull = 8638,
ERR_BadNullableTypeof = 8639,
ERR_ExpressionTreeCantContainRefStruct = 8640,
ERR_ElseCannotStartStatement = 8641,
ERR_ExpressionTreeCantContainNullCoalescingAssignment = 8642,
WRN_NullabilityMismatchInExplicitlyImplementedInterface = 8643,
WRN_NullabilityMismatchInInterfaceImplementedByBase = 8644,
WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList = 8645,
ERR_DuplicateExplicitImpl = 8646,
ERR_UsingVarInSwitchCase = 8647,
ERR_GoToForwardJumpOverUsingVar = 8648,
ERR_GoToBackwardJumpOverUsingVar = 8649,
ERR_IsNullableType = 8650,
ERR_AsNullableType = 8651,
ERR_FeatureInPreview = 8652,
//WRN_DefaultExpressionMayIntroduceNullT = 8653,
//WRN_NullLiteralMayIntroduceNullT = 8654,
WRN_SwitchExpressionNotExhaustiveForNull = 8655,
WRN_ImplicitCopyInReadOnlyMember = 8656,
ERR_StaticMemberCantBeReadOnly = 8657,
ERR_AutoSetterCantBeReadOnly = 8658,
ERR_AutoPropertyWithSetterCantBeReadOnly = 8659,
ERR_InvalidPropertyReadOnlyMods = 8660,
ERR_DuplicatePropertyReadOnlyMods = 8661,
ERR_FieldLikeEventCantBeReadOnly = 8662,
ERR_PartialMethodReadOnlyDifference = 8663,
ERR_ReadOnlyModMissingAccessor = 8664,
ERR_OverrideRefConstraintNotSatisfied = 8665,
ERR_OverrideValConstraintNotSatisfied = 8666,
WRN_NullabilityMismatchInConstraintsOnPartialImplementation = 8667,
ERR_NullableDirectiveTargetExpected = 8668,
WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode = 8669,
WRN_NullReferenceInitializer = 8670,
ERR_MultipleAnalyzerConfigsInSameDir = 8700,
ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation = 8701,
ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember = 8702,
ERR_InvalidModifierForLanguageVersion = 8703,
ERR_ImplicitImplementationOfNonPublicInterfaceMember = 8704,
ERR_MostSpecificImplementationIsNotFound = 8705,
ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember = 8706,
ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember = 8707,
//ERR_NotBaseOrImplementedInterface = 8708,
//ERR_NotImplementedInBase = 8709,
//ERR_NotDeclaredInBase = 8710,
ERR_DefaultInterfaceImplementationInNoPIAType = 8711,
ERR_AbstractEventHasAccessors = 8712,
//ERR_NotNullConstraintMustBeFirst = 8713,
WRN_NullabilityMismatchInTypeParameterNotNullConstraint = 8714,
ERR_DuplicateNullSuppression = 8715,
ERR_DefaultLiteralNoTargetType = 8716,
ERR_ReAbstractionInNoPIAType = 8750,
#endregion diagnostics introduced for C# 8.0
#region diagnostics introduced in C# 9.0
ERR_InternalError = 8751,
ERR_ImplicitObjectCreationIllegalTargetType = 8752,
ERR_ImplicitObjectCreationNotValid = 8753,
ERR_ImplicitObjectCreationNoTargetType = 8754,
ERR_BadFuncPointerParamModifier = 8755,
ERR_BadFuncPointerArgCount = 8756,
ERR_MethFuncPtrMismatch = 8757,
ERR_FuncPtrRefMismatch = 8758,
ERR_FuncPtrMethMustBeStatic = 8759,
ERR_ExternEventInitializer = 8760,
ERR_AmbigBinaryOpsOnUnconstrainedDefault = 8761,
WRN_ParameterConditionallyDisallowsNull = 8762,
WRN_ShouldNotReturn = 8763,
WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride = 8764,
WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride = 8765,
WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation = 8766,
WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation = 8767,
WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation = 8768,
WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation = 8769,
WRN_DoesNotReturnMismatch = 8770,
ERR_NoOutputDirectory = 8771,
ERR_StdInOptionProvidedButConsoleInputIsNotRedirected = 8772,
ERR_FeatureNotAvailableInVersion9 = 8773,
WRN_MemberNotNull = 8774,
WRN_MemberNotNullWhen = 8775,
WRN_MemberNotNullBadMember = 8776,
WRN_ParameterDisallowsNull = 8777,
WRN_ConstOutOfRangeChecked = 8778,
ERR_DuplicateInterfaceWithDifferencesInBaseList = 8779,
ERR_DesignatorBeneathPatternCombinator = 8780,
ERR_UnsupportedTypeForRelationalPattern = 8781,
ERR_RelationalPatternWithNaN = 8782,
ERR_ConditionalOnLocalFunction = 8783,
WRN_GeneratorFailedDuringInitialization = 8784,
WRN_GeneratorFailedDuringGeneration = 8785,
ERR_WrongFuncPtrCallingConvention = 8786,
ERR_MissingAddressOf = 8787,
ERR_CannotUseReducedExtensionMethodInAddressOf = 8788,
ERR_CannotUseFunctionPointerAsFixedLocal = 8789,
ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer = 8790,
ERR_ExpressionTreeContainsFromEndIndexExpression = 8791,
ERR_ExpressionTreeContainsRangeExpression = 8792,
WRN_GivenExpressionAlwaysMatchesPattern = 8793,
WRN_IsPatternAlways = 8794,
ERR_PartialMethodWithAccessibilityModsMustHaveImplementation = 8795,
ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods = 8796,
ERR_PartialMethodWithOutParamMustHaveAccessMods = 8797,
ERR_PartialMethodWithExtendedModMustHaveAccessMods = 8798,
ERR_PartialMethodAccessibilityDifference = 8799,
ERR_PartialMethodExtendedModDifference = 8800,
ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement = 8801,
ERR_SimpleProgramMultipleUnitsWithTopLevelStatements = 8802,
ERR_TopLevelStatementAfterNamespaceOrType = 8803,
ERR_SimpleProgramDisallowsMainType = 8804,
ERR_SimpleProgramNotAnExecutable = 8805,
ERR_UnsupportedCallingConvention = 8806,
ERR_InvalidFunctionPointerCallingConvention = 8807,
ERR_InvalidFuncPointerReturnTypeModifier = 8808,
ERR_DupReturnTypeMod = 8809,
ERR_AddressOfMethodGroupInExpressionTree = 8810,
ERR_CannotConvertAddressOfToDelegate = 8811,
ERR_AddressOfToNonFunctionPointer = 8812,
ERR_ModuleInitializerMethodMustBeOrdinary = 8813,
ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType = 8814,
ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid = 8815,
ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric = 8816,
ERR_PartialMethodReturnTypeDifference = 8817,
ERR_PartialMethodRefReturnDifference = 8818,
WRN_NullabilityMismatchInReturnTypeOnPartial = 8819,
ERR_StaticAnonymousFunctionCannotCaptureVariable = 8820,
ERR_StaticAnonymousFunctionCannotCaptureThis = 8821,
ERR_OverrideDefaultConstraintNotSatisfied = 8822,
ERR_DefaultConstraintOverrideOnly = 8823,
WRN_ParameterNotNullIfNotNull = 8824,
WRN_ReturnNotNullIfNotNull = 8825,
WRN_PartialMethodTypeDifference = 8826,
ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses = 8830,
ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses = 8831,
WRN_SwitchExpressionNotExhaustiveWithWhen = 8846,
WRN_SwitchExpressionNotExhaustiveForNullWithWhen = 8847,
WRN_PrecedenceInversion = 8848,
ERR_ExpressionTreeContainsWithExpression = 8849,
WRN_AnalyzerReferencesFramework = 8850,
// WRN_EqualsWithoutGetHashCode is for object.Equals and works for classes.
// WRN_RecordEqualsWithoutGetHashCode is for IEquatable<T>.Equals and works for records.
WRN_RecordEqualsWithoutGetHashCode = 8851,
ERR_AssignmentInitOnly = 8852,
ERR_CantChangeInitOnlyOnOverride = 8853,
ERR_CloseUnimplementedInterfaceMemberWrongInitOnly = 8854,
ERR_ExplicitPropertyMismatchInitOnly = 8855,
ERR_BadInitAccessor = 8856,
ERR_InvalidWithReceiverType = 8857,
ERR_CannotClone = 8858,
ERR_CloneDisallowedInRecord = 8859,
WRN_RecordNamedDisallowed = 8860,
ERR_UnexpectedArgumentList = 8861,
ERR_UnexpectedOrMissingConstructorInitializerInRecord = 8862,
ERR_MultipleRecordParameterLists = 8863,
ERR_BadRecordBase = 8864,
ERR_BadInheritanceFromRecord = 8865,
ERR_BadRecordMemberForPositionalParameter = 8866,
ERR_NoCopyConstructorInBaseType = 8867,
ERR_CopyConstructorMustInvokeBaseCopyConstructor = 8868,
ERR_DoesNotOverrideMethodFromObject = 8869,
ERR_SealedAPIInRecord = 8870,
ERR_DoesNotOverrideBaseMethod = 8871,
ERR_NotOverridableAPIInRecord = 8872,
ERR_NonPublicAPIInRecord = 8873,
ERR_SignatureMismatchInRecord = 8874,
ERR_NonProtectedAPIInRecord = 8875,
ERR_DoesNotOverrideBaseEqualityContract = 8876,
ERR_StaticAPIInRecord = 8877,
ERR_CopyConstructorWrongAccessibility = 8878,
ERR_NonPrivateAPIInRecord = 8879,
// The following warnings correspond to errors of the same name, but are reported
// when a definite assignment issue is reported due to private fields imported from metadata.
WRN_UnassignedThisAutoProperty = 8880,
WRN_UnassignedThis = 8881,
WRN_ParamUnassigned = 8882,
WRN_UseDefViolationProperty = 8883,
WRN_UseDefViolationField = 8884,
WRN_UseDefViolationThis = 8885,
WRN_UseDefViolationOut = 8886,
WRN_UseDefViolation = 8887,
ERR_CannotSpecifyManagedWithUnmanagedSpecifiers = 8888,
ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv = 8889,
ERR_TypeNotFound = 8890,
ERR_TypeMustBePublic = 8891,
WRN_SyncAndAsyncEntryPoints = 8892,
ERR_InvalidUnmanagedCallersOnlyCallConv = 8893,
ERR_CannotUseManagedTypeInUnmanagedCallersOnly = 8894,
ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric = 8895,
ERR_UnmanagedCallersOnlyRequiresStatic = 8896,
// The following warnings correspond to errors of the same name, but are reported
// as warnings on interface methods and properties due in warning level 5. They
// were not reported at all prior to level 5.
WRN_ParameterIsStaticClass = 8897,
WRN_ReturnTypeIsStaticClass = 8898,
ERR_EntryPointCannotBeUnmanagedCallersOnly = 8899,
ERR_ModuleInitializerCannotBeUnmanagedCallersOnly = 8900,
ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly = 8901,
ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate = 8902,
ERR_InitCannotBeReadonly = 8903,
ERR_UnexpectedVarianceStaticMember = 8904,
ERR_FunctionPointersCannotBeCalledWithNamedArguments = 8905,
ERR_EqualityContractRequiresGetter = 8906,
WRN_UnreadRecordParameter = 8907,
ERR_BadFieldTypeInRecord = 8908,
WRN_DoNotCompareFunctionPointers = 8909,
ERR_RecordAmbigCtor = 8910,
ERR_FunctionPointerTypesInAttributeNotSupported = 8911,
#endregion diagnostics introduced for C# 9.0
#region diagnostics introduced for C# 10.0
ERR_InheritingFromRecordWithSealedToString = 8912,
ERR_HiddenPositionalMember = 8913,
ERR_GlobalUsingInNamespace = 8914,
ERR_GlobalUsingOutOfOrder = 8915,
ERR_AttributesRequireParenthesizedLambdaExpression = 8916,
ERR_CannotInferDelegateType = 8917,
ERR_InvalidNameInSubpattern = 8918,
ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces = 8919,
ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers = 8920,
ERR_BadAbstractUnaryOperatorSignature = 8921,
ERR_BadAbstractIncDecSignature = 8922,
ERR_BadAbstractIncDecRetType = 8923,
ERR_BadAbstractBinaryOperatorSignature = 8924,
ERR_BadAbstractShiftOperatorSignature = 8925,
ERR_BadAbstractStaticMemberAccess = 8926,
ERR_ExpressionTreeContainsAbstractStaticMemberAccess = 8927,
ERR_CloseUnimplementedInterfaceMemberNotStatic = 8928,
ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember = 8929,
ERR_ExplicitImplementationOfOperatorsMustBeStatic = 8930,
ERR_AbstractConversionNotInvolvingContainedType = 8931,
ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod = 8932,
HDN_DuplicateWithGlobalUsing = 8933,
ERR_CantConvAnonMethReturnType = 8934,
ERR_BuilderAttributeDisallowed = 8935,
ERR_FeatureNotAvailableInVersion10 = 8936,
ERR_SimpleProgramIsEmpty = 8937,
ERR_LineSpanDirectiveInvalidValue = 8938,
ERR_LineSpanDirectiveEndLessThanStart = 8939,
ERR_WrongArityAsyncReturn = 8940,
ERR_InterpolatedStringHandlerMethodReturnMalformed = 8941,
ERR_InterpolatedStringHandlerMethodReturnInconsistent = 8942,
ERR_NullInvalidInterpolatedStringHandlerArgumentName = 8943,
ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName = 8944,
ERR_InvalidInterpolatedStringHandlerArgumentName = 8945,
ERR_TypeIsNotAnInterpolatedStringHandlerType = 8946,
WRN_ParameterOccursAfterInterpolatedStringHandlerParameter = 8947,
ERR_CannotUseSelfAsInterpolatedStringHandlerArgument = 8948,
ERR_InterpolatedStringHandlerArgumentAttributeMalformed = 8949,
ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString = 8950,
ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified = 8951,
ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion = 8952,
ERR_InterpolatedStringHandlerCreationCannotUseDynamic = 8953,
ERR_MultipleFileScopedNamespace = 8954,
ERR_FileScopedAndNormalNamespace = 8955,
ERR_FileScopedNamespaceNotBeforeAllMembers = 8956,
ERR_NoImplicitConvTargetTypedConditional = 8957,
ERR_NonPublicParameterlessStructConstructor = 8958,
ERR_NoConversionForCallerArgumentExpressionParam = 8959,
WRN_CallerLineNumberPreferredOverCallerArgumentExpression = 8960,
WRN_CallerFilePathPreferredOverCallerArgumentExpression = 8961,
WRN_CallerMemberNamePreferredOverCallerArgumentExpression = 8962,
WRN_CallerArgumentExpressionAttributeHasInvalidParameterName = 8963,
ERR_BadCallerArgumentExpressionParamWithoutDefaultValue = 8964,
WRN_CallerArgumentExpressionAttributeSelfReferential = 8965,
WRN_CallerArgumentExpressionParamForUnconsumedLocation = 8966,
ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString = 8967,
ERR_AttrTypeArgCannotBeTypeVar = 8968,
// WRN_AttrDependentTypeNotAllowed = 8969, // Backed out of of warning wave 6, may be reintroduced later
ERR_AttrDependentTypeNotAllowed = 8970,
WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters = 8971,
#endregion
// Note: you will need to re-generate compiler code after adding warnings (eng\generate-compiler-code.cmd)
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.