repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/EditorFeatures/TestUtilities/Squiggles/SquiggleUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles
{
public static class SquiggleUtilities
{
// Squiggle tests require solution crawler to run.
internal static TestComposition CompositionWithSolutionCrawler = EditorTestCompositions.EditorFeatures
.RemoveParts(typeof(MockWorkspaceEventListenerProvider));
internal static async Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpansAsync<TProvider>(
TestWorkspace workspace,
IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null)
where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag>
{
using var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, analyzerMap);
var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());
using var disposable = tagger as IDisposable;
await wrapper.WaitForTags();
var analyzerDiagnostics = await wrapper.AnalyzerService.GetDiagnosticsAsync(workspace.CurrentSolution);
var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray();
return (analyzerDiagnostics, spans);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles
{
public static class SquiggleUtilities
{
// Squiggle tests require solution crawler to run.
internal static TestComposition CompositionWithSolutionCrawler = EditorTestCompositions.EditorFeatures
.RemoveParts(typeof(MockWorkspaceEventListenerProvider));
internal static async Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpansAsync<TProvider>(
TestWorkspace workspace,
IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null)
where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag>
{
using var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, analyzerMap);
var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());
using var disposable = tagger as IDisposable;
await wrapper.WaitForTags();
var analyzerDiagnostics = await wrapper.AnalyzerService.GetDiagnosticsAsync(workspace.CurrentSolution);
var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray();
return (analyzerDiagnostics, spans);
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICoalesceOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ICoalesceOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_01()
{
var source = @"
class C
{
void F(int? input, int alternative, int result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_02()
{
var source = @"
class C
{
void F(int? input, long alternative, long result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_03()
{
var source = @"
class C
{
void F(int? input, long? alternative, long? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_04()
{
var source = @"
class C
{
void F(string input, object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_05()
{
var source = @"
class C
{
void F(int? input, System.DateTime alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime'
// result = input ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_06()
{
var source = @"
class C
{
void F(int? input, dynamic alternative, dynamic result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_07()
{
var source = @"
class C
{
void F(dynamic alternative, dynamic result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
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: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_08()
{
var source = @"
class C
{
void F(int alternative, int result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int'
// result = null ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_09()
{
var source = @"
class C
{
void F(int? alternative, int? result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_10()
{
var source = @"
class C
{
void F(int? input, byte? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_11()
{
var source = @"
class C
{
void F(int? input, int? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_12()
{
var source = @"
class C
{
void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result)
/*<bind>*/{
result = (input1 ?? alternative1) ?? (input2 ?? alternative2);
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1')
Value:
IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Leaving: {R2}
Entering: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1')
Value:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Next (Regular) Block[B10]
Leaving: {R2}
}
.locals {R4}
{
CaptureIds: [4]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2')
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Leaving: {R4}
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Next (Regular) Block[B10]
Leaving: {R4}
}
Block[B9] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2')
Value:
IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B6] [B8] [B9]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)')
Next (Regular) Block[B11]
Leaving: {R1}
}
Block[B11] - Exit
Predecessors: [B10]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_13()
{
var source = @"
class C
{
const string input = ""a"";
void F(object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
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: 'input')
Value:
IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input')
Instance Receiver:
null
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_14()
{
string source = @"
class P
{
void M1(int? i, int j, int result)
/*<bind>*/{
result = i ?? j;
}/*</bind>*/
}
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
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: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
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_ICoalesceOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_01()
{
var source = @"
class C
{
void F(int? input, int alternative, int result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_02()
{
var source = @"
class C
{
void F(int? input, long alternative, long result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_03()
{
var source = @"
class C
{
void F(int? input, long? alternative, long? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_04()
{
var source = @"
class C
{
void F(string input, object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_05()
{
var source = @"
class C
{
void F(int? input, System.DateTime alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime'
// result = input ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_06()
{
var source = @"
class C
{
void F(int? input, dynamic alternative, dynamic result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_07()
{
var source = @"
class C
{
void F(dynamic alternative, dynamic result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
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: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_08()
{
var source = @"
class C
{
void F(int alternative, int result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int'
// result = null ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_09()
{
var source = @"
class C
{
void F(int? alternative, int? result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_10()
{
var source = @"
class C
{
void F(int? input, byte? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_11()
{
var source = @"
class C
{
void F(int? input, int? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_12()
{
var source = @"
class C
{
void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result)
/*<bind>*/{
result = (input1 ?? alternative1) ?? (input2 ?? alternative2);
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
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, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1')
Value:
IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Leaving: {R2}
Entering: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1')
Value:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Next (Regular) Block[B10]
Leaving: {R2}
}
.locals {R4}
{
CaptureIds: [4]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2')
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Leaving: {R4}
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Next (Regular) Block[B10]
Leaving: {R4}
}
Block[B9] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2')
Value:
IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B6] [B8] [B9]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)')
Next (Regular) Block[B11]
Leaving: {R1}
}
Block[B11] - Exit
Predecessors: [B10]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_13()
{
var source = @"
class C
{
const string input = ""a"";
void F(object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
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: 'input')
Value:
IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input')
Instance Receiver:
null
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_14()
{
string source = @"
class P
{
void M1(int? i, int j, int result)
/*<bind>*/{
result = i ?? j;
}/*</bind>*/
}
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
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: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Analyzers/Core/Analyzers/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NewLines.MultipleBlankLines
{
internal abstract class AbstractMultipleBlankLinesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private readonly ISyntaxFacts _syntaxFacts;
protected AbstractMultipleBlankLinesDiagnosticAnalyzer(ISyntaxFacts syntaxFacts)
: base(IDEDiagnosticIds.MultipleBlankLinesDiagnosticId,
EnforceOnBuildValues.MultipleBlankLines,
CodeStyleOptions2.AllowMultipleBlankLines,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(AnalyzersResources.Avoid_multiple_blank_lines), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
_syntaxFacts = syntaxFacts;
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeTree);
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
var option = context.GetOption(CodeStyleOptions2.AllowMultipleBlankLines, context.Tree.Options.Language);
if (option.Value)
return;
var tree = context.Tree;
var cancellationToken = context.CancellationToken;
var root = tree.GetRoot(cancellationToken);
Recurse(context, option.Notification.Severity, root, cancellationToken);
}
private void Recurse(
SyntaxTreeAnalysisContext context,
ReportDiagnostic severity,
SyntaxNode node,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Don't bother analyzing nodes that have syntax errors in them.
if (node.ContainsDiagnostics)
return;
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
Recurse(context, severity, child.AsNode()!, cancellationToken);
else if (child.IsToken)
CheckToken(context, severity, child.AsToken());
}
}
private void CheckToken(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxToken token)
{
if (token.ContainsDiagnostics)
return;
if (!ContainsMultipleBlankLines(token, out var badTrivia))
return;
context.ReportDiagnostic(DiagnosticHelper.Create(
this.Descriptor,
Location.Create(badTrivia.SyntaxTree!, new TextSpan(badTrivia.SpanStart, 0)),
severity,
additionalLocations: ImmutableArray.Create(token.GetLocation()),
properties: null));
}
private bool ContainsMultipleBlankLines(SyntaxToken token, out SyntaxTrivia firstBadTrivia)
{
var leadingTrivia = token.LeadingTrivia;
for (var i = 0; i < leadingTrivia.Count; i++)
{
if (IsEndOfLine(leadingTrivia, i) &&
IsEndOfLine(leadingTrivia, i + 1))
{
// Three cases that end up with two blank lines.
//
// 1. the token starts with two newlines. This is definitely something to clean up.
// 2. we have two newlines after structured trivia (which itself ends with an newline).
// 3. we have three newlines (following non-structured trivia).
if (i == 0 ||
leadingTrivia[i - 1].HasStructure)
{
firstBadTrivia = leadingTrivia[i];
return true;
}
if (IsEndOfLine(leadingTrivia, i + 2))
{
// Report on the second newline. This is for cases like:
//
// // comment
//
//
// public
//
// The first newline follows the comment. But we want to report the issue on the start of the
// next line.
firstBadTrivia = leadingTrivia[i + 1];
return true;
}
}
}
firstBadTrivia = default;
return false;
}
private bool IsEndOfLine(SyntaxTriviaList triviaList, int index)
{
if (index >= triviaList.Count)
return false;
var trivia = triviaList[index];
return _syntaxFacts.IsEndOfLineTrivia(trivia);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.NewLines.MultipleBlankLines
{
internal abstract class AbstractMultipleBlankLinesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private readonly ISyntaxFacts _syntaxFacts;
protected AbstractMultipleBlankLinesDiagnosticAnalyzer(ISyntaxFacts syntaxFacts)
: base(IDEDiagnosticIds.MultipleBlankLinesDiagnosticId,
EnforceOnBuildValues.MultipleBlankLines,
CodeStyleOptions2.AllowMultipleBlankLines,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(AnalyzersResources.Avoid_multiple_blank_lines), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
_syntaxFacts = syntaxFacts;
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeTree);
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
var option = context.GetOption(CodeStyleOptions2.AllowMultipleBlankLines, context.Tree.Options.Language);
if (option.Value)
return;
var tree = context.Tree;
var cancellationToken = context.CancellationToken;
var root = tree.GetRoot(cancellationToken);
Recurse(context, option.Notification.Severity, root, cancellationToken);
}
private void Recurse(
SyntaxTreeAnalysisContext context,
ReportDiagnostic severity,
SyntaxNode node,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Don't bother analyzing nodes that have syntax errors in them.
if (node.ContainsDiagnostics)
return;
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
Recurse(context, severity, child.AsNode()!, cancellationToken);
else if (child.IsToken)
CheckToken(context, severity, child.AsToken());
}
}
private void CheckToken(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxToken token)
{
if (token.ContainsDiagnostics)
return;
if (!ContainsMultipleBlankLines(token, out var badTrivia))
return;
context.ReportDiagnostic(DiagnosticHelper.Create(
this.Descriptor,
Location.Create(badTrivia.SyntaxTree!, new TextSpan(badTrivia.SpanStart, 0)),
severity,
additionalLocations: ImmutableArray.Create(token.GetLocation()),
properties: null));
}
private bool ContainsMultipleBlankLines(SyntaxToken token, out SyntaxTrivia firstBadTrivia)
{
var leadingTrivia = token.LeadingTrivia;
for (var i = 0; i < leadingTrivia.Count; i++)
{
if (IsEndOfLine(leadingTrivia, i) &&
IsEndOfLine(leadingTrivia, i + 1))
{
// Three cases that end up with two blank lines.
//
// 1. the token starts with two newlines. This is definitely something to clean up.
// 2. we have two newlines after structured trivia (which itself ends with an newline).
// 3. we have three newlines (following non-structured trivia).
if (i == 0 ||
leadingTrivia[i - 1].HasStructure)
{
firstBadTrivia = leadingTrivia[i];
return true;
}
if (IsEndOfLine(leadingTrivia, i + 2))
{
// Report on the second newline. This is for cases like:
//
// // comment
//
//
// public
//
// The first newline follows the comment. But we want to report the issue on the start of the
// next line.
firstBadTrivia = leadingTrivia[i + 1];
return true;
}
}
}
firstBadTrivia = default;
return false;
}
private bool IsEndOfLine(SyntaxTriviaList triviaList, int index)
{
if (index >= triviaList.Count)
return false;
var trivia = triviaList[index];
return _syntaxFacts.IsEndOfLineTrivia(trivia);
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypescriptNavigationBarItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal class VSTypescriptNavigationBarItem
{
public string Text { get; }
public VSTypeScriptGlyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public ImmutableArray<VSTypescriptNavigationBarItem> ChildItems { get; }
public ImmutableArray<TextSpan> Spans { get; }
public VSTypescriptNavigationBarItem(
string text,
VSTypeScriptGlyph glyph,
ImmutableArray<TextSpan> spans,
ImmutableArray<VSTypescriptNavigationBarItem> childItems = default,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans.NullToEmpty();
this.ChildItems = childItems.NullToEmpty();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal class VSTypescriptNavigationBarItem
{
public string Text { get; }
public VSTypeScriptGlyph Glyph { get; }
public bool Bolded { get; }
public bool Grayed { get; }
public int Indent { get; }
public ImmutableArray<VSTypescriptNavigationBarItem> ChildItems { get; }
public ImmutableArray<TextSpan> Spans { get; }
public VSTypescriptNavigationBarItem(
string text,
VSTypeScriptGlyph glyph,
ImmutableArray<TextSpan> spans,
ImmutableArray<VSTypescriptNavigationBarItem> childItems = default,
int indent = 0,
bool bolded = false,
bool grayed = false)
{
this.Text = text;
this.Glyph = glyph;
this.Spans = spans.NullToEmpty();
this.ChildItems = childItems.NullToEmpty();
this.Indent = indent;
this.Bolded = bolded;
this.Grayed = grayed;
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/EditorFeatures/Test/TextEditor/TextBufferAssociatedViewServiceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Moq;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.TextEditor
{
[UseExportProvider]
public class TextBufferAssociatedViewServiceTests
{
[Fact]
public void SanityCheck()
{
var viewMock = new Mock<IWpfTextView>(MockBehavior.Strict);
var viewMock2 = new Mock<IWpfTextView>(MockBehavior.Strict);
var contentType = new Mock<IContentType>(MockBehavior.Strict);
contentType.Setup(c => c.IsOfType(ContentTypeNames.RoslynContentType)).Returns(true);
var bufferMock = new Mock<ITextBuffer>(MockBehavior.Strict);
bufferMock.Setup(b => b.ContentType).Returns(contentType.Object);
var bufferCollection = new Collection<ITextBuffer>(SpecializedCollections.SingletonEnumerable(bufferMock.Object).ToList());
var dummyReason = ConnectionReason.BufferGraphChange;
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var service = Assert.IsType<TextBufferAssociatedViewService>(exportProvider.GetExportedValue<ITextBufferAssociatedViewService>());
((ITextViewConnectionListener)service).SubjectBuffersConnected(viewMock.Object, dummyReason, bufferCollection);
Assert.Equal(1, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersDisconnected(viewMock.Object, dummyReason, bufferCollection);
Assert.Equal(0, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersConnected(viewMock.Object, dummyReason, bufferCollection);
((ITextViewConnectionListener)service).SubjectBuffersConnected(viewMock2.Object, dummyReason, bufferCollection);
Assert.Equal(2, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersDisconnected(viewMock.Object, dummyReason, bufferCollection);
Assert.Equal(1, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersDisconnected(viewMock2.Object, dummyReason, bufferCollection);
Assert.Equal(0, service.GetAssociatedTextViews(bufferMock.Object).Count());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Moq;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.TextEditor
{
[UseExportProvider]
public class TextBufferAssociatedViewServiceTests
{
[Fact]
public void SanityCheck()
{
var viewMock = new Mock<IWpfTextView>(MockBehavior.Strict);
var viewMock2 = new Mock<IWpfTextView>(MockBehavior.Strict);
var contentType = new Mock<IContentType>(MockBehavior.Strict);
contentType.Setup(c => c.IsOfType(ContentTypeNames.RoslynContentType)).Returns(true);
var bufferMock = new Mock<ITextBuffer>(MockBehavior.Strict);
bufferMock.Setup(b => b.ContentType).Returns(contentType.Object);
var bufferCollection = new Collection<ITextBuffer>(SpecializedCollections.SingletonEnumerable(bufferMock.Object).ToList());
var dummyReason = ConnectionReason.BufferGraphChange;
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var service = Assert.IsType<TextBufferAssociatedViewService>(exportProvider.GetExportedValue<ITextBufferAssociatedViewService>());
((ITextViewConnectionListener)service).SubjectBuffersConnected(viewMock.Object, dummyReason, bufferCollection);
Assert.Equal(1, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersDisconnected(viewMock.Object, dummyReason, bufferCollection);
Assert.Equal(0, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersConnected(viewMock.Object, dummyReason, bufferCollection);
((ITextViewConnectionListener)service).SubjectBuffersConnected(viewMock2.Object, dummyReason, bufferCollection);
Assert.Equal(2, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersDisconnected(viewMock.Object, dummyReason, bufferCollection);
Assert.Equal(1, service.GetAssociatedTextViews(bufferMock.Object).Count());
((ITextViewConnectionListener)service).SubjectBuffersDisconnected(viewMock2.Object, dummyReason, bufferCollection);
Assert.Equal(0, service.GetAssociatedTextViews(bufferMock.Object).Count());
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/Test/Core/Syntax/NodeInfo.FieldInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public partial class NodeInfo
{
//Package of information containing the name, type, and value of a field on a syntax node.
public class FieldInfo
{
private readonly string _propertyName;
private readonly Type _fieldType;
private readonly object _value;
public string PropertyName
{
get
{
return _propertyName;
}
}
public Type FieldType
{
get
{
return _fieldType;
}
}
public object Value
{
get
{
return _value;
}
}
public FieldInfo(string propertyName, Type fieldType, object value)
{
_propertyName = propertyName;
_fieldType = fieldType;
_value = value;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public partial class NodeInfo
{
//Package of information containing the name, type, and value of a field on a syntax node.
public class FieldInfo
{
private readonly string _propertyName;
private readonly Type _fieldType;
private readonly object _value;
public string PropertyName
{
get
{
return _propertyName;
}
}
public Type FieldType
{
get
{
return _fieldType;
}
}
public object Value
{
get
{
return _value;
}
}
public FieldInfo(string propertyName, Type fieldType, object value)
{
_propertyName = propertyName;
_fieldType = fieldType;
_value = value;
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.StateManager.HostStates.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2
{
internal partial class DiagnosticIncrementalAnalyzer
{
private partial class StateManager
{
public IEnumerable<StateSet> GetAllHostStateSets()
=> _hostAnalyzerStateMap.Values.SelectMany(v => v.OrderedStateSets);
private HostAnalyzerStateSets GetOrCreateHostStateSets(Project project, ProjectAnalyzerStateSets projectStateSets)
{
var hostStateSets = ImmutableInterlocked.GetOrAdd(ref _hostAnalyzerStateMap, project.Language, CreateLanguageSpecificAnalyzerMap, project.Solution.State.Analyzers);
return hostStateSets.WithExcludedAnalyzers(projectStateSets.SkippedAnalyzersInfo.SkippedAnalyzers);
static HostAnalyzerStateSets CreateLanguageSpecificAnalyzerMap(string language, HostDiagnosticAnalyzers hostAnalyzers)
{
var analyzersPerReference = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(language);
var analyzerMap = CreateStateSetMap(language, analyzersPerReference.Values, includeFileContentLoadAnalyzer: true);
VerifyUniqueStateNames(analyzerMap.Values);
return new HostAnalyzerStateSets(analyzerMap);
}
}
private sealed class HostAnalyzerStateSets
{
private const int FileContentLoadAnalyzerPriority = -3;
private const int BuiltInCompilerPriority = -2;
private const int RegularDiagnosticAnalyzerPriority = -1;
// ordered by priority
public readonly ImmutableArray<StateSet> OrderedStateSets;
public readonly ImmutableDictionary<DiagnosticAnalyzer, StateSet> StateSetMap;
private HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> stateSetMap, ImmutableArray<StateSet> orderedStateSets)
{
StateSetMap = stateSetMap;
OrderedStateSets = orderedStateSets;
}
public HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> analyzerMap)
{
StateSetMap = analyzerMap;
// order statesets
// order will be in this order
// BuiltIn Compiler Analyzer (C#/VB) < Regular DiagnosticAnalyzers < Document/ProjectDiagnosticAnalyzers
OrderedStateSets = StateSetMap.Values.OrderBy(PriorityComparison).ToImmutableArray();
}
public HostAnalyzerStateSets WithExcludedAnalyzers(ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers)
{
if (excludedAnalyzers.IsEmpty)
{
return this;
}
var stateSetMap = StateSetMap.Where(kvp => !excludedAnalyzers.Contains(kvp.Key)).ToImmutableDictionary();
var orderedStateSets = OrderedStateSets.WhereAsArray(stateSet => !excludedAnalyzers.Contains(stateSet.Analyzer));
return new HostAnalyzerStateSets(stateSetMap, orderedStateSets);
}
private int PriorityComparison(StateSet state1, StateSet state2)
=> GetPriority(state1) - GetPriority(state2);
private static int GetPriority(StateSet state)
{
// compiler gets highest priority
if (state.Analyzer.IsCompilerAnalyzer())
{
return BuiltInCompilerPriority;
}
return state.Analyzer switch
{
FileContentLoadAnalyzer _ => FileContentLoadAnalyzerPriority,
DocumentDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority),
ProjectDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority),
_ => RegularDiagnosticAnalyzerPriority,
};
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2
{
internal partial class DiagnosticIncrementalAnalyzer
{
private partial class StateManager
{
public IEnumerable<StateSet> GetAllHostStateSets()
=> _hostAnalyzerStateMap.Values.SelectMany(v => v.OrderedStateSets);
private HostAnalyzerStateSets GetOrCreateHostStateSets(Project project, ProjectAnalyzerStateSets projectStateSets)
{
var hostStateSets = ImmutableInterlocked.GetOrAdd(ref _hostAnalyzerStateMap, project.Language, CreateLanguageSpecificAnalyzerMap, project.Solution.State.Analyzers);
return hostStateSets.WithExcludedAnalyzers(projectStateSets.SkippedAnalyzersInfo.SkippedAnalyzers);
static HostAnalyzerStateSets CreateLanguageSpecificAnalyzerMap(string language, HostDiagnosticAnalyzers hostAnalyzers)
{
var analyzersPerReference = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(language);
var analyzerMap = CreateStateSetMap(language, analyzersPerReference.Values, includeFileContentLoadAnalyzer: true);
VerifyUniqueStateNames(analyzerMap.Values);
return new HostAnalyzerStateSets(analyzerMap);
}
}
private sealed class HostAnalyzerStateSets
{
private const int FileContentLoadAnalyzerPriority = -3;
private const int BuiltInCompilerPriority = -2;
private const int RegularDiagnosticAnalyzerPriority = -1;
// ordered by priority
public readonly ImmutableArray<StateSet> OrderedStateSets;
public readonly ImmutableDictionary<DiagnosticAnalyzer, StateSet> StateSetMap;
private HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> stateSetMap, ImmutableArray<StateSet> orderedStateSets)
{
StateSetMap = stateSetMap;
OrderedStateSets = orderedStateSets;
}
public HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> analyzerMap)
{
StateSetMap = analyzerMap;
// order statesets
// order will be in this order
// BuiltIn Compiler Analyzer (C#/VB) < Regular DiagnosticAnalyzers < Document/ProjectDiagnosticAnalyzers
OrderedStateSets = StateSetMap.Values.OrderBy(PriorityComparison).ToImmutableArray();
}
public HostAnalyzerStateSets WithExcludedAnalyzers(ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers)
{
if (excludedAnalyzers.IsEmpty)
{
return this;
}
var stateSetMap = StateSetMap.Where(kvp => !excludedAnalyzers.Contains(kvp.Key)).ToImmutableDictionary();
var orderedStateSets = OrderedStateSets.WhereAsArray(stateSet => !excludedAnalyzers.Contains(stateSet.Analyzer));
return new HostAnalyzerStateSets(stateSetMap, orderedStateSets);
}
private int PriorityComparison(StateSet state1, StateSet state2)
=> GetPriority(state1) - GetPriority(state2);
private static int GetPriority(StateSet state)
{
// compiler gets highest priority
if (state.Analyzer.IsCompilerAnalyzer())
{
return BuiltInCompilerPriority;
}
return state.Analyzer switch
{
FileContentLoadAnalyzer _ => FileContentLoadAnalyzerPriority,
DocumentDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority),
ProjectDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority),
_ => RegularDiagnosticAnalyzerPriority,
};
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/Core/Portable/CodeGeneration/CodeGenerationOperatorKind.cs | // Licensed to the .NET Foundation under one or more 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.CodeGeneration
{
internal enum CodeGenerationOperatorKind
{
Addition = 0,
BitwiseAnd = 1,
BitwiseOr = 2,
Concatenate = 3,
Decrement = 4,
Division = 5,
Equality = 6,
ExclusiveOr = 7,
Exponent = 8,
False = 9,
GreaterThan = 10,
GreaterThanOrEqual = 11,
Increment = 12,
Inequality = 13,
IntegerDivision = 14,
LeftShift = 15,
LessThan = 16,
LessThanOrEqual = 17,
Like = 18,
LogicalNot = 19,
Modulus = 20,
Multiplication = 21,
OnesComplement = 22,
RightShift = 23,
Subtraction = 24,
True = 25,
UnaryPlus = 26,
UnaryNegation = 27
}
}
| // Licensed to the .NET Foundation under one or more 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.CodeGeneration
{
internal enum CodeGenerationOperatorKind
{
Addition = 0,
BitwiseAnd = 1,
BitwiseOr = 2,
Concatenate = 3,
Decrement = 4,
Division = 5,
Equality = 6,
ExclusiveOr = 7,
Exponent = 8,
False = 9,
GreaterThan = 10,
GreaterThanOrEqual = 11,
Increment = 12,
Inequality = 13,
IntegerDivision = 14,
LeftShift = 15,
LessThan = 16,
LessThanOrEqual = 17,
Like = 18,
LogicalNot = 19,
Modulus = 20,
Multiplication = 21,
OnesComplement = 22,
RightShift = 23,
Subtraction = 24,
True = 25,
UnaryPlus = 26,
UnaryNegation = 27
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/Core/Portable/Wrapping/BinaryExpression/AbstractBinaryExpressionWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
#if DEBUG
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.Wrapping.BinaryExpression
{
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Precedence;
internal abstract partial class AbstractBinaryExpressionWrapper<TBinaryExpressionSyntax> : AbstractSyntaxWrapper
where TBinaryExpressionSyntax : SyntaxNode
{
private readonly ISyntaxFacts _syntaxFacts;
private readonly IPrecedenceService _precedenceService;
protected AbstractBinaryExpressionWrapper(
IIndentationService indentationService,
ISyntaxFacts syntaxFacts,
IPrecedenceService precedenceService) : base(indentationService)
{
_syntaxFacts = syntaxFacts;
_precedenceService = precedenceService;
}
/// <summary>
/// Get's the language specific trivia that should be inserted before an operator if the
/// user wants to wrap the operator to the next line. For C# this is a simple newline-trivia.
/// For VB, this will be a line-continuation char (<c>_</c>), followed by a newline.
/// </summary>
protected abstract SyntaxTriviaList GetNewLineBeforeOperatorTrivia(SyntaxTriviaList newLine);
public sealed override async Task<ICodeActionComputer> TryCreateComputerAsync(
Document document, int position, SyntaxNode node, CancellationToken cancellationToken)
{
if (node is not TBinaryExpressionSyntax binaryExpr)
{
return null;
}
var precedence = _precedenceService.GetPrecedenceKind(binaryExpr);
if (precedence == PrecedenceKind.Other)
{
return null;
}
// Don't process this binary expression if it's in a parent binary expr of the same or
// lower precedence. We'll just allow our caller to walk up to that and call back into
// us to handle. This way, we're always starting at the topmost binary expr of this
// precedence.
//
// for example, if we have `if (a + b == c + d)` expectation is to wrap on the lower
// precedence `==` op, not either of the `+` ops
//
// Note: we use `<=` when comparing precedence because lower precedence has a higher
// value.
if (binaryExpr.Parent is TBinaryExpressionSyntax parentBinary &&
precedence <= _precedenceService.GetPrecedenceKind(parentBinary))
{
return null;
}
var exprsAndOperators = GetExpressionsAndOperators(precedence, binaryExpr);
#if DEBUG
Debug.Assert(exprsAndOperators.Length >= 3);
Debug.Assert(exprsAndOperators.Length % 2 == 1, "Should have odd number of exprs and operators");
for (var i = 0; i < exprsAndOperators.Length; i++)
{
var item = exprsAndOperators[i];
Debug.Assert(((i % 2) == 0 && item.IsNode) ||
((i % 2) == 1 && item.IsToken));
}
#endif
var containsUnformattableContent = await ContainsUnformattableContentAsync(
document, exprsAndOperators, cancellationToken).ConfigureAwait(false);
if (containsUnformattableContent)
{
return null;
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
return new BinaryExpressionCodeActionComputer(
this, document, sourceText, options, binaryExpr,
exprsAndOperators, cancellationToken);
}
private ImmutableArray<SyntaxNodeOrToken> GetExpressionsAndOperators(
PrecedenceKind precedence, TBinaryExpressionSyntax binaryExpr)
{
using var _ = ArrayBuilder<SyntaxNodeOrToken>.GetInstance(out var result);
AddExpressionsAndOperators(precedence, binaryExpr, result);
return result.ToImmutable();
}
private void AddExpressionsAndOperators(
PrecedenceKind precedence, SyntaxNode expr, ArrayBuilder<SyntaxNodeOrToken> result)
{
if (expr is TBinaryExpressionSyntax &&
precedence == _precedenceService.GetPrecedenceKind(expr))
{
_syntaxFacts.GetPartsOfBinaryExpression(
expr, out var left, out var opToken, out var right);
AddExpressionsAndOperators(precedence, left, result);
result.Add(opToken);
AddExpressionsAndOperators(precedence, right, result);
}
else
{
result.Add(expr);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
#if DEBUG
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.Wrapping.BinaryExpression
{
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Precedence;
internal abstract partial class AbstractBinaryExpressionWrapper<TBinaryExpressionSyntax> : AbstractSyntaxWrapper
where TBinaryExpressionSyntax : SyntaxNode
{
private readonly ISyntaxFacts _syntaxFacts;
private readonly IPrecedenceService _precedenceService;
protected AbstractBinaryExpressionWrapper(
IIndentationService indentationService,
ISyntaxFacts syntaxFacts,
IPrecedenceService precedenceService) : base(indentationService)
{
_syntaxFacts = syntaxFacts;
_precedenceService = precedenceService;
}
/// <summary>
/// Get's the language specific trivia that should be inserted before an operator if the
/// user wants to wrap the operator to the next line. For C# this is a simple newline-trivia.
/// For VB, this will be a line-continuation char (<c>_</c>), followed by a newline.
/// </summary>
protected abstract SyntaxTriviaList GetNewLineBeforeOperatorTrivia(SyntaxTriviaList newLine);
public sealed override async Task<ICodeActionComputer> TryCreateComputerAsync(
Document document, int position, SyntaxNode node, CancellationToken cancellationToken)
{
if (node is not TBinaryExpressionSyntax binaryExpr)
{
return null;
}
var precedence = _precedenceService.GetPrecedenceKind(binaryExpr);
if (precedence == PrecedenceKind.Other)
{
return null;
}
// Don't process this binary expression if it's in a parent binary expr of the same or
// lower precedence. We'll just allow our caller to walk up to that and call back into
// us to handle. This way, we're always starting at the topmost binary expr of this
// precedence.
//
// for example, if we have `if (a + b == c + d)` expectation is to wrap on the lower
// precedence `==` op, not either of the `+` ops
//
// Note: we use `<=` when comparing precedence because lower precedence has a higher
// value.
if (binaryExpr.Parent is TBinaryExpressionSyntax parentBinary &&
precedence <= _precedenceService.GetPrecedenceKind(parentBinary))
{
return null;
}
var exprsAndOperators = GetExpressionsAndOperators(precedence, binaryExpr);
#if DEBUG
Debug.Assert(exprsAndOperators.Length >= 3);
Debug.Assert(exprsAndOperators.Length % 2 == 1, "Should have odd number of exprs and operators");
for (var i = 0; i < exprsAndOperators.Length; i++)
{
var item = exprsAndOperators[i];
Debug.Assert(((i % 2) == 0 && item.IsNode) ||
((i % 2) == 1 && item.IsToken));
}
#endif
var containsUnformattableContent = await ContainsUnformattableContentAsync(
document, exprsAndOperators, cancellationToken).ConfigureAwait(false);
if (containsUnformattableContent)
{
return null;
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
return new BinaryExpressionCodeActionComputer(
this, document, sourceText, options, binaryExpr,
exprsAndOperators, cancellationToken);
}
private ImmutableArray<SyntaxNodeOrToken> GetExpressionsAndOperators(
PrecedenceKind precedence, TBinaryExpressionSyntax binaryExpr)
{
using var _ = ArrayBuilder<SyntaxNodeOrToken>.GetInstance(out var result);
AddExpressionsAndOperators(precedence, binaryExpr, result);
return result.ToImmutable();
}
private void AddExpressionsAndOperators(
PrecedenceKind precedence, SyntaxNode expr, ArrayBuilder<SyntaxNodeOrToken> result)
{
if (expr is TBinaryExpressionSyntax &&
precedence == _precedenceService.GetPrecedenceKind(expr))
{
_syntaxFacts.GetPartsOfBinaryExpression(
expr, out var left, out var opToken, out var right);
AddExpressionsAndOperators(precedence, left, result);
result.Add(opToken);
AddExpressionsAndOperators(precedence, right, result);
}
else
{
result.Add(expr);
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/MSBuildTest/Resources/Issue30174/ReferencedLibrary/SomeMetadataAttribute.cs | using System;
namespace ReferencedLibrary
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class SomeMetadataAttribute : Attribute
{
}
}
| using System;
namespace ReferencedLibrary
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class SomeMetadataAttribute : Attribute
{
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/Xaml/Impl/Implementation/XamlOleCommandTarget.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
/// <summary>
/// This command target routes commands in .xaml files.
/// </summary>
internal sealed class XamlOleCommandTarget : AbstractOleCommandTarget
{
internal XamlOleCommandTarget(
IWpfTextView wpfTextView,
IComponentModel componentModel)
: base(wpfTextView, componentModel)
{
}
protected override ITextBuffer? GetSubjectBufferContainingCaret()
{
return this.WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.XamlContentType);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Xaml
{
/// <summary>
/// This command target routes commands in .xaml files.
/// </summary>
internal sealed class XamlOleCommandTarget : AbstractOleCommandTarget
{
internal XamlOleCommandTarget(
IWpfTextView wpfTextView,
IComponentModel componentModel)
: base(wpfTextView, componentModel)
{
}
protected override ITextBuffer? GetSubjectBufferContainingCaret()
{
return this.WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.XamlContentType);
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicGenerateConstructorDialog.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicGenerateConstructorDialog : AbstractEditorTest
{
private const string DialogName = "PickMembersDialog";
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicGenerateConstructorDialog(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicGenerateConstructorDialog))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyCodeRefactoringOfferedAndCanceled()
{
SetUpEditor(@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
Dialog_ClickCancel();
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
End Class", actualText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyCodeRefactoringOfferedAndAccepted()
{
SetUpEditor(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
Dialog_ClickOk();
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
Public Sub New(i As Integer, j As String, k As Boolean)
Me.i = i
Me.j = j
Me.k = k
End Sub
End Class", actualText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyReordering()
{
SetUpEditor(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.PressDialogButton(DialogName, "Down");
Dialog_ClickOk();
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
Public Sub New(j As String, i As Integer, k As Boolean)
Me.j = j
Me.i = i
Me.k = k
End Sub
End Class", actualText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyDeselect()
{
SetUpEditor(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Space);
Dialog_ClickOk();
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
Public Sub New(j As String, k As Boolean)
Me.j = j
Me.k = k
End Sub
End Class", actualText);
}
private void VerifyDialog(bool isOpen)
=> VisualStudio.Editor.Verify.Dialog(DialogName, isOpen);
private void Dialog_ClickCancel()
=> VisualStudio.Editor.PressDialogButton(DialogName, "CancelButton");
private void Dialog_ClickOk()
=> VisualStudio.Editor.PressDialogButton(DialogName, "OkButton");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicGenerateConstructorDialog : AbstractEditorTest
{
private const string DialogName = "PickMembersDialog";
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicGenerateConstructorDialog(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicGenerateConstructorDialog))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyCodeRefactoringOfferedAndCanceled()
{
SetUpEditor(@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
Dialog_ClickCancel();
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
End Class", actualText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyCodeRefactoringOfferedAndAccepted()
{
SetUpEditor(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
Dialog_ClickOk();
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
Public Sub New(i As Integer, j As String, k As Boolean)
Me.i = i
Me.j = j
Me.k = k
End Sub
End Class", actualText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyReordering()
{
SetUpEditor(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.PressDialogButton(DialogName, "Down");
Dialog_ClickOk();
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
Public Sub New(j As String, i As Integer, k As Boolean)
Me.j = j
Me.i = i
Me.k = k
End Sub
End Class", actualText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public void VerifyDeselect()
{
SetUpEditor(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
$$
End Class");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false);
VerifyDialog(isOpen: true);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab);
VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Space);
Dialog_ClickOk();
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb);
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(
@"
Class C
Dim i as Integer
Dim j as String
Dim k as Boolean
Public Sub New(j As String, k As Boolean)
Me.j = j
Me.k = k
End Sub
End Class", actualText);
}
private void VerifyDialog(bool isOpen)
=> VisualStudio.Editor.Verify.Dialog(DialogName, isOpen);
private void Dialog_ClickCancel()
=> VisualStudio.Editor.PressDialogButton(DialogName, "CancelButton");
private void Dialog_ClickOk()
=> VisualStudio.Editor.PressDialogButton(DialogName, "OkButton");
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractReferenceFinder_GlobalSuppressions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal abstract partial class AbstractReferenceFinder : IReferenceFinder
{
private static bool ShouldFindReferencesInGlobalSuppressions(ISymbol symbol, [NotNullWhen(returnValue: true)] out string? documentationCommentId)
{
if (!SupportsGlobalSuppression(symbol))
{
documentationCommentId = null;
return false;
}
documentationCommentId = DocumentationCommentId.CreateDeclarationId(symbol);
return documentationCommentId != null;
// Global suppressions are currently supported for types, members and
// namespaces, except global namespace.
static bool SupportsGlobalSuppression(ISymbol symbol)
=> symbol.Kind switch
{
SymbolKind.Namespace => !((INamespaceSymbol)symbol).IsGlobalNamespace,
SymbolKind.NamedType => true,
SymbolKind.Method => true,
SymbolKind.Field => true,
SymbolKind.Property => true,
SymbolKind.Event => true,
_ => false,
};
}
/// <summary>
/// Find references to a symbol inside global suppressions.
/// For example, consider a field 'Field' defined inside a type 'C'.
/// This field's documentation comment ID is 'F:C.Field'
/// A reference to this field inside a global suppression would be as following:
/// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "~F:C.Field")]
/// </summary>
[PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)]
protected static async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentInsideGlobalSuppressionsAsync(
Document document,
SemanticModel semanticModel,
ISymbol symbol,
CancellationToken cancellationToken)
{
if (!ShouldFindReferencesInGlobalSuppressions(symbol, out var docCommentId))
return ImmutableArray<FinderLocation>.Empty;
// Check if we have any relevant global attributes in this document.
var info = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false);
if (!info.ContainsGlobalAttributes)
return ImmutableArray<FinderLocation>.Empty;
var suppressMessageAttribute = semanticModel.Compilation.SuppressMessageAttributeType();
if (suppressMessageAttribute == null)
return ImmutableArray<FinderLocation>.Empty;
// Check if we have any instances of the symbol documentation comment ID string literals within global attributes.
// These string literals represent references to the symbol.
if (!TryGetExpectedDocumentationCommentId(docCommentId, out var expectedDocCommentId))
return ImmutableArray<FinderLocation>.Empty;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// We map the positions of documentation ID literals in tree to string literal tokens,
// perform semantic checks to ensure these are valid references to the symbol
// and if so, add these locations to the computed references.
var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<FinderLocation>.GetInstance(out var locations);
foreach (var token in root.DescendantTokens())
{
if (IsCandidate(token, expectedDocCommentId.Span, semanticModel, syntaxFacts, suppressMessageAttribute, cancellationToken, out var offsetOfReferenceInToken))
{
var referenceLocation = CreateReferenceLocation(offsetOfReferenceInToken, token, root, document, syntaxFacts);
locations.Add(new FinderLocation(token.GetRequiredParent(), referenceLocation));
}
}
return locations.ToImmutable();
// Local functions
static bool IsCandidate(
SyntaxToken token, ReadOnlySpan<char> expectedDocCommentId, SemanticModel semanticModel, ISyntaxFacts syntaxFacts,
INamedTypeSymbol suppressMessageAttribute, CancellationToken cancellationToken, out int offsetOfReferenceInToken)
{
offsetOfReferenceInToken = -1;
// Check if this token is a named attribute argument to "Target" property of "SuppressMessageAttribute".
if (!IsValidTargetOfGlobalSuppressionAttribute(token, suppressMessageAttribute, semanticModel, syntaxFacts, cancellationToken))
{
return false;
}
// Target string must contain a valid symbol DocumentationCommentId.
if (!ValidateAndSplitDocumentationCommentId(token.ValueText, out var prefix, out var docCommentId))
{
return false;
}
// We have couple of success cases:
// 1. The FAR symbol is the same one as the target of the suppression. In this case,
// target string for the suppression exactly matches the expectedDocCommentId.
// 2. The FAR symbol is one of the containing symbols of the target symbol of suppression.
// In this case, the target string for the suppression starts with the expectedDocCommentId.
//
// For example, consider the below suppression applied to field 'Field' of type 'C'
// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "~F:C.Field")]
// When doing a FAR query on 'Field', we would return true from case 1.
// When doing a FAR query on 'C', we would return true from case 2.
if (!docCommentId.Span.StartsWith(expectedDocCommentId))
{
return false;
}
// We found a match, now compute the offset of the reference within the string literal token.
offsetOfReferenceInToken = prefix.Length;
if (expectedDocCommentId.Length < docCommentId.Length)
{
// Expected doc comment ID belongs to a containing symbol of the symbol referenced in suppression's target doc comment ID.
// Verify the next character in suppression doc comment ID is the '.' separator for its member.
if (docCommentId.Span[expectedDocCommentId.Length] != '.')
return false;
offsetOfReferenceInToken += expectedDocCommentId.LastIndexOf('.') + 1;
}
else
{
// Expected doc comment ID matches the suppression's target doc comment ID.
SplitIdAndArguments(docCommentId, out var idPartBeforeArguments, out var _);
offsetOfReferenceInToken += idPartBeforeArguments.Span.LastIndexOf('.') + 1;
}
return true;
}
static bool IsValidTargetOfGlobalSuppressionAttribute(
SyntaxToken token,
INamedTypeSymbol suppressMessageAttribute,
SemanticModel semanticModel,
ISyntaxFacts syntaxFacts,
CancellationToken cancellationToken)
{
// We need to check if the given token is a non-null, non-empty string literal token
// passed as a named argument to 'Target' property of a global SuppressMessageAttribute.
//
// For example, consider the below global suppression.
// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "F:C.Field")]
//
// We return true when processing "F:C.Field".
if (!syntaxFacts.IsStringLiteral(token))
{
return false;
}
var text = token.ValueText;
if (string.IsNullOrEmpty(text))
{
return false;
}
// We need to go from string literal token "F:C.Field" to the suppression attribute node.
// AttributeSyntax
// -> AttributeArgumentList
// -> AttributeArgument
// -> StringLiteralExpression
// -> StringLiteralToken
var attributeArgument = token.Parent?.Parent;
if (syntaxFacts.GetNameForAttributeArgument(attributeArgument) != "Target")
{
return false;
}
var attributeNode = attributeArgument!.Parent?.Parent;
if (attributeNode == null || !syntaxFacts.IsGlobalAttribute(attributeNode))
{
return false;
}
// Check the attribute type matches 'SuppressMessageAttribute'.
var attributeSymbol = semanticModel.GetSymbolInfo(attributeNode, cancellationToken).Symbol?.ContainingType;
return suppressMessageAttribute.Equals(attributeSymbol);
}
static ReferenceLocation CreateReferenceLocation(
int offsetOfReferenceInToken,
SyntaxToken token,
SyntaxNode root,
Document document,
ISyntaxFacts syntaxFacts)
{
// We found a valid reference to the symbol in documentation comment ID string literal.
// Compute the reference span within this string literal for the identifier.
// For example, consider the suppression below for field 'Field' defined in type 'C':
// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "F:C.Field")]
// We compute the span for 'Field' within the target string literal.
// NOTE: '#' is also a valid char in documentation comment ID. For example, '#ctor' and '#cctor'.
var positionOfReferenceInTree = token.SpanStart + offsetOfReferenceInToken + 1;
var valueText = token.ValueText;
var length = 0;
while (offsetOfReferenceInToken < valueText.Length)
{
var ch = valueText[offsetOfReferenceInToken++];
if (ch == '#' || syntaxFacts.IsIdentifierPartCharacter(ch))
length++;
else
break;
}
// We create a reference location of the identifier span within this string literal
// that represents the symbol reference.
// We also add the location for the containing documentation comment ID string literal.
// For the suppression example above, location points to the span of 'Field' inside "F:C.Field"
// and containing string location points to the span of the entire string literal "F:C.Field".
var location = Location.Create(root.SyntaxTree, new TextSpan(positionOfReferenceInTree, length));
var containingStringLocation = token.GetLocation();
return new ReferenceLocation(document, location, containingStringLocation);
}
}
private static bool TryGetExpectedDocumentationCommentId(
string id,
out ReadOnlyMemory<char> docCommentId)
{
return ValidateAndSplitDocumentationCommentId(id, out _, out docCommentId);
}
/// <summary>
/// Validate and split a documentation comment ID into a prefix and complete symbol ID. For the
/// <paramref name="docCommentId"/> <c>~M:C.X(System.String)</c>, the <paramref name="prefix"/> would be
/// <c>~M:</c> and <paramref name="id"/> would be <c>C.X(System.String)</c>.
/// </summary>
[PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", Constraint = "Avoid Regex splitting due to high allocation costs.")]
private static bool ValidateAndSplitDocumentationCommentId(
[NotNullWhen(true)] string? docCommentId,
out ReadOnlyMemory<char> prefix,
out ReadOnlyMemory<char> id)
{
prefix = ReadOnlyMemory<char>.Empty;
id = ReadOnlyMemory<char>.Empty;
if (docCommentId is null)
{
return false;
}
// Parse the prefix
if (docCommentId.StartsWith("~"))
{
if (docCommentId.Length < 3)
return false;
prefix = docCommentId.AsMemory()[0..3];
}
else
{
if (docCommentId.Length < 2)
return false;
prefix = docCommentId.AsMemory()[0..2];
}
if (prefix.Span[^2] is < 'A' or > 'Z')
{
return false;
}
if (prefix.Span[^1] is not ':')
{
return false;
}
// The rest of the ID is returned without splitting
id = docCommentId.AsMemory()[prefix.Length..];
return true;
}
/// <summary>
/// Split a full documentation symbol ID into the core symbol ID and optional parameter list. For the
/// <paramref name="id"/> <c>C.X(System.String)</c>, the <paramref name="idPartBeforeArguments"/> would be
/// <c>C.X</c> and <paramref name="arguments"/> would be <c>(System.String)</c>.
/// </summary>
private static void SplitIdAndArguments(
ReadOnlyMemory<char> id,
out ReadOnlyMemory<char> idPartBeforeArguments,
out ReadOnlyMemory<char> arguments)
{
ReadOnlySpan<char> argumentSeparators = stackalloc[] { '(', '[' };
var indexOfArguments = id.Span.IndexOfAny(argumentSeparators);
if (indexOfArguments < 0)
{
idPartBeforeArguments = id;
arguments = ReadOnlyMemory<char>.Empty;
}
else
{
idPartBeforeArguments = id[0..indexOfArguments];
arguments = id[indexOfArguments..];
}
}
/// <summary>
/// Validate and split symbol documentation comment ID.
/// For example, "~M:C.X(System.String)" represents the documentation comment ID of a method named 'X'
/// that takes a single string-typed parameter and is contained in a type named 'C'.
///
/// We divide the ID into 3 groups:
/// 1. Prefix:
/// - Starts with an optional '~'
/// - Followed by a single capital letter indicating the symbol kind (for example, 'M' indicates method symbol)
/// - Followed by ':'
/// 2. Core symbol ID, which is its fully qualified name before the optional parameter list and return type (i.e. before the '(' or '[' tokens)
/// 3. Optional parameter list and/or return type that begins with a '(' or '[' tokens.
///
/// For the above example, "~M:" is the prefix, "C.X" is the core symbol ID and "(System.String)" is the parameter list.
/// </summary>
private static bool ValidateAndSplitDocumentationCommentId(
[NotNullWhen(true)] string? docCommentId,
out ReadOnlyMemory<char> prefix,
out ReadOnlyMemory<char> idPartBeforeArguments,
out ReadOnlyMemory<char> arguments)
{
idPartBeforeArguments = ReadOnlyMemory<char>.Empty;
arguments = ReadOnlyMemory<char>.Empty;
if (!ValidateAndSplitDocumentationCommentId(docCommentId, out prefix, out var id))
{
return false;
}
// Parse the id part and arguments
SplitIdAndArguments(id, out idPartBeforeArguments, out arguments);
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal abstract partial class AbstractReferenceFinder : IReferenceFinder
{
private static bool ShouldFindReferencesInGlobalSuppressions(ISymbol symbol, [NotNullWhen(returnValue: true)] out string? documentationCommentId)
{
if (!SupportsGlobalSuppression(symbol))
{
documentationCommentId = null;
return false;
}
documentationCommentId = DocumentationCommentId.CreateDeclarationId(symbol);
return documentationCommentId != null;
// Global suppressions are currently supported for types, members and
// namespaces, except global namespace.
static bool SupportsGlobalSuppression(ISymbol symbol)
=> symbol.Kind switch
{
SymbolKind.Namespace => !((INamespaceSymbol)symbol).IsGlobalNamespace,
SymbolKind.NamedType => true,
SymbolKind.Method => true,
SymbolKind.Field => true,
SymbolKind.Property => true,
SymbolKind.Event => true,
_ => false,
};
}
/// <summary>
/// Find references to a symbol inside global suppressions.
/// For example, consider a field 'Field' defined inside a type 'C'.
/// This field's documentation comment ID is 'F:C.Field'
/// A reference to this field inside a global suppression would be as following:
/// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "~F:C.Field")]
/// </summary>
[PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)]
protected static async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentInsideGlobalSuppressionsAsync(
Document document,
SemanticModel semanticModel,
ISymbol symbol,
CancellationToken cancellationToken)
{
if (!ShouldFindReferencesInGlobalSuppressions(symbol, out var docCommentId))
return ImmutableArray<FinderLocation>.Empty;
// Check if we have any relevant global attributes in this document.
var info = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false);
if (!info.ContainsGlobalAttributes)
return ImmutableArray<FinderLocation>.Empty;
var suppressMessageAttribute = semanticModel.Compilation.SuppressMessageAttributeType();
if (suppressMessageAttribute == null)
return ImmutableArray<FinderLocation>.Empty;
// Check if we have any instances of the symbol documentation comment ID string literals within global attributes.
// These string literals represent references to the symbol.
if (!TryGetExpectedDocumentationCommentId(docCommentId, out var expectedDocCommentId))
return ImmutableArray<FinderLocation>.Empty;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// We map the positions of documentation ID literals in tree to string literal tokens,
// perform semantic checks to ensure these are valid references to the symbol
// and if so, add these locations to the computed references.
var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<FinderLocation>.GetInstance(out var locations);
foreach (var token in root.DescendantTokens())
{
if (IsCandidate(token, expectedDocCommentId.Span, semanticModel, syntaxFacts, suppressMessageAttribute, cancellationToken, out var offsetOfReferenceInToken))
{
var referenceLocation = CreateReferenceLocation(offsetOfReferenceInToken, token, root, document, syntaxFacts);
locations.Add(new FinderLocation(token.GetRequiredParent(), referenceLocation));
}
}
return locations.ToImmutable();
// Local functions
static bool IsCandidate(
SyntaxToken token, ReadOnlySpan<char> expectedDocCommentId, SemanticModel semanticModel, ISyntaxFacts syntaxFacts,
INamedTypeSymbol suppressMessageAttribute, CancellationToken cancellationToken, out int offsetOfReferenceInToken)
{
offsetOfReferenceInToken = -1;
// Check if this token is a named attribute argument to "Target" property of "SuppressMessageAttribute".
if (!IsValidTargetOfGlobalSuppressionAttribute(token, suppressMessageAttribute, semanticModel, syntaxFacts, cancellationToken))
{
return false;
}
// Target string must contain a valid symbol DocumentationCommentId.
if (!ValidateAndSplitDocumentationCommentId(token.ValueText, out var prefix, out var docCommentId))
{
return false;
}
// We have couple of success cases:
// 1. The FAR symbol is the same one as the target of the suppression. In this case,
// target string for the suppression exactly matches the expectedDocCommentId.
// 2. The FAR symbol is one of the containing symbols of the target symbol of suppression.
// In this case, the target string for the suppression starts with the expectedDocCommentId.
//
// For example, consider the below suppression applied to field 'Field' of type 'C'
// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "~F:C.Field")]
// When doing a FAR query on 'Field', we would return true from case 1.
// When doing a FAR query on 'C', we would return true from case 2.
if (!docCommentId.Span.StartsWith(expectedDocCommentId))
{
return false;
}
// We found a match, now compute the offset of the reference within the string literal token.
offsetOfReferenceInToken = prefix.Length;
if (expectedDocCommentId.Length < docCommentId.Length)
{
// Expected doc comment ID belongs to a containing symbol of the symbol referenced in suppression's target doc comment ID.
// Verify the next character in suppression doc comment ID is the '.' separator for its member.
if (docCommentId.Span[expectedDocCommentId.Length] != '.')
return false;
offsetOfReferenceInToken += expectedDocCommentId.LastIndexOf('.') + 1;
}
else
{
// Expected doc comment ID matches the suppression's target doc comment ID.
SplitIdAndArguments(docCommentId, out var idPartBeforeArguments, out var _);
offsetOfReferenceInToken += idPartBeforeArguments.Span.LastIndexOf('.') + 1;
}
return true;
}
static bool IsValidTargetOfGlobalSuppressionAttribute(
SyntaxToken token,
INamedTypeSymbol suppressMessageAttribute,
SemanticModel semanticModel,
ISyntaxFacts syntaxFacts,
CancellationToken cancellationToken)
{
// We need to check if the given token is a non-null, non-empty string literal token
// passed as a named argument to 'Target' property of a global SuppressMessageAttribute.
//
// For example, consider the below global suppression.
// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "F:C.Field")]
//
// We return true when processing "F:C.Field".
if (!syntaxFacts.IsStringLiteral(token))
{
return false;
}
var text = token.ValueText;
if (string.IsNullOrEmpty(text))
{
return false;
}
// We need to go from string literal token "F:C.Field" to the suppression attribute node.
// AttributeSyntax
// -> AttributeArgumentList
// -> AttributeArgument
// -> StringLiteralExpression
// -> StringLiteralToken
var attributeArgument = token.Parent?.Parent;
if (syntaxFacts.GetNameForAttributeArgument(attributeArgument) != "Target")
{
return false;
}
var attributeNode = attributeArgument!.Parent?.Parent;
if (attributeNode == null || !syntaxFacts.IsGlobalAttribute(attributeNode))
{
return false;
}
// Check the attribute type matches 'SuppressMessageAttribute'.
var attributeSymbol = semanticModel.GetSymbolInfo(attributeNode, cancellationToken).Symbol?.ContainingType;
return suppressMessageAttribute.Equals(attributeSymbol);
}
static ReferenceLocation CreateReferenceLocation(
int offsetOfReferenceInToken,
SyntaxToken token,
SyntaxNode root,
Document document,
ISyntaxFacts syntaxFacts)
{
// We found a valid reference to the symbol in documentation comment ID string literal.
// Compute the reference span within this string literal for the identifier.
// For example, consider the suppression below for field 'Field' defined in type 'C':
// [assembly: SuppressMessage("RuleCategory", "RuleId', Scope = "member", Target = "F:C.Field")]
// We compute the span for 'Field' within the target string literal.
// NOTE: '#' is also a valid char in documentation comment ID. For example, '#ctor' and '#cctor'.
var positionOfReferenceInTree = token.SpanStart + offsetOfReferenceInToken + 1;
var valueText = token.ValueText;
var length = 0;
while (offsetOfReferenceInToken < valueText.Length)
{
var ch = valueText[offsetOfReferenceInToken++];
if (ch == '#' || syntaxFacts.IsIdentifierPartCharacter(ch))
length++;
else
break;
}
// We create a reference location of the identifier span within this string literal
// that represents the symbol reference.
// We also add the location for the containing documentation comment ID string literal.
// For the suppression example above, location points to the span of 'Field' inside "F:C.Field"
// and containing string location points to the span of the entire string literal "F:C.Field".
var location = Location.Create(root.SyntaxTree, new TextSpan(positionOfReferenceInTree, length));
var containingStringLocation = token.GetLocation();
return new ReferenceLocation(document, location, containingStringLocation);
}
}
private static bool TryGetExpectedDocumentationCommentId(
string id,
out ReadOnlyMemory<char> docCommentId)
{
return ValidateAndSplitDocumentationCommentId(id, out _, out docCommentId);
}
/// <summary>
/// Validate and split a documentation comment ID into a prefix and complete symbol ID. For the
/// <paramref name="docCommentId"/> <c>~M:C.X(System.String)</c>, the <paramref name="prefix"/> would be
/// <c>~M:</c> and <paramref name="id"/> would be <c>C.X(System.String)</c>.
/// </summary>
[PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", Constraint = "Avoid Regex splitting due to high allocation costs.")]
private static bool ValidateAndSplitDocumentationCommentId(
[NotNullWhen(true)] string? docCommentId,
out ReadOnlyMemory<char> prefix,
out ReadOnlyMemory<char> id)
{
prefix = ReadOnlyMemory<char>.Empty;
id = ReadOnlyMemory<char>.Empty;
if (docCommentId is null)
{
return false;
}
// Parse the prefix
if (docCommentId.StartsWith("~"))
{
if (docCommentId.Length < 3)
return false;
prefix = docCommentId.AsMemory()[0..3];
}
else
{
if (docCommentId.Length < 2)
return false;
prefix = docCommentId.AsMemory()[0..2];
}
if (prefix.Span[^2] is < 'A' or > 'Z')
{
return false;
}
if (prefix.Span[^1] is not ':')
{
return false;
}
// The rest of the ID is returned without splitting
id = docCommentId.AsMemory()[prefix.Length..];
return true;
}
/// <summary>
/// Split a full documentation symbol ID into the core symbol ID and optional parameter list. For the
/// <paramref name="id"/> <c>C.X(System.String)</c>, the <paramref name="idPartBeforeArguments"/> would be
/// <c>C.X</c> and <paramref name="arguments"/> would be <c>(System.String)</c>.
/// </summary>
private static void SplitIdAndArguments(
ReadOnlyMemory<char> id,
out ReadOnlyMemory<char> idPartBeforeArguments,
out ReadOnlyMemory<char> arguments)
{
ReadOnlySpan<char> argumentSeparators = stackalloc[] { '(', '[' };
var indexOfArguments = id.Span.IndexOfAny(argumentSeparators);
if (indexOfArguments < 0)
{
idPartBeforeArguments = id;
arguments = ReadOnlyMemory<char>.Empty;
}
else
{
idPartBeforeArguments = id[0..indexOfArguments];
arguments = id[indexOfArguments..];
}
}
/// <summary>
/// Validate and split symbol documentation comment ID.
/// For example, "~M:C.X(System.String)" represents the documentation comment ID of a method named 'X'
/// that takes a single string-typed parameter and is contained in a type named 'C'.
///
/// We divide the ID into 3 groups:
/// 1. Prefix:
/// - Starts with an optional '~'
/// - Followed by a single capital letter indicating the symbol kind (for example, 'M' indicates method symbol)
/// - Followed by ':'
/// 2. Core symbol ID, which is its fully qualified name before the optional parameter list and return type (i.e. before the '(' or '[' tokens)
/// 3. Optional parameter list and/or return type that begins with a '(' or '[' tokens.
///
/// For the above example, "~M:" is the prefix, "C.X" is the core symbol ID and "(System.String)" is the parameter list.
/// </summary>
private static bool ValidateAndSplitDocumentationCommentId(
[NotNullWhen(true)] string? docCommentId,
out ReadOnlyMemory<char> prefix,
out ReadOnlyMemory<char> idPartBeforeArguments,
out ReadOnlyMemory<char> arguments)
{
idPartBeforeArguments = ReadOnlyMemory<char>.Empty;
arguments = ReadOnlyMemory<char>.Empty;
if (!ValidateAndSplitDocumentationCommentId(docCommentId, out prefix, out var id))
{
return false;
}
// Parse the id part and arguments
SplitIdAndArguments(id, out idPartBeforeArguments, out arguments);
return true;
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/Core/Portable/PEWriter/AssemblyReferenceAlias.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Roslyn.Utilities;
namespace Microsoft.Cci
{
/// <summary>
/// Represents an assembly reference with an alias (C# only, /r:Name=Reference on command line).
/// </summary>
internal struct AssemblyReferenceAlias
{
/// <summary>
/// An alias for the global namespace of the assembly.
/// </summary>
public readonly string Name;
/// <summary>
/// The assembly reference.
/// </summary>
public readonly IAssemblyReference Assembly;
internal AssemblyReferenceAlias(string name, IAssemblyReference assembly)
{
RoslynDebug.Assert(name != null);
RoslynDebug.Assert(assembly != null);
Name = name;
Assembly = assembly;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Roslyn.Utilities;
namespace Microsoft.Cci
{
/// <summary>
/// Represents an assembly reference with an alias (C# only, /r:Name=Reference on command line).
/// </summary>
internal struct AssemblyReferenceAlias
{
/// <summary>
/// An alias for the global namespace of the assembly.
/// </summary>
public readonly string Name;
/// <summary>
/// The assembly reference.
/// </summary>
public readonly IAssemblyReference Assembly;
internal AssemblyReferenceAlias(string name, IAssemblyReference assembly)
{
RoslynDebug.Assert(name != null);
RoslynDebug.Assert(assembly != null);
Name = name;
Assembly = assembly;
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/ExpressionEvaluator/Core/Source/ResultProvider/ResultProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal delegate void CompletionRoutine();
internal delegate void CompletionRoutine<TResult>(TResult result);
/// <summary>
/// Computes expansion of <see cref="DkmClrValue"/> instances.
/// </summary>
/// <remarks>
/// This class provides implementation for the default ResultProvider component.
/// </remarks>
public abstract class ResultProvider : IDkmClrResultProvider
{
// TODO: There is a potential that these values will conflict with debugger defined flags in future.
// It'd be better if we attached these flags to the DkmClrValue object via data items, however DkmClrValue is currently mutable
// and we can't clone it -- in some cases we might need to attach different flags in different code paths and it wouldn't be possible
// to do so due to mutability.
// See https://github.com/dotnet/roslyn/issues/55676.
internal const DkmEvaluationFlags NotRoot = (DkmEvaluationFlags)(1 << 30);
internal const DkmEvaluationFlags NoResults = (DkmEvaluationFlags)(1 << 31);
// Fields should be removed and replaced with calls through DkmInspectionContext.
// (see https://github.com/dotnet/roslyn/issues/6899).
internal readonly IDkmClrFormatter2 Formatter2;
internal readonly IDkmClrFullNameProvider FullNameProvider;
static ResultProvider()
{
FatalError.Handler = FailFast.OnFatalException;
}
internal ResultProvider(IDkmClrFormatter2 formatter2, IDkmClrFullNameProvider fullNameProvider)
{
Formatter2 = formatter2;
FullNameProvider = fullNameProvider;
}
internal abstract string StaticMembersString { get; }
internal abstract bool IsPrimitiveType(Type type);
void IDkmClrResultProvider.GetResult(DkmClrValue value, DkmWorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers, string resultName, string resultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine)
{
if (formatSpecifiers == null)
{
formatSpecifiers = Formatter.NoFormatSpecifiers;
}
if (resultFullName != null)
{
ReadOnlyCollection<string> otherSpecifiers;
resultFullName = FullNameProvider.GetClrExpressionAndFormatSpecifiers(inspectionContext, resultFullName, out otherSpecifiers);
foreach (var formatSpecifier in otherSpecifiers)
{
formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, formatSpecifier);
}
}
var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationAsyncResult.CreateErrorResult(e)));
wl.ContinueWith(
() => GetRootResultAndContinue(
value,
wl,
declaredType,
declaredTypeInfo,
inspectionContext,
resultName,
resultFullName,
formatSpecifiers,
result => wl.ContinueWith(() => completionRoutine(new DkmEvaluationAsyncResult(result)))));
}
DkmClrValue IDkmClrResultProvider.GetClrValue(DkmSuccessEvaluationResult evaluationResult)
{
try
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
return evaluationResult.GetClrValue();
}
return dataItem.Value;
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrResultProvider.GetChildren(DkmEvaluationResult evaluationResult, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine)
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
evaluationResult.GetChildren(workList, initialRequestSize, inspectionContext, completionRoutine);
return;
}
var expansion = dataItem.Expansion;
if (expansion == null)
{
var enumContext = DkmEvaluationResultEnumContext.Create(0, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult));
completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], enumContext));
return;
}
// Evaluate children with InspectionContext that is not the root.
inspectionContext = inspectionContext.With(NotRoot);
var rows = ArrayBuilder<EvalResult>.GetInstance();
int index = 0;
expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, 0, initialRequestSize, visitAll: true, index: ref index);
var numRows = rows.Count;
Debug.Assert(index >= numRows);
Debug.Assert(initialRequestSize >= numRows);
var initialChildren = new DkmEvaluationResult[numRows];
void onException(Exception e) => completionRoutine(DkmGetChildrenAsyncResult.CreateErrorResult(e));
var wl = new WorkList(workList, onException);
wl.ContinueWith(() =>
GetEvaluationResultsAndContinue(evaluationResult, rows, initialChildren, 0, numRows, wl, inspectionContext,
() =>
wl.ContinueWith(
() =>
{
var enumContext = DkmEvaluationResultEnumContext.Create(index, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult));
completionRoutine(new DkmGetChildrenAsyncResult(initialChildren, enumContext));
rows.Free();
}),
onException));
}
void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine)
{
var enumContextDataItem = enumContext.GetDataItem<EnumContextDataItem>();
if (enumContextDataItem == null)
{
// We don't know about this result. Call next implementation
enumContext.GetItems(workList, startIndex, count, completionRoutine);
return;
}
var evaluationResult = enumContextDataItem.Result;
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
var expansion = dataItem.Expansion;
if (expansion == null)
{
completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0]));
return;
}
var inspectionContext = enumContext.InspectionContext;
var rows = ArrayBuilder<EvalResult>.GetInstance();
int index = 0;
expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, startIndex, count, visitAll: false, index: ref index);
var numRows = rows.Count;
Debug.Assert(count >= numRows);
var results = new DkmEvaluationResult[numRows];
void onException(Exception e) => completionRoutine(DkmEvaluationEnumAsyncResult.CreateErrorResult(e));
var wl = new WorkList(workList, onException);
wl.ContinueWith(() =>
GetEvaluationResultsAndContinue(evaluationResult, rows, results, 0, numRows, wl, inspectionContext,
() =>
wl.ContinueWith(
() =>
{
completionRoutine(new DkmEvaluationEnumAsyncResult(results));
rows.Free();
}),
onException));
}
string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result)
{
try
{
var dataItem = result.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
return result.GetUnderlyingString();
}
return dataItem.Value?.GetUnderlyingString(result.InspectionContext);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void GetChild(
DkmEvaluationResult parent,
WorkList workList,
EvalResult row,
DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine)
{
var inspectionContext = row.InspectionContext;
if ((row.Kind != ExpansionKind.Default) || (row.Value == null))
{
CreateEvaluationResultAndContinue(
row,
workList,
row.InspectionContext,
parent.StackFrame,
child => completionRoutine(new DkmEvaluationAsyncResult(child)));
}
else
{
var typeDeclaringMember = row.TypeDeclaringMemberAndInfo;
var name = (typeDeclaringMember.Type == null) ?
row.Name :
GetQualifiedMemberName(row.InspectionContext, typeDeclaringMember, row.Name, FullNameProvider);
row.Value.SetDataItem(DkmDataCreationDisposition.CreateAlways, new FavoritesDataItem(row.CanFavorite, row.IsFavorite));
row.Value.GetResult(
workList.InnerWorkList,
row.DeclaredTypeAndInfo.ClrType,
row.DeclaredTypeAndInfo.Info,
row.InspectionContext,
Formatter.NoFormatSpecifiers,
name,
row.FullName,
result => workList.ContinueWith(() => completionRoutine(result)));
}
}
private void CreateEvaluationResultAndContinue(EvalResult result, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
switch (result.Kind)
{
case ExpansionKind.Explicit:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: result.DisplayName,
FullName: result.FullName,
Flags: result.Flags,
Value: result.DisplayValue,
EditableValue: result.EditableValue,
Type: result.DisplayType,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.Error:
completionRoutine(DkmFailedEvaluationResult.Create(
inspectionContext,
StackFrame: stackFrame,
Name: result.Name,
FullName: result.FullName,
ErrorMessage: result.DisplayValue,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null));
break;
case ExpansionKind.NativeView:
{
var value = result.Value;
var name = Resources.NativeView;
var fullName = result.FullName;
var display = result.Name;
DkmEvaluationResult evalResult;
if (value.IsError())
{
evalResult = DkmFailedEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
ErrorMessage: display,
Flags: result.Flags,
Type: null,
DataItem: result.ToDataItem());
}
else
{
// For Native View, create a DkmIntermediateEvaluationResult.
// This will allow the C++ EE to take over expansion.
var process = inspectionContext.RuntimeInstance.Process;
var cpp = process.EngineSettings.GetLanguage(new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp));
evalResult = DkmIntermediateEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
Expression: display,
IntermediateLanguage: cpp,
TargetRuntime: process.GetNativeRuntimeInstance(),
DataItem: result.ToDataItem());
}
completionRoutine(evalResult);
}
break;
case ExpansionKind.NonPublicMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.NonPublicMembers,
FullName: result.FullName,
Flags: result.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.StaticMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: StaticMembersString,
FullName: result.FullName,
Flags: result.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Class,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.RawView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.RawView,
FullName: result.FullName,
Flags: result.Flags,
Value: null,
EditableValue: result.EditableValue,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.DynamicView:
case ExpansionKind.ResultsView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
result.Name,
result.FullName,
result.Flags,
result.DisplayValue,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Method,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.TypeVariable:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
result.Name,
result.FullName,
result.Flags,
result.DisplayValue,
EditableValue: null,
Type: result.DisplayValue,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.PointerDereference:
case ExpansionKind.Default:
// This call will evaluate DebuggerDisplayAttributes.
GetResultAndContinue(
result,
workList,
declaredType: result.DeclaredTypeAndInfo.ClrType,
declaredTypeInfo: result.DeclaredTypeAndInfo.Info,
inspectionContext: inspectionContext,
useDebuggerDisplay: result.UseDebuggerDisplay,
completionRoutine: completionRoutine);
break;
default:
throw ExceptionUtilities.UnexpectedValue(result.Kind);
}
}
private static DkmEvaluationResult CreateEvaluationResult(
DkmInspectionContext inspectionContext,
DkmClrValue value,
string name,
string typeName,
string display,
EvalResult result)
{
if (value.IsError())
{
// Evaluation failed
return DkmFailedEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: result.FullName,
ErrorMessage: display,
Flags: result.Flags,
Type: typeName,
DataItem: result.ToDataItem());
}
else
{
ReadOnlyCollection<DkmCustomUIVisualizerInfo> customUIVisualizers = null;
if (!value.IsNull)
{
DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = value.Type.GetDebuggerCustomUIVisualizerInfo();
if (customUIVisualizerInfo != null)
{
customUIVisualizers = new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo);
}
}
// If the EvalResultDataItem doesn't specify a particular category, we'll just propagate DkmClrValue.Category,
// which typically appears to be set to the default value ("Other").
var category = (result.Category != DkmEvaluationResultCategory.Other) ? result.Category : value.Category;
var nullableMemberInfo = value.GetDataItem<NullableMemberInfo>();
// Valid value
return DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: result.FullName,
Flags: result.Flags,
Value: display,
EditableValue: result.EditableValue,
Type: typeName,
Category: nullableMemberInfo?.Category ?? category,
Access: nullableMemberInfo?.Access ?? value.Access,
StorageType: nullableMemberInfo?.StorageType ?? value.StorageType,
TypeModifierFlags: nullableMemberInfo?.TypeModifierFlags ?? value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: customUIVisualizers,
ExternalModules: null,
DataItem: result.ToDataItem());
}
}
/// <returns>
/// The qualified name (i.e. including containing types and namespaces) of a named, pointer,
/// or array type followed by the qualified name of the actual runtime type, if provided.
/// </returns>
internal static string GetTypeName(
DkmInspectionContext inspectionContext,
DkmClrValue value,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
bool isPointerDereference)
{
var declaredLmrType = declaredType.GetLmrType();
var runtimeType = value.Type;
var declaredTypeName = inspectionContext.GetTypeName(declaredType, declaredTypeInfo, Formatter.NoFormatSpecifiers);
// Include the runtime type if distinct.
if (!declaredLmrType.IsPointer &&
!isPointerDereference &&
(!declaredLmrType.IsNullable() || value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown)))
{
// Generate the declared type name without tuple element names.
var declaredTypeInfoNoTupleElementNames = declaredTypeInfo.WithNoTupleElementNames();
var declaredTypeNameNoTupleElementNames = (declaredTypeInfo == declaredTypeInfoNoTupleElementNames) ?
declaredTypeName :
inspectionContext.GetTypeName(declaredType, declaredTypeInfoNoTupleElementNames, Formatter.NoFormatSpecifiers);
// Generate the runtime type name with no tuple element names and no dynamic.
var runtimeTypeName = inspectionContext.GetTypeName(runtimeType, null, FormatSpecifiers: Formatter.NoFormatSpecifiers);
// If the two names are distinct, include both.
if (!string.Equals(declaredTypeNameNoTupleElementNames, runtimeTypeName, StringComparison.Ordinal)) // Names will reflect "dynamic", types will not.
{
return string.Format("{0} {{{1}}}", declaredTypeName, runtimeTypeName);
}
}
return declaredTypeName;
}
internal EvalResult CreateDataItem(
DkmInspectionContext inspectionContext,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfo,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
bool useDebuggerDisplay,
ExpansionFlags expansionFlags,
bool childShouldParenthesize,
string fullName,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultCategory category,
DkmEvaluationResultFlags flags,
DkmEvaluationFlags evalFlags,
bool canFavorite,
bool isFavorite,
bool supportsFavorites)
{
if ((evalFlags & DkmEvaluationFlags.ShowValueRaw) != 0)
{
formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, "raw");
}
Expansion expansion;
// If the declared type is Nullable<T>, the value should
// have no expansion if null, or be expanded as a T.
var declaredType = declaredTypeAndInfo.Type;
var lmrNullableTypeArg = declaredType.GetNullableTypeArgument();
if (lmrNullableTypeArg != null && !value.HasExceptionThrown())
{
Debug.Assert(value.Type.GetProxyType() == null);
DkmClrValue nullableValue;
if (value.IsError())
{
expansion = null;
}
else if ((nullableValue = value.GetNullableValue(lmrNullableTypeArg, inspectionContext)) == null)
{
Debug.Assert(declaredType.Equals(value.Type.GetLmrType()));
// No expansion of "null".
expansion = null;
}
else
{
// nullableValue is taken from an internal field.
// It may have different category, access, etc comparing the original member.
// For example, the orignal member can be a property not a field.
// Save original member values to restore them later.
if (value != nullableValue)
{
var nullableMemberInfo = new NullableMemberInfo(value.Category, value.Access, value.StorageType, value.TypeModifierFlags);
nullableValue.SetDataItem(DkmDataCreationDisposition.CreateAlways, nullableMemberInfo);
}
value = nullableValue;
Debug.Assert(lmrNullableTypeArg.Equals(value.Type.GetLmrType())); // If this is not the case, add a test for includeRuntimeTypeIfNecessary.
// CONSIDER: The DynamicAttribute for the type argument should just be Skip(1) of the original flag array.
expansion = this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, lmrNullableTypeArg)), value, ExpansionFlags.IncludeResultsView, supportsFavorites: supportsFavorites);
}
}
else if (value.IsError() || (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
expansion = null;
}
else
{
expansion = DebuggerTypeProxyExpansion.CreateExpansion(
this,
inspectionContext,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
value,
childShouldParenthesize,
fullName,
flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers,
flags,
Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info));
if (expansion == null)
{
expansion = value.HasExceptionThrown()
? this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(value.Type), value, expansionFlags, supportsFavorites: false)
: this.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, expansionFlags, supportsFavorites: supportsFavorites);
}
}
return new EvalResult(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
useDebuggerDisplay: useDebuggerDisplay,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: childShouldParenthesize,
fullName: fullName,
childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers: formatSpecifiers,
category: category,
flags: flags,
editableValue: Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info),
inspectionContext: inspectionContext,
canFavorite: canFavorite,
isFavorite: isFavorite);
}
private void GetRootResultAndContinue(
DkmClrValue value,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
string name,
string fullName,
ReadOnlyCollection<string> formatSpecifiers,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
Debug.Assert(formatSpecifiers != null);
var type = value.Type.GetLmrType();
if (type.IsTypeVariables())
{
Debug.Assert(type.Equals(declaredType.GetLmrType()));
var declaredTypeAndInfo = new TypeAndCustomInfo(declaredType, declaredTypeInfo);
var expansion = new TypeVariablesExpansion(declaredTypeAndInfo);
var dataItem = new EvalResult(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: declaredTypeAndInfo,
useDebuggerDisplay: false,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: null,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: DkmEvaluationResultCategory.Data,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
Debug.Assert(dataItem.Flags == (DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable));
// Note: We're not including value.EvalFlags in Flags parameter
// below (there shouldn't be a reason to do so).
completionRoutine(DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: Resources.TypeVariablesName,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: "",
EditableValue: null,
Type: "",
Category: dataItem.Category,
Access: value.Access,
StorageType: value.StorageType,
TypeModifierFlags: value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem.ToDataItem()));
}
else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ResultsOnly) != 0)
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRow(
inspectionContext,
name,
fullName,
formatSpecifiers,
declaredType,
declaredTypeInfo,
value,
this);
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.DynamicView) != 0)
{
var dataItem = DynamicViewExpansion.CreateMembersOnlyRow(
inspectionContext,
name,
value,
this);
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRowIfSynthesizedEnumerable(
inspectionContext,
name,
fullName,
formatSpecifiers,
declaredType,
declaredTypeInfo,
value,
this);
if (dataItem != null)
{
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
var useDebuggerDisplay = (inspectionContext.EvaluationFlags & NotRoot) != 0;
var expansionFlags = (inspectionContext.EvaluationFlags & NoResults) != 0 ?
ExpansionFlags.IncludeBaseMembers :
ExpansionFlags.All;
var favortiesDataItem = value.GetDataItem<FavoritesDataItem>();
dataItem = CreateDataItem(
inspectionContext,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: new TypeAndCustomInfo(declaredType, declaredTypeInfo),
value: value,
useDebuggerDisplay: useDebuggerDisplay,
expansionFlags: expansionFlags,
childShouldParenthesize: (fullName == null) ? false : FullNameProvider.ClrExpressionMayRequireParentheses(inspectionContext, fullName),
fullName: fullName,
formatSpecifiers: formatSpecifiers,
category: DkmEvaluationResultCategory.Other,
flags: value.EvalFlags,
evalFlags: inspectionContext.EvaluationFlags,
canFavorite: favortiesDataItem?.CanFavorite ?? false,
isFavorite: favortiesDataItem?.IsFavorite ?? false,
supportsFavorites: true);
GetResultAndContinue(dataItem, workList, declaredType, declaredTypeInfo, inspectionContext, useDebuggerDisplay, completionRoutine);
}
}
}
private void GetResultAndContinue(
EvalResult result,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
bool useDebuggerDisplay,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
var value = result.Value; // Value may have been replaced (specifically, for Nullable<T>).
if (value.TryGetDebuggerDisplayInfo(out DebuggerDisplayInfo displayInfo))
{
void onException(Exception e) => completionRoutine(CreateEvaluationResultFromException(e, result, inspectionContext));
if (displayInfo.Name != null)
{
// Favorites currently dependes on the name matching the member name
result = result.WithDisableCanAddFavorite();
}
var innerWorkList = workList.InnerWorkList;
EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.Name,
displayName => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.GetValue(inspectionContext),
displayValue => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.TypeName,
displayType =>
workList.ContinueWith(() =>
completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName.Result, displayValue.Result, displayType.Result, useDebuggerDisplay))),
onException),
onException),
onException);
}
else
{
completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName: null, displayValue: null, displayType: null, useDebuggerDisplay: false));
}
}
private static void EvaluateDebuggerDisplayStringAndContinue(
DkmClrValue value,
DkmWorkList workList,
DkmInspectionContext inspectionContext,
DebuggerDisplayItemInfo displayInfo,
CompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> onCompleted,
CompletionRoutine<Exception> onException)
{
void completionRoutine(DkmEvaluateDebuggerDisplayStringAsyncResult result)
{
try
{
onCompleted(result);
}
catch (Exception e)
{
onException(e);
}
}
if (displayInfo == null)
{
completionRoutine(default(DkmEvaluateDebuggerDisplayStringAsyncResult));
}
else
{
value.EvaluateDebuggerDisplayString(workList, inspectionContext, displayInfo.TargetType, displayInfo.Value, completionRoutine);
}
}
private DkmEvaluationResult GetResult(
DkmInspectionContext inspectionContext,
EvalResult result,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
string displayName,
string displayValue,
string displayType,
bool useDebuggerDisplay)
{
var name = result.Name;
Debug.Assert(name != null);
var typeDeclaringMemberAndInfo = result.TypeDeclaringMemberAndInfo;
// Note: Don't respect the debugger display name on the root element:
// 1) In the Watch window, that's where the user's text goes.
// 2) In the Locals window, that's where the local name goes.
// Note: Dev12 respects the debugger display name in the Locals window,
// but not in the Watch window, but we can't distinguish and this
// behavior seems reasonable.
if (displayName != null && useDebuggerDisplay)
{
name = displayName;
}
else if (typeDeclaringMemberAndInfo.Type != null)
{
name = GetQualifiedMemberName(inspectionContext, typeDeclaringMemberAndInfo, name, FullNameProvider);
}
var value = result.Value;
string display;
if (value.HasExceptionThrown())
{
display = result.DisplayValue ?? value.GetExceptionMessage(inspectionContext, result.FullNameWithoutFormatSpecifiers ?? result.Name);
}
else if (displayValue != null)
{
display = value.IncludeObjectId(displayValue);
}
else
{
display = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
}
var typeName = displayType ?? GetTypeName(inspectionContext, value, declaredType, declaredTypeInfo, result.Kind == ExpansionKind.PointerDereference);
return CreateEvaluationResult(inspectionContext, value, name, typeName, display, result);
}
private void GetEvaluationResultsAndContinue(
DkmEvaluationResult parent,
ArrayBuilder<EvalResult> rows,
DkmEvaluationResult[] results,
int index,
int numRows,
WorkList workList,
DkmInspectionContext inspectionContext,
CompletionRoutine onCompleted,
CompletionRoutine<Exception> onException)
{
void completionRoutine(DkmEvaluationAsyncResult result)
{
try
{
results[index] = result.Result;
GetEvaluationResultsAndContinue(parent, rows, results, index + 1, numRows, workList, inspectionContext, onCompleted, onException);
}
catch (Exception e)
{
onException(e);
}
}
if (index < numRows)
{
GetChild(
parent,
workList,
rows[index],
child => workList.ContinueWith(() => completionRoutine(child)));
}
else
{
onCompleted();
}
}
internal Expansion GetTypeExpansion(
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
ExpansionFlags flags,
bool supportsFavorites)
{
var declaredType = declaredTypeAndInfo.Type;
Debug.Assert(!declaredType.IsTypeVariables());
if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
return null;
}
var runtimeType = value.Type.GetLmrType();
// If the value is an array, expand the array elements.
if (runtimeType.IsArray)
{
var sizes = value.ArrayDimensions;
if (sizes == null)
{
// Null array. No expansion.
return null;
}
var lowerBounds = value.ArrayLowerBounds;
Type elementType;
DkmClrCustomTypeInfo elementTypeInfo;
if (declaredType.IsArray)
{
elementType = declaredType.GetElementType();
elementTypeInfo = CustomTypeInfo.SkipOne(declaredTypeAndInfo.Info);
}
else
{
elementType = runtimeType.GetElementType();
elementTypeInfo = null;
}
return ArrayExpansion.CreateExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType), elementTypeInfo), sizes, lowerBounds);
}
if (this.IsPrimitiveType(runtimeType))
{
return null;
}
if (declaredType.IsFunctionPointer())
{
// Function pointers have no expansion
return null;
}
if (declaredType.IsPointer)
{
// If this assert fails, the element type info is just .SkipOne().
Debug.Assert(declaredTypeAndInfo.Info?.PayloadTypeId != CustomTypeInfo.PayloadTypeId);
var elementType = declaredType.GetElementType();
return value.IsNull || elementType.IsVoid()
? null
: new PointerDereferenceExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType)));
}
if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown) &&
runtimeType.IsEmptyResultsViewException())
{
// The value is an exception thrown expanding an empty
// IEnumerable. Use the runtime type of the exception and
// skip base types. (This matches the native EE behavior
// to expose a single property from the exception.)
flags &= ~ExpansionFlags.IncludeBaseMembers;
}
int cardinality;
if (runtimeType.IsTupleCompatible(out cardinality))
{
return TupleExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, cardinality);
}
return MemberExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, flags, TypeHelpers.IsVisibleMember, this, isProxyType: false, supportsFavorites);
}
private static DkmEvaluationResult CreateEvaluationResultFromException(Exception e, EvalResult result, DkmInspectionContext inspectionContext)
{
return DkmFailedEvaluationResult.Create(
inspectionContext,
result.Value.StackFrame,
Name: result.Name,
FullName: null,
ErrorMessage: e.Message,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null);
}
private static string GetQualifiedMemberName(
DkmInspectionContext inspectionContext,
TypeAndCustomInfo typeDeclaringMember,
string memberName,
IDkmClrFullNameProvider fullNameProvider)
{
var typeName = fullNameProvider.GetClrTypeName(inspectionContext, typeDeclaringMember.ClrType, typeDeclaringMember.Info) ??
inspectionContext.GetTypeName(typeDeclaringMember.ClrType, typeDeclaringMember.Info, Formatter.NoFormatSpecifiers);
return typeDeclaringMember.Type.IsInterface ?
$"{typeName}.{memberName}" :
$"{memberName} ({typeName})";
}
// Track remaining evaluations so that each subsequent evaluation
// is executed at the entry point from the host rather than on the
// callstack of the previous evaluation.
private sealed class WorkList
{
private enum State { Initialized, Executing, Executed }
internal readonly DkmWorkList InnerWorkList;
private readonly CompletionRoutine<Exception> _onException;
private CompletionRoutine _completionRoutine;
private State _state;
internal WorkList(DkmWorkList workList, CompletionRoutine<Exception> onException)
{
InnerWorkList = workList;
_onException = onException;
_state = State.Initialized;
}
/// <summary>
/// Run the continuation synchronously if there is no current
/// continuation. Otherwise hold on to the continuation for
/// the current execution to complete.
/// </summary>
internal void ContinueWith(CompletionRoutine completionRoutine)
{
Debug.Assert(_completionRoutine == null);
_completionRoutine = completionRoutine;
if (_state != State.Executing)
{
Execute();
}
}
private void Execute()
{
Debug.Assert(_state != State.Executing);
_state = State.Executing;
while (_completionRoutine != null)
{
var completionRoutine = _completionRoutine;
_completionRoutine = null;
try
{
completionRoutine();
}
catch (Exception e)
{
_onException(e);
}
}
_state = State.Executed;
}
}
private class NullableMemberInfo : DkmDataItem
{
public readonly DkmEvaluationResultCategory Category;
public readonly DkmEvaluationResultAccessType Access;
public readonly DkmEvaluationResultStorageType StorageType;
public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags;
public NullableMemberInfo(DkmEvaluationResultCategory category, DkmEvaluationResultAccessType access, DkmEvaluationResultStorageType storageType, DkmEvaluationResultTypeModifierFlags typeModifierFlags)
{
Category = category;
Access = access;
StorageType = storageType;
TypeModifierFlags = typeModifierFlags;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal delegate void CompletionRoutine();
internal delegate void CompletionRoutine<TResult>(TResult result);
/// <summary>
/// Computes expansion of <see cref="DkmClrValue"/> instances.
/// </summary>
/// <remarks>
/// This class provides implementation for the default ResultProvider component.
/// </remarks>
public abstract class ResultProvider : IDkmClrResultProvider
{
// TODO: There is a potential that these values will conflict with debugger defined flags in future.
// It'd be better if we attached these flags to the DkmClrValue object via data items, however DkmClrValue is currently mutable
// and we can't clone it -- in some cases we might need to attach different flags in different code paths and it wouldn't be possible
// to do so due to mutability.
// See https://github.com/dotnet/roslyn/issues/55676.
internal const DkmEvaluationFlags NotRoot = (DkmEvaluationFlags)(1 << 30);
internal const DkmEvaluationFlags NoResults = (DkmEvaluationFlags)(1 << 31);
// Fields should be removed and replaced with calls through DkmInspectionContext.
// (see https://github.com/dotnet/roslyn/issues/6899).
internal readonly IDkmClrFormatter2 Formatter2;
internal readonly IDkmClrFullNameProvider FullNameProvider;
static ResultProvider()
{
FatalError.Handler = FailFast.OnFatalException;
}
internal ResultProvider(IDkmClrFormatter2 formatter2, IDkmClrFullNameProvider fullNameProvider)
{
Formatter2 = formatter2;
FullNameProvider = fullNameProvider;
}
internal abstract string StaticMembersString { get; }
internal abstract bool IsPrimitiveType(Type type);
void IDkmClrResultProvider.GetResult(DkmClrValue value, DkmWorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers, string resultName, string resultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine)
{
if (formatSpecifiers == null)
{
formatSpecifiers = Formatter.NoFormatSpecifiers;
}
if (resultFullName != null)
{
ReadOnlyCollection<string> otherSpecifiers;
resultFullName = FullNameProvider.GetClrExpressionAndFormatSpecifiers(inspectionContext, resultFullName, out otherSpecifiers);
foreach (var formatSpecifier in otherSpecifiers)
{
formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, formatSpecifier);
}
}
var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationAsyncResult.CreateErrorResult(e)));
wl.ContinueWith(
() => GetRootResultAndContinue(
value,
wl,
declaredType,
declaredTypeInfo,
inspectionContext,
resultName,
resultFullName,
formatSpecifiers,
result => wl.ContinueWith(() => completionRoutine(new DkmEvaluationAsyncResult(result)))));
}
DkmClrValue IDkmClrResultProvider.GetClrValue(DkmSuccessEvaluationResult evaluationResult)
{
try
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
return evaluationResult.GetClrValue();
}
return dataItem.Value;
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrResultProvider.GetChildren(DkmEvaluationResult evaluationResult, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine)
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
evaluationResult.GetChildren(workList, initialRequestSize, inspectionContext, completionRoutine);
return;
}
var expansion = dataItem.Expansion;
if (expansion == null)
{
var enumContext = DkmEvaluationResultEnumContext.Create(0, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult));
completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], enumContext));
return;
}
// Evaluate children with InspectionContext that is not the root.
inspectionContext = inspectionContext.With(NotRoot);
var rows = ArrayBuilder<EvalResult>.GetInstance();
int index = 0;
expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, 0, initialRequestSize, visitAll: true, index: ref index);
var numRows = rows.Count;
Debug.Assert(index >= numRows);
Debug.Assert(initialRequestSize >= numRows);
var initialChildren = new DkmEvaluationResult[numRows];
void onException(Exception e) => completionRoutine(DkmGetChildrenAsyncResult.CreateErrorResult(e));
var wl = new WorkList(workList, onException);
wl.ContinueWith(() =>
GetEvaluationResultsAndContinue(evaluationResult, rows, initialChildren, 0, numRows, wl, inspectionContext,
() =>
wl.ContinueWith(
() =>
{
var enumContext = DkmEvaluationResultEnumContext.Create(index, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult));
completionRoutine(new DkmGetChildrenAsyncResult(initialChildren, enumContext));
rows.Free();
}),
onException));
}
void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine)
{
var enumContextDataItem = enumContext.GetDataItem<EnumContextDataItem>();
if (enumContextDataItem == null)
{
// We don't know about this result. Call next implementation
enumContext.GetItems(workList, startIndex, count, completionRoutine);
return;
}
var evaluationResult = enumContextDataItem.Result;
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
var expansion = dataItem.Expansion;
if (expansion == null)
{
completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0]));
return;
}
var inspectionContext = enumContext.InspectionContext;
var rows = ArrayBuilder<EvalResult>.GetInstance();
int index = 0;
expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, startIndex, count, visitAll: false, index: ref index);
var numRows = rows.Count;
Debug.Assert(count >= numRows);
var results = new DkmEvaluationResult[numRows];
void onException(Exception e) => completionRoutine(DkmEvaluationEnumAsyncResult.CreateErrorResult(e));
var wl = new WorkList(workList, onException);
wl.ContinueWith(() =>
GetEvaluationResultsAndContinue(evaluationResult, rows, results, 0, numRows, wl, inspectionContext,
() =>
wl.ContinueWith(
() =>
{
completionRoutine(new DkmEvaluationEnumAsyncResult(results));
rows.Free();
}),
onException));
}
string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result)
{
try
{
var dataItem = result.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
return result.GetUnderlyingString();
}
return dataItem.Value?.GetUnderlyingString(result.InspectionContext);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void GetChild(
DkmEvaluationResult parent,
WorkList workList,
EvalResult row,
DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine)
{
var inspectionContext = row.InspectionContext;
if ((row.Kind != ExpansionKind.Default) || (row.Value == null))
{
CreateEvaluationResultAndContinue(
row,
workList,
row.InspectionContext,
parent.StackFrame,
child => completionRoutine(new DkmEvaluationAsyncResult(child)));
}
else
{
var typeDeclaringMember = row.TypeDeclaringMemberAndInfo;
var name = (typeDeclaringMember.Type == null) ?
row.Name :
GetQualifiedMemberName(row.InspectionContext, typeDeclaringMember, row.Name, FullNameProvider);
row.Value.SetDataItem(DkmDataCreationDisposition.CreateAlways, new FavoritesDataItem(row.CanFavorite, row.IsFavorite));
row.Value.GetResult(
workList.InnerWorkList,
row.DeclaredTypeAndInfo.ClrType,
row.DeclaredTypeAndInfo.Info,
row.InspectionContext,
Formatter.NoFormatSpecifiers,
name,
row.FullName,
result => workList.ContinueWith(() => completionRoutine(result)));
}
}
private void CreateEvaluationResultAndContinue(EvalResult result, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
switch (result.Kind)
{
case ExpansionKind.Explicit:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: result.DisplayName,
FullName: result.FullName,
Flags: result.Flags,
Value: result.DisplayValue,
EditableValue: result.EditableValue,
Type: result.DisplayType,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.Error:
completionRoutine(DkmFailedEvaluationResult.Create(
inspectionContext,
StackFrame: stackFrame,
Name: result.Name,
FullName: result.FullName,
ErrorMessage: result.DisplayValue,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null));
break;
case ExpansionKind.NativeView:
{
var value = result.Value;
var name = Resources.NativeView;
var fullName = result.FullName;
var display = result.Name;
DkmEvaluationResult evalResult;
if (value.IsError())
{
evalResult = DkmFailedEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
ErrorMessage: display,
Flags: result.Flags,
Type: null,
DataItem: result.ToDataItem());
}
else
{
// For Native View, create a DkmIntermediateEvaluationResult.
// This will allow the C++ EE to take over expansion.
var process = inspectionContext.RuntimeInstance.Process;
var cpp = process.EngineSettings.GetLanguage(new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp));
evalResult = DkmIntermediateEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
Expression: display,
IntermediateLanguage: cpp,
TargetRuntime: process.GetNativeRuntimeInstance(),
DataItem: result.ToDataItem());
}
completionRoutine(evalResult);
}
break;
case ExpansionKind.NonPublicMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.NonPublicMembers,
FullName: result.FullName,
Flags: result.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.StaticMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: StaticMembersString,
FullName: result.FullName,
Flags: result.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Class,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.RawView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.RawView,
FullName: result.FullName,
Flags: result.Flags,
Value: null,
EditableValue: result.EditableValue,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.DynamicView:
case ExpansionKind.ResultsView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
result.Name,
result.FullName,
result.Flags,
result.DisplayValue,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Method,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.TypeVariable:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
result.Name,
result.FullName,
result.Flags,
result.DisplayValue,
EditableValue: null,
Type: result.DisplayValue,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: result.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: result.ToDataItem()));
break;
case ExpansionKind.PointerDereference:
case ExpansionKind.Default:
// This call will evaluate DebuggerDisplayAttributes.
GetResultAndContinue(
result,
workList,
declaredType: result.DeclaredTypeAndInfo.ClrType,
declaredTypeInfo: result.DeclaredTypeAndInfo.Info,
inspectionContext: inspectionContext,
useDebuggerDisplay: result.UseDebuggerDisplay,
completionRoutine: completionRoutine);
break;
default:
throw ExceptionUtilities.UnexpectedValue(result.Kind);
}
}
private static DkmEvaluationResult CreateEvaluationResult(
DkmInspectionContext inspectionContext,
DkmClrValue value,
string name,
string typeName,
string display,
EvalResult result)
{
if (value.IsError())
{
// Evaluation failed
return DkmFailedEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: result.FullName,
ErrorMessage: display,
Flags: result.Flags,
Type: typeName,
DataItem: result.ToDataItem());
}
else
{
ReadOnlyCollection<DkmCustomUIVisualizerInfo> customUIVisualizers = null;
if (!value.IsNull)
{
DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = value.Type.GetDebuggerCustomUIVisualizerInfo();
if (customUIVisualizerInfo != null)
{
customUIVisualizers = new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo);
}
}
// If the EvalResultDataItem doesn't specify a particular category, we'll just propagate DkmClrValue.Category,
// which typically appears to be set to the default value ("Other").
var category = (result.Category != DkmEvaluationResultCategory.Other) ? result.Category : value.Category;
var nullableMemberInfo = value.GetDataItem<NullableMemberInfo>();
// Valid value
return DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: result.FullName,
Flags: result.Flags,
Value: display,
EditableValue: result.EditableValue,
Type: typeName,
Category: nullableMemberInfo?.Category ?? category,
Access: nullableMemberInfo?.Access ?? value.Access,
StorageType: nullableMemberInfo?.StorageType ?? value.StorageType,
TypeModifierFlags: nullableMemberInfo?.TypeModifierFlags ?? value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: customUIVisualizers,
ExternalModules: null,
DataItem: result.ToDataItem());
}
}
/// <returns>
/// The qualified name (i.e. including containing types and namespaces) of a named, pointer,
/// or array type followed by the qualified name of the actual runtime type, if provided.
/// </returns>
internal static string GetTypeName(
DkmInspectionContext inspectionContext,
DkmClrValue value,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
bool isPointerDereference)
{
var declaredLmrType = declaredType.GetLmrType();
var runtimeType = value.Type;
var declaredTypeName = inspectionContext.GetTypeName(declaredType, declaredTypeInfo, Formatter.NoFormatSpecifiers);
// Include the runtime type if distinct.
if (!declaredLmrType.IsPointer &&
!isPointerDereference &&
(!declaredLmrType.IsNullable() || value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown)))
{
// Generate the declared type name without tuple element names.
var declaredTypeInfoNoTupleElementNames = declaredTypeInfo.WithNoTupleElementNames();
var declaredTypeNameNoTupleElementNames = (declaredTypeInfo == declaredTypeInfoNoTupleElementNames) ?
declaredTypeName :
inspectionContext.GetTypeName(declaredType, declaredTypeInfoNoTupleElementNames, Formatter.NoFormatSpecifiers);
// Generate the runtime type name with no tuple element names and no dynamic.
var runtimeTypeName = inspectionContext.GetTypeName(runtimeType, null, FormatSpecifiers: Formatter.NoFormatSpecifiers);
// If the two names are distinct, include both.
if (!string.Equals(declaredTypeNameNoTupleElementNames, runtimeTypeName, StringComparison.Ordinal)) // Names will reflect "dynamic", types will not.
{
return string.Format("{0} {{{1}}}", declaredTypeName, runtimeTypeName);
}
}
return declaredTypeName;
}
internal EvalResult CreateDataItem(
DkmInspectionContext inspectionContext,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfo,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
bool useDebuggerDisplay,
ExpansionFlags expansionFlags,
bool childShouldParenthesize,
string fullName,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultCategory category,
DkmEvaluationResultFlags flags,
DkmEvaluationFlags evalFlags,
bool canFavorite,
bool isFavorite,
bool supportsFavorites)
{
if ((evalFlags & DkmEvaluationFlags.ShowValueRaw) != 0)
{
formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, "raw");
}
Expansion expansion;
// If the declared type is Nullable<T>, the value should
// have no expansion if null, or be expanded as a T.
var declaredType = declaredTypeAndInfo.Type;
var lmrNullableTypeArg = declaredType.GetNullableTypeArgument();
if (lmrNullableTypeArg != null && !value.HasExceptionThrown())
{
Debug.Assert(value.Type.GetProxyType() == null);
DkmClrValue nullableValue;
if (value.IsError())
{
expansion = null;
}
else if ((nullableValue = value.GetNullableValue(lmrNullableTypeArg, inspectionContext)) == null)
{
Debug.Assert(declaredType.Equals(value.Type.GetLmrType()));
// No expansion of "null".
expansion = null;
}
else
{
// nullableValue is taken from an internal field.
// It may have different category, access, etc comparing the original member.
// For example, the orignal member can be a property not a field.
// Save original member values to restore them later.
if (value != nullableValue)
{
var nullableMemberInfo = new NullableMemberInfo(value.Category, value.Access, value.StorageType, value.TypeModifierFlags);
nullableValue.SetDataItem(DkmDataCreationDisposition.CreateAlways, nullableMemberInfo);
}
value = nullableValue;
Debug.Assert(lmrNullableTypeArg.Equals(value.Type.GetLmrType())); // If this is not the case, add a test for includeRuntimeTypeIfNecessary.
// CONSIDER: The DynamicAttribute for the type argument should just be Skip(1) of the original flag array.
expansion = this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, lmrNullableTypeArg)), value, ExpansionFlags.IncludeResultsView, supportsFavorites: supportsFavorites);
}
}
else if (value.IsError() || (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
expansion = null;
}
else
{
expansion = DebuggerTypeProxyExpansion.CreateExpansion(
this,
inspectionContext,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
value,
childShouldParenthesize,
fullName,
flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers,
flags,
Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info));
if (expansion == null)
{
expansion = value.HasExceptionThrown()
? this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(value.Type), value, expansionFlags, supportsFavorites: false)
: this.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, expansionFlags, supportsFavorites: supportsFavorites);
}
}
return new EvalResult(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
useDebuggerDisplay: useDebuggerDisplay,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: childShouldParenthesize,
fullName: fullName,
childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers: formatSpecifiers,
category: category,
flags: flags,
editableValue: Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info),
inspectionContext: inspectionContext,
canFavorite: canFavorite,
isFavorite: isFavorite);
}
private void GetRootResultAndContinue(
DkmClrValue value,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
string name,
string fullName,
ReadOnlyCollection<string> formatSpecifiers,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
Debug.Assert(formatSpecifiers != null);
var type = value.Type.GetLmrType();
if (type.IsTypeVariables())
{
Debug.Assert(type.Equals(declaredType.GetLmrType()));
var declaredTypeAndInfo = new TypeAndCustomInfo(declaredType, declaredTypeInfo);
var expansion = new TypeVariablesExpansion(declaredTypeAndInfo);
var dataItem = new EvalResult(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: declaredTypeAndInfo,
useDebuggerDisplay: false,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: null,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: DkmEvaluationResultCategory.Data,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
Debug.Assert(dataItem.Flags == (DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable));
// Note: We're not including value.EvalFlags in Flags parameter
// below (there shouldn't be a reason to do so).
completionRoutine(DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: Resources.TypeVariablesName,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: "",
EditableValue: null,
Type: "",
Category: dataItem.Category,
Access: value.Access,
StorageType: value.StorageType,
TypeModifierFlags: value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem.ToDataItem()));
}
else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ResultsOnly) != 0)
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRow(
inspectionContext,
name,
fullName,
formatSpecifiers,
declaredType,
declaredTypeInfo,
value,
this);
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.DynamicView) != 0)
{
var dataItem = DynamicViewExpansion.CreateMembersOnlyRow(
inspectionContext,
name,
value,
this);
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRowIfSynthesizedEnumerable(
inspectionContext,
name,
fullName,
formatSpecifiers,
declaredType,
declaredTypeInfo,
value,
this);
if (dataItem != null)
{
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
var useDebuggerDisplay = (inspectionContext.EvaluationFlags & NotRoot) != 0;
var expansionFlags = (inspectionContext.EvaluationFlags & NoResults) != 0 ?
ExpansionFlags.IncludeBaseMembers :
ExpansionFlags.All;
var favortiesDataItem = value.GetDataItem<FavoritesDataItem>();
dataItem = CreateDataItem(
inspectionContext,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: new TypeAndCustomInfo(declaredType, declaredTypeInfo),
value: value,
useDebuggerDisplay: useDebuggerDisplay,
expansionFlags: expansionFlags,
childShouldParenthesize: (fullName == null) ? false : FullNameProvider.ClrExpressionMayRequireParentheses(inspectionContext, fullName),
fullName: fullName,
formatSpecifiers: formatSpecifiers,
category: DkmEvaluationResultCategory.Other,
flags: value.EvalFlags,
evalFlags: inspectionContext.EvaluationFlags,
canFavorite: favortiesDataItem?.CanFavorite ?? false,
isFavorite: favortiesDataItem?.IsFavorite ?? false,
supportsFavorites: true);
GetResultAndContinue(dataItem, workList, declaredType, declaredTypeInfo, inspectionContext, useDebuggerDisplay, completionRoutine);
}
}
}
private void GetResultAndContinue(
EvalResult result,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
bool useDebuggerDisplay,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
var value = result.Value; // Value may have been replaced (specifically, for Nullable<T>).
if (value.TryGetDebuggerDisplayInfo(out DebuggerDisplayInfo displayInfo))
{
void onException(Exception e) => completionRoutine(CreateEvaluationResultFromException(e, result, inspectionContext));
if (displayInfo.Name != null)
{
// Favorites currently dependes on the name matching the member name
result = result.WithDisableCanAddFavorite();
}
var innerWorkList = workList.InnerWorkList;
EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.Name,
displayName => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.GetValue(inspectionContext),
displayValue => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, displayInfo.TypeName,
displayType =>
workList.ContinueWith(() =>
completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName.Result, displayValue.Result, displayType.Result, useDebuggerDisplay))),
onException),
onException),
onException);
}
else
{
completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName: null, displayValue: null, displayType: null, useDebuggerDisplay: false));
}
}
private static void EvaluateDebuggerDisplayStringAndContinue(
DkmClrValue value,
DkmWorkList workList,
DkmInspectionContext inspectionContext,
DebuggerDisplayItemInfo displayInfo,
CompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> onCompleted,
CompletionRoutine<Exception> onException)
{
void completionRoutine(DkmEvaluateDebuggerDisplayStringAsyncResult result)
{
try
{
onCompleted(result);
}
catch (Exception e)
{
onException(e);
}
}
if (displayInfo == null)
{
completionRoutine(default(DkmEvaluateDebuggerDisplayStringAsyncResult));
}
else
{
value.EvaluateDebuggerDisplayString(workList, inspectionContext, displayInfo.TargetType, displayInfo.Value, completionRoutine);
}
}
private DkmEvaluationResult GetResult(
DkmInspectionContext inspectionContext,
EvalResult result,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
string displayName,
string displayValue,
string displayType,
bool useDebuggerDisplay)
{
var name = result.Name;
Debug.Assert(name != null);
var typeDeclaringMemberAndInfo = result.TypeDeclaringMemberAndInfo;
// Note: Don't respect the debugger display name on the root element:
// 1) In the Watch window, that's where the user's text goes.
// 2) In the Locals window, that's where the local name goes.
// Note: Dev12 respects the debugger display name in the Locals window,
// but not in the Watch window, but we can't distinguish and this
// behavior seems reasonable.
if (displayName != null && useDebuggerDisplay)
{
name = displayName;
}
else if (typeDeclaringMemberAndInfo.Type != null)
{
name = GetQualifiedMemberName(inspectionContext, typeDeclaringMemberAndInfo, name, FullNameProvider);
}
var value = result.Value;
string display;
if (value.HasExceptionThrown())
{
display = result.DisplayValue ?? value.GetExceptionMessage(inspectionContext, result.FullNameWithoutFormatSpecifiers ?? result.Name);
}
else if (displayValue != null)
{
display = value.IncludeObjectId(displayValue);
}
else
{
display = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
}
var typeName = displayType ?? GetTypeName(inspectionContext, value, declaredType, declaredTypeInfo, result.Kind == ExpansionKind.PointerDereference);
return CreateEvaluationResult(inspectionContext, value, name, typeName, display, result);
}
private void GetEvaluationResultsAndContinue(
DkmEvaluationResult parent,
ArrayBuilder<EvalResult> rows,
DkmEvaluationResult[] results,
int index,
int numRows,
WorkList workList,
DkmInspectionContext inspectionContext,
CompletionRoutine onCompleted,
CompletionRoutine<Exception> onException)
{
void completionRoutine(DkmEvaluationAsyncResult result)
{
try
{
results[index] = result.Result;
GetEvaluationResultsAndContinue(parent, rows, results, index + 1, numRows, workList, inspectionContext, onCompleted, onException);
}
catch (Exception e)
{
onException(e);
}
}
if (index < numRows)
{
GetChild(
parent,
workList,
rows[index],
child => workList.ContinueWith(() => completionRoutine(child)));
}
else
{
onCompleted();
}
}
internal Expansion GetTypeExpansion(
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
ExpansionFlags flags,
bool supportsFavorites)
{
var declaredType = declaredTypeAndInfo.Type;
Debug.Assert(!declaredType.IsTypeVariables());
if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
return null;
}
var runtimeType = value.Type.GetLmrType();
// If the value is an array, expand the array elements.
if (runtimeType.IsArray)
{
var sizes = value.ArrayDimensions;
if (sizes == null)
{
// Null array. No expansion.
return null;
}
var lowerBounds = value.ArrayLowerBounds;
Type elementType;
DkmClrCustomTypeInfo elementTypeInfo;
if (declaredType.IsArray)
{
elementType = declaredType.GetElementType();
elementTypeInfo = CustomTypeInfo.SkipOne(declaredTypeAndInfo.Info);
}
else
{
elementType = runtimeType.GetElementType();
elementTypeInfo = null;
}
return ArrayExpansion.CreateExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType), elementTypeInfo), sizes, lowerBounds);
}
if (this.IsPrimitiveType(runtimeType))
{
return null;
}
if (declaredType.IsFunctionPointer())
{
// Function pointers have no expansion
return null;
}
if (declaredType.IsPointer)
{
// If this assert fails, the element type info is just .SkipOne().
Debug.Assert(declaredTypeAndInfo.Info?.PayloadTypeId != CustomTypeInfo.PayloadTypeId);
var elementType = declaredType.GetElementType();
return value.IsNull || elementType.IsVoid()
? null
: new PointerDereferenceExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType)));
}
if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown) &&
runtimeType.IsEmptyResultsViewException())
{
// The value is an exception thrown expanding an empty
// IEnumerable. Use the runtime type of the exception and
// skip base types. (This matches the native EE behavior
// to expose a single property from the exception.)
flags &= ~ExpansionFlags.IncludeBaseMembers;
}
int cardinality;
if (runtimeType.IsTupleCompatible(out cardinality))
{
return TupleExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, cardinality);
}
return MemberExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, flags, TypeHelpers.IsVisibleMember, this, isProxyType: false, supportsFavorites);
}
private static DkmEvaluationResult CreateEvaluationResultFromException(Exception e, EvalResult result, DkmInspectionContext inspectionContext)
{
return DkmFailedEvaluationResult.Create(
inspectionContext,
result.Value.StackFrame,
Name: result.Name,
FullName: null,
ErrorMessage: e.Message,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null);
}
private static string GetQualifiedMemberName(
DkmInspectionContext inspectionContext,
TypeAndCustomInfo typeDeclaringMember,
string memberName,
IDkmClrFullNameProvider fullNameProvider)
{
var typeName = fullNameProvider.GetClrTypeName(inspectionContext, typeDeclaringMember.ClrType, typeDeclaringMember.Info) ??
inspectionContext.GetTypeName(typeDeclaringMember.ClrType, typeDeclaringMember.Info, Formatter.NoFormatSpecifiers);
return typeDeclaringMember.Type.IsInterface ?
$"{typeName}.{memberName}" :
$"{memberName} ({typeName})";
}
// Track remaining evaluations so that each subsequent evaluation
// is executed at the entry point from the host rather than on the
// callstack of the previous evaluation.
private sealed class WorkList
{
private enum State { Initialized, Executing, Executed }
internal readonly DkmWorkList InnerWorkList;
private readonly CompletionRoutine<Exception> _onException;
private CompletionRoutine _completionRoutine;
private State _state;
internal WorkList(DkmWorkList workList, CompletionRoutine<Exception> onException)
{
InnerWorkList = workList;
_onException = onException;
_state = State.Initialized;
}
/// <summary>
/// Run the continuation synchronously if there is no current
/// continuation. Otherwise hold on to the continuation for
/// the current execution to complete.
/// </summary>
internal void ContinueWith(CompletionRoutine completionRoutine)
{
Debug.Assert(_completionRoutine == null);
_completionRoutine = completionRoutine;
if (_state != State.Executing)
{
Execute();
}
}
private void Execute()
{
Debug.Assert(_state != State.Executing);
_state = State.Executing;
while (_completionRoutine != null)
{
var completionRoutine = _completionRoutine;
_completionRoutine = null;
try
{
completionRoutine();
}
catch (Exception e)
{
_onException(e);
}
}
_state = State.Executed;
}
}
private class NullableMemberInfo : DkmDataItem
{
public readonly DkmEvaluationResultCategory Category;
public readonly DkmEvaluationResultAccessType Access;
public readonly DkmEvaluationResultStorageType StorageType;
public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags;
public NullableMemberInfo(DkmEvaluationResultCategory category, DkmEvaluationResultAccessType access, DkmEvaluationResultStorageType storageType, DkmEvaluationResultTypeModifierFlags typeModifierFlags)
{
Category = category;
Access = access;
StorageType = storageType;
TypeModifierFlags = typeModifierFlags;
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/SyntacticDocument.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal class SyntacticDocument
{
public readonly Document Document;
public readonly SourceText Text;
public readonly SyntaxTree SyntaxTree;
public readonly SyntaxNode Root;
protected SyntacticDocument(Document document, SourceText text, SyntaxTree tree, SyntaxNode root)
{
this.Document = document;
this.Text = text;
this.SyntaxTree = tree;
this.Root = root;
}
public Project Project => this.Document.Project;
public static async Task<SyntacticDocument> CreateAsync(
Document document, CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return new SyntacticDocument(document, text, root.SyntaxTree, root);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal class SyntacticDocument
{
public readonly Document Document;
public readonly SourceText Text;
public readonly SyntaxTree SyntaxTree;
public readonly SyntaxNode Root;
protected SyntacticDocument(Document document, SourceText text, SyntaxTree tree, SyntaxNode root)
{
this.Document = document;
this.Text = text;
this.SyntaxTree = tree;
this.Root = root;
}
public Project Project => this.Document.Project;
public static async Task<SyntacticDocument> CreateAsync(
Document document, CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return new SyntacticDocument(document, text, root.SyntaxTree, root);
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Tools/ExternalAccess/FSharp/Internal/NavigateTo/FSharpNavigateToMatchKindHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ExternalAccess.FSharp.NavigateTo;
using Microsoft.CodeAnalysis.NavigateTo;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.NavigateTo
{
internal static class FSharpNavigateToMatchKindHelpers
{
public static NavigateToMatchKind ConvertTo(FSharpNavigateToMatchKind kind)
{
switch (kind)
{
case FSharpNavigateToMatchKind.Exact:
{
return NavigateToMatchKind.Exact;
}
case FSharpNavigateToMatchKind.Prefix:
{
return NavigateToMatchKind.Prefix;
}
case FSharpNavigateToMatchKind.Substring:
{
return NavigateToMatchKind.Substring;
}
case FSharpNavigateToMatchKind.Regular:
{
return NavigateToMatchKind.Regular;
}
case FSharpNavigateToMatchKind.None:
{
return NavigateToMatchKind.None;
}
case FSharpNavigateToMatchKind.CamelCaseExact:
{
return NavigateToMatchKind.CamelCaseExact;
}
case FSharpNavigateToMatchKind.CamelCasePrefix:
{
return NavigateToMatchKind.CamelCasePrefix;
}
case FSharpNavigateToMatchKind.CamelCaseNonContiguousPrefix:
{
return NavigateToMatchKind.CamelCaseNonContiguousPrefix;
}
case FSharpNavigateToMatchKind.CamelCaseSubstring:
{
return NavigateToMatchKind.CamelCaseSubstring;
}
case FSharpNavigateToMatchKind.CamelCaseNonContiguousSubstring:
{
return NavigateToMatchKind.CamelCaseNonContiguousSubstring;
}
case FSharpNavigateToMatchKind.Fuzzy:
{
return NavigateToMatchKind.Fuzzy;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ExternalAccess.FSharp.NavigateTo;
using Microsoft.CodeAnalysis.NavigateTo;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.NavigateTo
{
internal static class FSharpNavigateToMatchKindHelpers
{
public static NavigateToMatchKind ConvertTo(FSharpNavigateToMatchKind kind)
{
switch (kind)
{
case FSharpNavigateToMatchKind.Exact:
{
return NavigateToMatchKind.Exact;
}
case FSharpNavigateToMatchKind.Prefix:
{
return NavigateToMatchKind.Prefix;
}
case FSharpNavigateToMatchKind.Substring:
{
return NavigateToMatchKind.Substring;
}
case FSharpNavigateToMatchKind.Regular:
{
return NavigateToMatchKind.Regular;
}
case FSharpNavigateToMatchKind.None:
{
return NavigateToMatchKind.None;
}
case FSharpNavigateToMatchKind.CamelCaseExact:
{
return NavigateToMatchKind.CamelCaseExact;
}
case FSharpNavigateToMatchKind.CamelCasePrefix:
{
return NavigateToMatchKind.CamelCasePrefix;
}
case FSharpNavigateToMatchKind.CamelCaseNonContiguousPrefix:
{
return NavigateToMatchKind.CamelCaseNonContiguousPrefix;
}
case FSharpNavigateToMatchKind.CamelCaseSubstring:
{
return NavigateToMatchKind.CamelCaseSubstring;
}
case FSharpNavigateToMatchKind.CamelCaseNonContiguousSubstring:
{
return NavigateToMatchKind.CamelCaseNonContiguousSubstring;
}
case FSharpNavigateToMatchKind.Fuzzy:
{
return NavigateToMatchKind.Fuzzy;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/CSharp/Test/Semantic/Semantics/UnsafeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 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;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Tests related to binding (but not lowering) lock statements.
/// </summary>
public class UnsafeTests : CompilingTestBase
{
private static string GetEscapedNewLine()
{
if (Environment.NewLine == "\n")
{
return @"\n";
}
else if (Environment.NewLine == "\r\n")
{
return @"\r\n";
}
else
{
throw new Exception("Unrecognized new line");
}
}
#region Unsafe regions
[Fact]
public void FixedSizeBuffer()
{
var text1 = @"
using System;
using System.Runtime.InteropServices;
public static class R
{
public unsafe struct S
{
public fixed byte Buffer[16];
}
}";
var comp1 = CreateEmptyCompilation(text1, assemblyName: "assembly1", references: new[] { MscorlibRef_v20 },
options: TestOptions.UnsafeDebugDll);
var ref1 = comp1.EmitToImageReference();
var text2 = @"
using System;
class C
{
unsafe void M(byte* p)
{
R.S* p2 = (R.S*)p;
IntPtr p3 = M2((IntPtr)p2[0].Buffer);
}
unsafe IntPtr M2(IntPtr p) => p;
}";
var comp2 = CreateCompilationWithMscorlib45(text2,
references: new[] { ref1 },
options: TestOptions.UnsafeDebugDll);
comp2.VerifyDiagnostics(
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1));
}
[Fact]
public void FixedSizeBuffer_GenericStruct_01()
{
var code = @"
unsafe struct MyStruct<T>
{
public fixed char buf[16];
public static void M()
{
var ms = new MyStruct<int>();
var ptr = &ms;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void FixedSizeBuffer_GenericStruct_02()
{
var code = @"
unsafe struct MyStruct<T>
{
public fixed T buf[16];
public static void M()
{
var ms = new MyStruct<int>();
var ptr = &ms;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,18): 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
// public fixed T buf[16];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "T").WithLocation(4, 18)
);
}
[Fact]
public void FixedSizeBuffer_GenericStruct_03()
{
var code = @"
unsafe struct MyStruct<T> where T : unmanaged
{
public fixed T buf[16];
public static void M()
{
var ms = new MyStruct<int>();
var ptr = &ms;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,18): 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
// public fixed T buf[16];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "T").WithLocation(4, 18)
);
}
[Fact]
public void FixedSizeBuffer_GenericStruct_04()
{
var code = @"
public unsafe struct MyStruct<T>
{
public T field;
}
unsafe struct OuterStruct
{
public fixed MyStruct<int> buf[16];
public static void M()
{
var os = new OuterStruct();
var ptr = &os;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,18): 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
// public fixed MyStruct<int> buf[16];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "MyStruct<int>").WithLocation(9, 18)
);
}
[Fact]
public void CompilationNotUnsafe1()
{
var text = @"
unsafe class C
{
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics(
// (2,14): error CS0227: Unsafe code may only appear if compiling with /unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "C"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void CompilationNotUnsafe2()
{
var text = @"
class C
{
unsafe void Goo()
{
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics(
// (4,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Goo"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void CompilationNotUnsafe3()
{
var text = @"
class C
{
void Goo()
{
/*<bind>*/unsafe
{
_ = 0;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = 0')
Left:
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(text, expectedOperationTree,
compilationOptions: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false),
expectedDiagnostics: new DiagnosticDescription[] {
// file.cs(6,19): error CS0227: Unsafe code may only appear if compiling with /unsafe
// /*<bind>*/unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(6, 19)
});
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void IteratorUnsafe1()
{
var text = @"
unsafe class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void IteratorUnsafe2()
{
var text = @"
class C
{
unsafe System.Collections.Generic.IEnumerator<int> Goo()
{
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,56): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Goo"));
}
[Fact]
public void IteratorUnsafe3()
{
var text = @"
class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
unsafe { }
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"));
}
[Fact]
public void IteratorUnsafe4()
{
var text = @"
unsafe class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
unsafe { }
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"));
}
[WorkItem(546657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546657")]
[Fact]
public void IteratorUnsafe5()
{
var text = @"
unsafe class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
System.Action a = () => { unsafe { } };
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"));
}
[Fact]
public void UnsafeModifier()
{
var text = @"
unsafe class C
{
unsafe C() { }
unsafe ~C() { }
unsafe static void Static() { }
unsafe void Instance() { }
unsafe struct Inner { }
unsafe int field = 1;
unsafe event System.Action Event;
unsafe int Property { get; set; }
unsafe int this[int x] { get { return field; } set { } }
unsafe public static C operator +(C c1, C c2) { return c1; }
unsafe public static implicit operator int(C c) { return 0; }
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,32): warning CS0067: The event 'C.Event' is never used
// unsafe event System.Action Event;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("C.Event"));
}
[Fact]
public void TypeIsUnsafe()
{
var text = @"
unsafe class C<T>
{
int* f0;
int** f1;
int*[] f2;
int*[][] f3;
C<int*> f4;
C<int**> f5;
C<int*[]> f6;
C<int*[][]> f7;
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
compilation.VerifyDiagnostics(
// (8,13): error CS0306: The type 'int*' may not be used as a type argument
// C<int*> f4;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "f4").WithArguments("int*").WithLocation(8, 13),
// (9,14): error CS0306: The type 'int**' may not be used as a type argument
// C<int**> f5;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "f5").WithArguments("int**").WithLocation(9, 14),
// (4,10): warning CS0169: The field 'C<T>.f0' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f0").WithArguments("C<T>.f0"),
// (5,11): warning CS0169: The field 'C<T>.f1' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f1").WithArguments("C<T>.f1"),
// (6,12): warning CS0169: The field 'C<T>.f2' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f2").WithArguments("C<T>.f2"),
// (7,14): warning CS0169: The field 'C<T>.f3' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f3").WithArguments("C<T>.f3"),
// (8,13): warning CS0169: The field 'C<T>.f4' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f4").WithArguments("C<T>.f4"),
// (9,14): warning CS0169: The field 'C<T>.f5' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f5").WithArguments("C<T>.f5"),
// (10,15): warning CS0169: The field 'C<T>.f6' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f6").WithArguments("C<T>.f6"),
// (11,17): warning CS0169: The field 'C<T>.f7' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f7").WithArguments("C<T>.f7"));
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var fieldTypes = Enumerable.Range(0, 8).Select(i => type.GetMember<FieldSymbol>("f" + i).TypeWithAnnotations).ToArray();
Assert.True(fieldTypes[0].Type.IsUnsafe());
Assert.True(fieldTypes[1].Type.IsUnsafe());
Assert.True(fieldTypes[2].Type.IsUnsafe());
Assert.True(fieldTypes[3].Type.IsUnsafe());
Assert.False(fieldTypes[4].Type.IsUnsafe());
Assert.False(fieldTypes[5].Type.IsUnsafe());
Assert.False(fieldTypes[6].Type.IsUnsafe());
Assert.False(fieldTypes[7].Type.IsUnsafe());
}
[Fact]
public void UnsafeFieldTypes()
{
var template = @"
{0} class C
{{
public {1} int* f = null, g = null;
}}
";
CompareUnsafeDiagnostics(template,
// (4,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public int* f = null, g = null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
);
}
[Fact]
public void UnsafeLocalTypes()
{
var template = @"
{0} class C
{{
void M()
{{
{1}
{{
int* f = null, g = null;
}}
}}
}}
";
CompareUnsafeDiagnostics(template,
// (6,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeMethodSignatures()
{
var template = @"
{0} interface I
{{
{1} int* M(long* p, byte* q);
}}
{0} class C
{{
{1} int* M(long* p, byte* q) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void DelegateSignatures()
{
var template = @"
{0} class C
{{
{1} delegate int* M(long* p, byte* q);
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,31): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (4,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeConstructorSignatures()
{
var template = @"
{0} class C
{{
{1} C(long* p, byte* q) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"));
}
[Fact]
public void UnsafeOperatorSignatures()
{
var template = @"
{0} class C
{{
public static {1} C operator +(C c, int* p) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeConversionSignatures()
{
var template = @"
{0} class C
{{
public static {1} explicit operator C(int* p) {{ throw null; }}
public static {1} explicit operator byte*(C c) {{ throw null; }}
public static {1} implicit operator C(short* p) {{ throw null; }}
public static {1} implicit operator long*(C c) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,40): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (6,40): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "short*"),
// (7,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"));
}
[Fact]
public void UnsafePropertySignatures()
{
var template = @"
{0} interface I
{{
{1} int* P {{ get; set; }}
}}
{0} class C
{{
{1} int* P {{ get; set; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeIndexerSignatures()
{
var template = @"
{0} interface I
{{
{1} int* this[long* p, byte* q] {{ get; set; }}
}}
{0} class C
{{
{1} int* this[long* p, byte* q] {{ get {{ throw null; }} set {{ throw null; }} }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"));
}
[Fact]
public void UnsafeEventSignatures()
{
var template = @"
{0} interface I
{{
{1} event int* E;
}}
{0} class C
{{
{1} event int* E1;
{1} event int* E2 {{ add {{ }} remove {{ }} }}
}}
";
DiagnosticDescription[] expected =
{
// (4,17): error CS0066: 'I.E': event must be of a delegate type
Diagnostic(ErrorCode.ERR_EventNotDelegate, "E").WithArguments("I.E"),
// (9,17): error CS0066: 'C.E1': event must be of a delegate type
Diagnostic(ErrorCode.ERR_EventNotDelegate, "E1").WithArguments("C.E1"),
// (10,17): error CS0066: 'C.E2': event must be of a delegate type
Diagnostic(ErrorCode.ERR_EventNotDelegate, "E2").WithArguments("C.E2"),
// (9,17): warning CS0067: The event 'C.E1' is never used
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1")
};
CompareUnsafeDiagnostics(template, expected, expected);
}
[Fact]
public void UnsafeTypeArguments()
{
var template = @"
{0} interface I<T>
{{
{1} void Test(I<int*> i);
}}
{0} class C<T>
{{
{1} void Test(C<int*> c) {{ }}
}}
";
DiagnosticDescription[] expected =
{
// (4,24): error CS0306: The type 'int*' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "i").WithArguments("int*"),
// (9,24): error CS0306: The type 'int*' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "c").WithArguments("int*")
};
CompareUnsafeDiagnostics(template, expected, expected);
}
[Fact]
public void UnsafeExpressions1()
{
var template = @"
{0} class C
{{
void Test()
{{
{1}
{{
Unsafe(); //CS0214
}}
{1}
{{
var x = Unsafe(); //CS0214
}}
{1}
{{
var x = Unsafe(); //CS0214
var y = Unsafe(); //CS0214 suppressed
}}
{1}
{{
Unsafe(null); //CS0214
}}
}}
{1} int* Unsafe() {{ return null; }} //CS0214
{1} void Unsafe(int* p) {{ }} //CS0214
}}
";
CompareUnsafeDiagnostics(template,
// (28,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* Unsafe() { return null; } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (29,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// void Unsafe(int* p) { } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (13,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x = Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (18,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x = Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (19,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var y = Unsafe(); //CS0214 suppressed
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (24,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (24,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe(null)")
);
}
[Fact]
public void UnsafeExpressions2()
{
var template = @"
{0} class C
{{
{1} int* Field = Unsafe(); //CS0214 * 2
{1} C()
{{
Unsafe(); //CS0214
}}
{1} ~C()
{{
Unsafe(); //CS0214
}}
{1} void Test()
{{
Unsafe(); //CS0214
}}
{1} event System.Action E
{{
add {{ Unsafe(); }} //CS0214
remove {{ Unsafe(); }} //CS0214
}}
{1} int P
{{
set {{ Unsafe(); }} //CS0214
}}
{1} int this[int x]
{{
set {{ Unsafe(); }} //CS0214
}}
{1} public static implicit operator int(C c)
{{
Unsafe(); //CS0214
return 0;
}}
{1} public static C operator +(C c)
{{
Unsafe(); //CS0214
return c;
}}
{1} static int* Unsafe() {{ return null; }} //CS0214
}}
";
CompareUnsafeDiagnostics(template,
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* Field = Unsafe(); //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* Field = Unsafe(); //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (8,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (13,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (18,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (23,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// add { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (24,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// remove { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (29,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// set { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (34,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// set { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (39,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (45,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (49,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static int* Unsafe() { return null; } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeExpressions3()
{
var template = @"
{0} class C
{{
{1} void Test(int* p = Unsafe()) //CS0214 * 2
{{
System.Action a1 = () => Unsafe(); //CS0214
System.Action a2 = () =>
{{
Unsafe(); //CS0214
}};
}}
{1} static int* Unsafe() {{ return null; }} //CS0214
}}
";
DiagnosticDescription[] expectedWithoutUnsafe =
{
// (4,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (4,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Unsafe()").WithArguments("p"),
// (6,34): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// System.Action a1 = () => Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (10,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (14,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static int* Unsafe() { return null; } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
};
DiagnosticDescription[] expectedWithUnsafe =
{
// (4,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Unsafe()").WithArguments("p")
};
CompareUnsafeDiagnostics(template, expectedWithoutUnsafe, expectedWithUnsafe);
}
[Fact]
public void UnsafeIteratorSignatures()
{
var template = @"
{0} class C
{{
{1} System.Collections.Generic.IEnumerable<int> Iterator(int* p)
{{
yield return 1;
}}
}}
";
var withoutUnsafe = string.Format(template, "", "");
CreateCompilation(withoutUnsafe, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// CONSIDER: We should probably suppress CS0214 (like Dev10 does) because it's
// confusing, but we don't have a good way to do so, because we don't know that
// the method is an iterator until we bind the body and we certainly don't want
// to do that just to figure out the types of the parameters.
// (4,59): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"));
var withUnsafeOnType = string.Format(template, "unsafe", "");
CreateCompilation(withUnsafeOnType, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"));
var withUnsafeOnMembers = string.Format(template, "", "unsafe");
CreateCompilation(withUnsafeOnMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"),
// (4,56): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Iterator")); //this is for putting "unsafe" on an iterator, not for the parameter type
var withUnsafeOnTypeAndMembers = string.Format(template, "unsafe", "unsafe");
CreateCompilation(withUnsafeOnTypeAndMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"),
// (4,56): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Iterator")); //this is for putting "unsafe" on an iterator, not for the parameter type
}
[Fact]
public void UnsafeInAttribute1()
{
var text = @"
unsafe class Attr : System.Attribute
{
[Attr(null)] // Dev10: doesn't matter that the type and member are both 'unsafe'
public unsafe Attr(int* i)
{
}
}
";
// CONSIDER: Dev10 reports CS0214 (unsafe) and CS0182 (not a constant), but this makes
// just as much sense.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,6): error CS0181: Attribute constructor parameter 'i' has type 'int*', which is not a valid attribute parameter type
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("i", "int*"));
}
[Fact]
public void UnsafeInAttribute2()
{
var text = @"
unsafe class Attr : System.Attribute
{
[Attr(Unsafe() == null)] // Not a constant
public unsafe Attr(bool b)
{
}
static int* Unsafe()
{
return null;
}
}
";
// CONSIDER: Dev10 reports both CS0214 (unsafe) and CS0182 (not a constant), but this makes
// just as much sense.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Unsafe() == null"));
}
[Fact]
public void TypeofNeverUnsafe()
{
var text = @"
class C<T>
{
void Test()
{
System.Type t;
t = typeof(int*);
t = typeof(int**);
t = typeof(int*[]);
t = typeof(int*[][]);
t = typeof(C<int*>); // CS0306
t = typeof(C<int**>); // CS0306
t = typeof(C<int*[]>);
t = typeof(C<int*[][]>);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (13,22): error CS0306: The type 'int*' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*"),
// (14,22): error CS0306: The type 'int**' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "int**").WithArguments("int**"));
}
[Fact]
public void UnsafeOnEnum()
{
var text = @"
unsafe enum E
{
A
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (2,13): error CS0106: The modifier 'unsafe' is not valid for this item
Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("unsafe"));
}
[WorkItem(543834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543834")]
[Fact]
public void UnsafeOnDelegates()
{
var text = @"
public unsafe delegate void TestDelegate();
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics(
// (2,29): error CS0227: Unsafe code may only appear if compiling with /unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "TestDelegate"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[WorkItem(543835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543835")]
[Fact]
public void UnsafeOnConstField()
{
var text = @"
public class Main
{
unsafe public const int number = 0;
}
";
CreateCompilation(text).VerifyDiagnostics(
// (4,29): error CS0106: The modifier 'unsafe' is not valid for this item
Diagnostic(ErrorCode.ERR_BadMemberFlag, "number").WithArguments("unsafe"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,29): error CS0106: The modifier 'unsafe' is not valid for this item
Diagnostic(ErrorCode.ERR_BadMemberFlag, "number").WithArguments("unsafe"));
}
[Fact]
public void UnsafeOnExplicitInterfaceImplementation()
{
var text = @"
interface I
{
int P { get; set; }
void M();
event System.Action E;
}
class C : I
{
unsafe int I.P { get; set; }
unsafe void I.M() { }
unsafe event System.Action I.E { add { } remove { } }
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[WorkItem(544417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544417")]
[Fact]
public void UnsafeCallParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
{{ Goo(); }}
{{ Goo(null); }}
{{ Goo((int*)1); }}
{{ Goo(new int*[2]); }}
}}
{1} static void Goo(params int*[] x) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (12,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(params int*[] x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (6,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo()"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)"),
// (8,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo((int*)1)"),
// (9,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"),
// (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(new int*[2])")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeCallOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
{{ Goo(); }}
{{ Goo(null); }}
{{ Goo((int*)1); }}
}}
{1} static void Goo(int* p = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (11,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(int* p = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (6,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo()"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)"),
// (8,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo((int*)1)")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeDelegateCallParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
D d = null;
{{ d(); }}
{{ d(null); }}
{{ d((int*)1); }}
{{ d(new int*[2]); }}
}}
{1} delegate void D(params int*[] x);
}}
";
CompareUnsafeDiagnostics(template,
// (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void D(params int*[] x);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d()"),
// (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(null)"),
// (9,14): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d((int*)1)"),
// (10,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"),
// (10,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(new int*[2])")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeDelegateCallOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
D d = null;
{{ d(); }}
{{ d(null); }}
{{ d((int*)1); }}
}}
{1} delegate void D(int* p = null);
}}
";
CompareUnsafeDiagnostics(template,
// (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void D(int* p = null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d()"),
// (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(null)"),
// (9,14): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d((int*)1)")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeObjectCreationParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c;
{{ c = new C(); }}
{{ c = new C(null); }}
{{ c = new C((int*)1); }}
{{ c = new C(new int*[2]); }}
}}
{1} C(params int*[] x) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (13,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// C(params int*[] x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C()"),
// (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(null)"),
// (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C((int*)1)"),
// (10,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"),
// (10,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(new int*[2])")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeObjectCreationOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c;
{{ c = new C(); }}
{{ c = new C(null); }}
{{ c = new C((int*)1); }}
}}
{1} C(int* p = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (12,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// C(int* p = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C()"),
// (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(null)"),
// (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C((int*)1)")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeIndexerParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c = new C();
{{ int x = c[1]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, null]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, (int*)1]; }}
{{ int x = c[1, new int*[2]]; }}
}}
{1} int this[int x, params int*[] a] {{ get {{ return 0; }} set {{ }} }}
}}
";
CompareUnsafeDiagnostics(template,
// (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int this[int x, params int*[] a] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (10,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, new int*[2]]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, new int*[2]]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeIndexerOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c = new C();
{{ int x = c[1]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, null]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, (int*)1]; }}
}}
{1} int this[int x, int* p = null] {{ get {{ return 0; }} set {{ }} }}
}}
";
CompareUnsafeDiagnostics(template,
// (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int this[int x, int* p = null] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeAttributeParamArrays()
{
var template = @"
[A]
{0} class A : System.Attribute
{{
{1} A(params int*[] a) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'a' has type 'int*[]', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "int*[]"),
// (5,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// A(params int*[] a) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
},
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'a' has type 'int*[]', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "int*[]")
});
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeAttributeOptionalParameters()
{
var template = @"
[A]
{0} class A : System.Attribute
{{
{1} A(int* p = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'p' has type 'int*', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("p", "int*"),
// (5,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// A(int* p = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
},
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'p' has type 'int*', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("p", "int*")
});
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeDelegateAssignment()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
D d;
{{ d = delegate {{ }}; }}
{{ d = null; }}
{{ d = Goo; }}
}}
{1} delegate void D(int* x = null);
{1} static void Goo(int* x = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d = Goo; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo"),
// (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void D(int* x = null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (13,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(int* x = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
private static void CompareUnsafeDiagnostics(string template, params DiagnosticDescription[] expectedWithoutUnsafe)
{
CompareUnsafeDiagnostics(template, expectedWithoutUnsafe, new DiagnosticDescription[0]);
}
private static void CompareUnsafeDiagnostics(string template, DiagnosticDescription[] expectedWithoutUnsafe, DiagnosticDescription[] expectedWithUnsafe)
{
// NOTE: ERR_UnsafeNeeded is not affected by the presence/absence of the /unsafe flag.
var withoutUnsafe = string.Format(template, "", "");
CreateCompilation(withoutUnsafe).VerifyDiagnostics(expectedWithoutUnsafe);
CreateCompilation(withoutUnsafe, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithoutUnsafe);
var withUnsafeOnType = string.Format(template, "unsafe", "");
CreateCompilation(withUnsafeOnType, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe);
var withUnsafeOnMembers = string.Format(template, "", "unsafe");
CreateCompilation(withUnsafeOnMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe);
var withUnsafeOnTypeAndMembers = string.Format(template, "unsafe", "unsafe");
CreateCompilation(withUnsafeOnTypeAndMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe);
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void MethodCallWithNullAsPointerArg()
{
var template = @"
{0} class Test
{{
{1} static void Goo(void* p) {{ }}
{1} static void Main()
{{
Goo(null);
}}
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(void* p) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"),
// (7,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Goo(null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (7,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Goo(null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)")
);
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void MethodCallWithUnsafeArgument()
{
var template = @"
{0} class Test
{{
{1} int M(params int*[] p) {{ return 0; }}
{1} public static implicit operator int*(Test t) {{ return null; }}
{1} void M()
{{
{{
int x = M(null); //CS0214
}}
{{
int x = M(null, null); //CS0214
}}
{{
int x = M(this); //CS0214
}}
}}
}}
";
CompareUnsafeDiagnostics(template,
// (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public static implicit operator int*(Test t) { return null; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int M(params int*[] p) { return 0; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (10,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(null)"),
// (13,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null, null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null, null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (13,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null, null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(null, null)"),
// (16,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(this); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "this"),
// (16,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(this); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(this)")
);
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void IndexerAccessWithUnsafeArgument()
{
var template = @"
{0} class Test
{{
{1} int this[params int*[] p] {{ get {{ return 0; }} set {{ }} }}
{1} public static implicit operator int*(Test t) {{ return null; }}
{1} void M()
{{
{{
int x = this[null]; //CS0214 seems appropriate, but dev10 accepts
}}
{{
int x = this[null, null]; //CS0214 seems appropriate, but dev10 accepts
}}
{{
int x = this[this]; //CS0214 seems appropriate, but dev10 accepts
}}
}}
}}
";
CompareUnsafeDiagnostics(template,
// (4,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int this[int* p] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public static implicit operator int*(Test t) { return null; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void ConstructorInitializerWithUnsafeArgument()
{
var template = @"
{0} class Base
{{
{1} public Base(int* p) {{ }}
}}
{0} class Derived : Base
{{
{1} public Derived() : base(null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public Base(int* p) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public Derived() : base(null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public Derived() : base(null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "base")
);
}
[WorkItem(544286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544286")]
[Fact]
public void UnsafeLambdaParameterType()
{
var template = @"
{0} class Program
{{
{1} delegate void F(int* x);
{1} static void Main()
{{
F e = x => {{ }};
}}
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void F(int* x);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// F e = x => { };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "x"));
}
#endregion Unsafe regions
#region Variables that need fixing
[Fact]
public void FixingVariables_Parameters()
{
var text = @"
class C
{
void M(int x, ref int y, out int z, params int[] p)
{
M(x, ref y, out z, p);
}
}
";
var expected = @"
Yes, Call 'M(x, ref y, out z, p)' requires fixing.
Yes, ThisReference 'M' requires fixing.
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
Yes, Parameter 'y' requires fixing.
Yes, Parameter 'z' requires fixing.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Locals()
{
var text = @"
class C
{
void M(params object[] p)
{
C c = null;
int x = 0;
M(c, x);
}
}
";
var expected = @"
Yes, TypeExpression 'C' requires fixing.
Yes, Conversion 'null' requires fixing.
Yes, Literal 'null' requires fixing.
Yes, TypeExpression 'int' requires fixing.
Yes, Literal '0' requires fixing.
Yes, Call 'M(c, x)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'x' requires fixing.
No, Local 'x' does not require fixing. It has an underlying symbol 'x'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields1()
{
var text = @"
class C
{
public S1 s;
public C c;
void M(params object[] p)
{
C c = new C();
S1 s = new S1();
M(this, this.s, this.s.s, this.s.c, this.c.s, this.c.c);
M(c, c.s, c.s.s, c.s.c, c.c.s, c.c.c);
M(s, s.s, s.s.i);
}
}
struct S1
{
public S2 s;
public C c;
}
struct S2
{
public int i;
}
";
var expected = @"
Yes, TypeExpression 'C' requires fixing.
Yes, ObjectCreationExpression 'new C()' requires fixing.
Yes, TypeExpression 'S1' requires fixing.
Yes, ObjectCreationExpression 'new S1()' requires fixing.
Yes, Call 'M(this, this.s, this.s.s, this.s.c, this.c.s, this.c.c)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'this' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.s' requires fixing.
Yes, FieldAccess 'this.s' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.s.s' requires fixing.
Yes, FieldAccess 'this.s.s' requires fixing.
Yes, FieldAccess 'this.s' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.s.c' requires fixing.
Yes, FieldAccess 'this.s.c' requires fixing.
Yes, FieldAccess 'this.s' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.c.s' requires fixing.
Yes, FieldAccess 'this.c.s' requires fixing.
Yes, FieldAccess 'this.c' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.c.c' requires fixing.
Yes, FieldAccess 'this.c.c' requires fixing.
Yes, FieldAccess 'this.c' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Call 'M(c, c.s, c.s.s, c.s.c, c.c.s, c.c.c)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.s' requires fixing.
Yes, FieldAccess 'c.s' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.s.s' requires fixing.
Yes, FieldAccess 'c.s.s' requires fixing.
Yes, FieldAccess 'c.s' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.s.c' requires fixing.
Yes, FieldAccess 'c.s.c' requires fixing.
Yes, FieldAccess 'c.s' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.c.s' requires fixing.
Yes, FieldAccess 'c.c.s' requires fixing.
Yes, FieldAccess 'c.c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.c.c' requires fixing.
Yes, FieldAccess 'c.c.c' requires fixing.
Yes, FieldAccess 'c.c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Call 'M(s, s.s, s.s.i)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 's' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
Yes, Conversion 's.s' requires fixing.
No, FieldAccess 's.s' does not require fixing. It has an underlying symbol 's'
No, Local 's' does not require fixing. It has an underlying symbol 's'
Yes, Conversion 's.s.i' requires fixing.
No, FieldAccess 's.s.i' does not require fixing. It has an underlying symbol 's'
No, FieldAccess 's.s' does not require fixing. It has an underlying symbol 's'
No, Local 's' does not require fixing. It has an underlying symbol 's'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields2()
{
var text = @"
class Base
{
public int i;
}
class Derived : Base
{
void M()
{
base.i = 0;
}
}
";
var expected = @"
Yes, AssignmentOperator 'base.i = 0' requires fixing.
Yes, FieldAccess 'base.i' requires fixing.
Yes, BaseReference 'base' requires fixing.
Yes, Literal '0' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields3()
{
var text = @"
struct S
{
static int i;
void M()
{
S.i = 0;
}
}
";
var expected = @"
Yes, AssignmentOperator 'S.i = 0' requires fixing.
Yes, FieldAccess 'S.i' requires fixing.
Yes, TypeExpression 'S' requires fixing.
Yes, Literal '0' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields4()
{
var text = @"
struct S
{
int i;
void M(params object[] p)
{
// rvalues always require fixing.
M(new S().i, default(S).i, MakeS().i, (new S[1])[0].i);
}
S MakeS()
{
return default(S);
}
}
";
var expected = @"
Yes, Call 'M(new S().i, default(S).i, MakeS().i, (new S[1])[0].i)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'new S().i' requires fixing.
Yes, FieldAccess 'new S().i' requires fixing.
Yes, ObjectCreationExpression 'new S()' requires fixing.
Yes, Conversion 'default(S).i' requires fixing.
Yes, FieldAccess 'default(S).i' requires fixing.
Yes, DefaultExpression 'default(S)' requires fixing.
Yes, Conversion 'MakeS().i' requires fixing.
Yes, FieldAccess 'MakeS().i' requires fixing.
Yes, Call 'MakeS()' requires fixing.
Yes, ThisReference 'MakeS' requires fixing.
Yes, Conversion '(new S[1])[0].i' requires fixing.
Yes, FieldAccess '(new S[1])[0].i' requires fixing.
Yes, ArrayAccess '(new S[1])[0]' requires fixing.
Yes, ArrayCreation 'new S[1]' requires fixing.
Yes, Literal '1' requires fixing.
Yes, Literal '0' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Events()
{
var text = @"
struct S
{
public event System.Action E;
public event System.Action F { add { } remove { } }
void M(params object[] p)
{
C c = new C();
S s = new S();
M(c.E, c.F); //note: note legal to pass F
M(s.E, s.F); //note: note legal to pass F
}
}
class C
{
public event System.Action E;
public event System.Action F { add { } remove { } }
}
";
var expected = @"
Yes, TypeExpression 'C' requires fixing.
Yes, ObjectCreationExpression 'new C()' requires fixing.
Yes, TypeExpression 'S' requires fixing.
Yes, ObjectCreationExpression 'new S()' requires fixing.
Yes, Call 'M(c.E, c.F)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'c.E' requires fixing.
Yes, BadExpression 'c.E' requires fixing.
Yes, EventAccess 'c.E' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.F' requires fixing.
Yes, BadExpression 'c.F' requires fixing.
Yes, EventAccess 'c.F' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Call 'M(s.E, s.F)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 's.E' requires fixing.
No, EventAccess 's.E' does not require fixing. It has an underlying symbol 's'
No, Local 's' does not require fixing. It has an underlying symbol 's'
Yes, Conversion 's.F' requires fixing.
Yes, BadExpression 's.F' requires fixing.
Yes, EventAccess 's.F' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
".Trim();
CheckIfVariablesNeedFixing(text, expected, expectError: true);
}
[Fact]
public void FixingVariables_Lambda1()
{
var text = @"
class C
{
void M(params object[] p)
{
int i = 0; // NOTE: does not require fixing even though it will be hoisted - lambdas handled separately.
i++;
System.Action a = () =>
{
int j = i;
j++;
};
}
}
";
var expected = string.Format(@"
Yes, TypeExpression 'int' requires fixing.
Yes, Literal '0' requires fixing.
Yes, IncrementOperator 'i++' requires fixing.
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
Yes, TypeExpression 'System.Action' requires fixing.
Yes, Conversion '() =>{0} {{{0} int j = i;{0} j++;{0} }}' requires fixing.
Yes, Lambda '() =>{0} {{{0} int j = i;{0} j++;{0} }}' requires fixing.
Yes, TypeExpression 'int' requires fixing.
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
Yes, IncrementOperator 'j++' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
", GetEscapedNewLine()).Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Lambda2()
{
var text = @"
class C
{
void M()
{
int i = 0; // NOTE: does not require fixing even though it will be hoisted - lambdas handled separately.
i++;
System.Func<int, System.Func<int, int>> a = p => q => p + q + i;
}
}
";
var expected = @"
Yes, TypeExpression 'int' requires fixing.
Yes, Literal '0' requires fixing.
Yes, IncrementOperator 'i++' requires fixing.
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
Yes, TypeExpression 'System.Func<int, System.Func<int, int>>' requires fixing.
Yes, Conversion 'p => q => p + q + i' requires fixing.
Yes, Lambda 'p => q => p + q + i' requires fixing.
Yes, Conversion 'q => p + q + i' requires fixing.
Yes, Lambda 'q => p + q + i' requires fixing.
Yes, BinaryOperator 'p + q + i' requires fixing.
Yes, BinaryOperator 'p + q' requires fixing.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
No, Parameter 'q' does not require fixing. It has an underlying symbol 'q'
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Dereference()
{
var text = @"
struct S
{
int i;
unsafe void Test(S* p)
{
S s;
s = *p;
s = p[0];
int j;
j = (*p).i;
j = p[0].i;
j = p->i;
}
}
";
var expected = @"
Yes, TypeExpression 'S' requires fixing.
Yes, AssignmentOperator 's = *p' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
No, PointerIndirectionOperator '*p' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, AssignmentOperator 's = p[0]' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
No, PointerElementAccess 'p[0]' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, Literal '0' requires fixing.
Yes, TypeExpression 'int' requires fixing.
Yes, AssignmentOperator 'j = (*p).i' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
No, FieldAccess '(*p).i' does not require fixing. It has no underlying symbol.
No, PointerIndirectionOperator '*p' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, AssignmentOperator 'j = p[0].i' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
No, FieldAccess 'p[0].i' does not require fixing. It has no underlying symbol.
No, PointerElementAccess 'p[0]' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, Literal '0' requires fixing.
Yes, AssignmentOperator 'j = p->i' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
No, FieldAccess 'p->i' does not require fixing. It has no underlying symbol.
No, PointerIndirectionOperator 'p' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_StackAlloc()
{
var text = @"
struct S
{
unsafe void Test()
{
int* p = stackalloc int[1];
}
}
";
var expected = @"
Yes, TypeExpression 'int*' requires fixing.
No, ConvertedStackAllocExpression 'stackalloc int[1]' does not require fixing. It has no underlying symbol.
Yes, Literal '1' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_TypeParameters1()
{
var text = @"
class C
{
public C c;
void M<T>(T t, C c) where T : C
{
M(t, t.c);
}
}
";
var expected = @"
Yes, Call 'M(t, t.c)' requires fixing.
Yes, ThisReference 'M' requires fixing.
No, Parameter 't' does not require fixing. It has an underlying symbol 't'
Yes, FieldAccess 't.c' requires fixing.
No, Parameter 't' does not require fixing. It has an underlying symbol 't'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_TypeParameters2()
{
var text = @"
class D : C<S>
{
public override void M<U>(U u, int j)
{
M(u, u.i); // effective base type (System.ValueType) does not have a member 'i'
}
}
abstract class C<T>
{
public abstract void M<U>(U u, int i) where U : T;
}
struct S
{
public int i;
}
";
var expected = @"
Yes, Call 'M(u, u.i)' requires fixing.
Yes, ThisReference 'M' requires fixing.
No, Parameter 'u' does not require fixing. It has an underlying symbol 'u'
Yes, BadExpression 'u.i' requires fixing.
No, Parameter 'u' does not require fixing. It has an underlying symbol 'u'
".Trim();
CheckIfVariablesNeedFixing(text, expected, expectError: true);
}
[Fact]
public void FixingVariables_RangeVariables1()
{
var text = @"
using System.Linq;
class C
{
void M(int[] array)
{
var result =
from i in array
from j in array
select i + j;
}
}
";
var expected = string.Format(@"
Yes, TypeExpression 'var' requires fixing.
Yes, QueryClause 'from i in array {0} from j in array {0} select i + j' requires fixing.
Yes, QueryClause 'select i + j' requires fixing.
Yes, QueryClause 'from j in array' requires fixing.
Yes, Call 'from j in array' requires fixing.
Yes, Conversion 'from i in array' requires fixing.
Yes, QueryClause 'from i in array' requires fixing.
No, Parameter 'array' does not require fixing. It has an underlying symbol 'array'
Yes, QueryClause 'from j in array' requires fixing.
Yes, Conversion 'array' requires fixing.
Yes, Lambda 'array' requires fixing.
Yes, Conversion 'array' requires fixing.
No, Parameter 'array' does not require fixing. It has an underlying symbol 'array'
Yes, Conversion 'i + j' requires fixing.
Yes, Lambda 'i + j' requires fixing.
Yes, BinaryOperator 'i + j' requires fixing.
No, RangeVariable 'i' does not require fixing. It has an underlying symbol 'i'
No, Parameter 'i' does not require fixing. It has an underlying symbol 'i'
No, RangeVariable 'j' does not require fixing. It has an underlying symbol 'j'
No, Parameter 'j' does not require fixing. It has an underlying symbol 'j'
", GetEscapedNewLine()).Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_RangeVariables2()
{
var text = @"
using System;
class Test
{
void M(C c)
{
var result = from x in c
where x > 0 //int
where x.Length < 2 //string
select char.IsLetter(x); //char
}
}
class C
{
public D Where(Func<int, bool> predicate)
{
return new D();
}
}
class D
{
public char[] Where(Func<string, bool> predicate)
{
return new char[10];
}
}
static class Extensions
{
public static object Select(this char[] array, Func<char, bool> func)
{
return null;
}
}
";
var expected = string.Format(@"
Yes, TypeExpression 'var' requires fixing.
Yes, QueryClause 'from x in c{0} where x > 0 //int{0} where x.Length < 2 //string{0} select char.IsLetter(x)' requires fixing.
Yes, QueryClause 'select char.IsLetter(x)' requires fixing.
Yes, Call 'select char.IsLetter(x)' requires fixing.
Yes, QueryClause 'where x.Length < 2' requires fixing.
Yes, Call 'where x.Length < 2' requires fixing.
Yes, QueryClause 'where x > 0' requires fixing.
Yes, Call 'where x > 0' requires fixing.
Yes, QueryClause 'from x in c' requires fixing.
No, Parameter 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'x > 0' requires fixing.
Yes, Lambda 'x > 0' requires fixing.
Yes, BinaryOperator 'x > 0' requires fixing.
No, RangeVariable 'x' does not require fixing. It has an underlying symbol 'x'
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
Yes, Literal '0' requires fixing.
Yes, Conversion 'x.Length < 2' requires fixing.
Yes, Lambda 'x.Length < 2' requires fixing.
Yes, BinaryOperator 'x.Length < 2' requires fixing.
Yes, PropertyAccess 'x.Length' requires fixing.
No, RangeVariable 'x' does not require fixing. It has an underlying symbol 'x'
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
Yes, Literal '2' requires fixing.
Yes, Conversion 'char.IsLetter(x)' requires fixing.
Yes, Lambda 'char.IsLetter(x)' requires fixing.
Yes, Call 'char.IsLetter(x)' requires fixing.
Yes, TypeExpression 'char' requires fixing.
No, RangeVariable 'x' does not require fixing. It has an underlying symbol 'x'
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
", GetEscapedNewLine()).Trim();
CheckIfVariablesNeedFixing(text, expected);
}
private static void CheckIfVariablesNeedFixing(string text, string expected, bool expectError = false)
{
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll);
var compilationDiagnostics = compilation.GetDiagnostics();
if (expectError != compilationDiagnostics.Any(diag => diag.Severity == DiagnosticSeverity.Error))
{
compilationDiagnostics.Verify();
Assert.True(false);
}
var tree = compilation.SyntaxTrees.Single();
var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
var methodBody = methodDecl.Body;
var model = compilation.GetSemanticModel(tree);
var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(methodBody.SpanStart);
Assert.NotNull(binder);
Assert.Equal(SymbolKind.Method, binder.ContainingMemberOrLambda.Kind);
var unusedDiagnostics = DiagnosticBag.GetInstance();
var block = binder.BindEmbeddedBlock(methodBody, unusedDiagnostics);
unusedDiagnostics.Free();
var builder = ArrayBuilder<string>.GetInstance();
CheckFixingVariablesVisitor.Process(block, binder, builder);
var actual = string.Join(Environment.NewLine, builder);
Assert.Equal(expected, actual);
builder.Free();
}
private class CheckFixingVariablesVisitor : BoundTreeWalkerWithStackGuard
{
private readonly Binder _binder;
private readonly ArrayBuilder<string> _builder;
private CheckFixingVariablesVisitor(Binder binder, ArrayBuilder<string> builder)
{
_binder = binder;
_builder = builder;
}
public static void Process(BoundBlock block, Binder binder, ArrayBuilder<string> builder)
{
var visitor = new CheckFixingVariablesVisitor(binder, builder);
visitor.Visit(block);
}
public override BoundNode Visit(BoundNode node)
{
var expr = node as BoundExpression;
if (expr != null)
{
var text = node.Syntax.ToString();
if (!string.IsNullOrEmpty(text))
{
text = SymbolDisplay.FormatLiteral(text, quote: false);
if (_binder.IsMoveableVariable(expr, out Symbol accessedLocalOrParameterOpt))
{
_builder.Add($"Yes, {expr.Kind} '{text}' requires fixing.");
}
else
{
_builder.Add(string.Concat($"No, {expr.Kind} '{text}' does not require fixing.", accessedLocalOrParameterOpt is null
? " It has no underlying symbol."
: $" It has an underlying symbol '{accessedLocalOrParameterOpt.Name}'"));
}
}
}
return base.Visit(node);
}
protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()
{
return false;
}
}
#endregion Variables that need fixing
#region IsManagedType
[Fact]
public void IsManagedType_Array()
{
var text = @"
class C
{
int[] f1;
int[,] f2;
int[][] f3;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Pointer()
{
var text = @"
unsafe class C
{
int* f1;
int** f2;
void* f3;
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => !field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Dynamic()
{
var text = @"
class C
{
dynamic f1;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Error()
{
var text = @"
class C<T>
{
C f1;
C<int, int> f2;
Garbage f3;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_TypeParameter()
{
var text = @"
class C<T, U> where U : struct
{
T f1;
U f2;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_AnonymousType()
{
var text = @"
class C
{
void M()
{
var local1 = new { };
var local2 = new { F = 1 };
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.True(tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().
Select(syntax => model.GetTypeInfo(syntax).Type).All(type => type.GetSymbol().IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Class()
{
var text = @"
class Outer
{
Outer f1;
Outer.Inner f2;
string f3;
class Inner { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_GenericClass()
{
var text = @"
class Outer<T>
{
Outer<T> f1;
Outer<T>.Inner f2;
Outer<int> f1;
Outer<string>.Inner f2;
class Inner { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_ManagedSpecialTypes()
{
var text = @"
class C
{
object f1;
string f2;
System.Collections.IEnumerable f3;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
foreach (var field in type.GetMembers().OfType<FieldSymbol>())
{
Assert.True(field.Type.IsManagedTypeNoUseSiteDiagnostics, field.ToString());
}
}
[Fact]
public void IsManagedType_NonManagedSpecialTypes()
{
var text = @"
class C
{
bool f1;
char f2;
sbyte f3;
byte f4;
short f5;
ushort f6;
int f7;
uint f8;
long f9;
ulong f10;
decimal f11;
float f12;
double f13;
System.IntPtr f14;
System.UIntPtr f15;
int? f16;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => !field.Type.IsManagedTypeNoUseSiteDiagnostics));
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetField("f16").Type.ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_Void()
{
var text = @"
class C
{
void M() { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var method = type.GetMember<MethodSymbol>("M");
Assert.False(method.ReturnType.IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_Enum()
{
var text = @"
enum E { A }
class C
{
enum E { A }
}
class D<T>
{
enum E { A }
}
struct S
{
enum E { A }
}
struct R<T>
{
enum E { A }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("R").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_EmptyStruct()
{
var text = @"
struct S { }
struct P<T> { }
class C
{
struct S { }
}
class D<T>
{
struct S { }
}
struct Q
{
struct S { }
}
struct R<T>
{
struct S { }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Unmanaged, globalNamespace.GetMember<NamedTypeSymbol>("S").ManagedKindNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("P").IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, globalNamespace.GetMember<NamedTypeSymbol>("P").ManagedKindNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("Q").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("R").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_SubstitutedStruct()
{
var text = @"
class C<U>
{
S<U> f1;
S<int> f2;
S<U>.R f3;
S<int>.R f4;
S<U>.R2 f5;
S<int>.R2 f6;
}
struct S<T>
{
struct R { }
internal struct R2 { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.False(type.GetMember<FieldSymbol>("f1").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f1").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f2").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f2").Type.ManagedKindNoUseSiteDiagnostics);
// these are managed due to S`1.R being ErrorType due to protection level (CS0169)
Assert.True(type.GetMember<FieldSymbol>("f3").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Managed, type.GetMember<FieldSymbol>("f3").Type.ManagedKindNoUseSiteDiagnostics);
Assert.True(type.GetMember<FieldSymbol>("f4").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Managed, type.GetMember<FieldSymbol>("f4").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f5").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f5").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f6").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f6").Type.ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_GenericStruct()
{
var text = @"
class C<U>
{
S<object> f1;
S<int> f2;
}
struct S<T>
{
T field;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMember<FieldSymbol>("f1").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Managed, type.GetMember<FieldSymbol>("f1").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f2").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f2").Type.ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_GenericStruct_ErrorTypeArg()
{
var text = @"
class C<U>
{
S<Widget> f1;
}
struct S<T>
{
T field;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMember<FieldSymbol>("f1").Type.IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_NonEmptyStruct()
{
var text = @"
struct S1
{
int f;
}
struct S2
{
object f;
}
struct S3
{
S1 s;
}
struct S4
{
S2 s;
}
struct S5
{
S1 s1;
S2 s2;
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_StaticFieldStruct()
{
var text = @"
struct S1
{
static object o;
int f;
}
struct S2
{
static object o;
object f;
}
struct S3
{
static object o;
S1 s;
}
struct S4
{
static object o;
S2 s;
}
struct S5
{
static object o;
S1 s1;
S2 s2;
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_AutoPropertyStruct()
{
var text = @"
struct S1
{
int f { get; set; }
}
struct S2
{
object f { get; set; }
}
struct S3
{
S1 s { get; set; }
}
struct S4
{
S2 s { get; set; }
}
struct S5
{
S1 s1 { get; set; }
S2 s2 { get; set; }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_PropertyStruct()
{
var text = @"
struct S1
{
object o { get { return null; } set { } }
int f { get; set; }
}
struct S2
{
object o { get { return null; } set { } }
object f { get; set; }
}
struct S3
{
object o { get { return null; } set { } }
S1 s { get; set; }
}
struct S4
{
object o { get { return null; } set { } }
S2 s { get; set; }
}
struct S5
{
object o { get { return null; } set { } }
S1 s1 { get; set; }
S2 s2 { get; set; }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_EventStruct()
{
var text = @"
struct S1
{
event System.Action E; // has field
}
struct S2
{
event System.Action E { add { } remove { } } // no field
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_ExpandingStruct()
{
var text = @"
struct X<T> { public T t; }
struct W<T> { X<W<W<T>>> x; }
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("X").IsManagedTypeNoUseSiteDiagnostics); // because of X.t
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("W").IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, globalNamespace.GetMember<NamedTypeSymbol>("W").ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_CyclicStruct()
{
var text = @"
struct S
{
S s;
}
struct R
{
object o;
S s;
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("R").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_CyclicStructChain()
{
var text = @"
struct Q { R r; }
struct R { A a; object o }
struct S { A a; }
//cycle
struct A { B b; }
struct B { C c; }
struct C { D d; }
struct D { A a; }
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("Q").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("R").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_SpecialClrTypes()
{
var text = @"
class C { }
";
var compilation = CreateCompilation(text);
Assert.False(compilation.GetSpecialType(SpecialType.System_ArgIterator).IsManagedTypeNoUseSiteDiagnostics);
Assert.False(compilation.GetSpecialType(SpecialType.System_RuntimeArgumentHandle).IsManagedTypeNoUseSiteDiagnostics);
Assert.False(compilation.GetSpecialType(SpecialType.System_TypedReference).IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void ERR_ManagedAddr_ShallowRecursive()
{
var text = @"
public unsafe struct S1
{
public S1* s; //CS0208
public object o;
}
public unsafe struct S2
{
public S2* s; //fine
public int i;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S1')
// public S1* s; //CS0523
Diagnostic(ErrorCode.ERR_ManagedAddr, "s").WithArguments("S1"));
}
[Fact]
public void ERR_ManagedAddr_DeepRecursive()
{
var text = @"
public unsafe struct A
{
public B** bb; //CS0208
public object o;
public struct B
{
public C*[] cc; //CS0208
public struct C
{
public A*[,][] aa; //CS0208
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A')
// public A*[,][] aa; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "aa").WithArguments("A"),
// (9,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A.B.C')
// public C*[] cc; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "cc").WithArguments("A.B.C"),
// (4,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A.B')
// public B** bb; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "bb").WithArguments("A.B"));
}
[Fact]
public void ERR_ManagedAddr_Alias()
{
var text = @"
using Alias = S;
public unsafe struct S
{
public Alias* s; //CS0208
public object o;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// public Alias* s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "s").WithArguments("S"));
}
[Fact()]
public void ERR_ManagedAddr_Members()
{
var text = @"
public unsafe struct S
{
S* M() { return M(); }
void M(S* p) { }
S* P { get; set; }
S* this[int x] { get { return M(); } set { } }
int this[S* p] { get { return 0; } set { } }
public S* s; //CS0208
public object o;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* M() { return M(); }
Diagnostic(ErrorCode.ERR_ManagedAddr, "M").WithArguments("S"),
// (5,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// void M(S* p) { }
Diagnostic(ErrorCode.ERR_ManagedAddr, "p").WithArguments("S"),
// (7,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* P { get; set; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "P").WithArguments("S"),
// (9,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* this[int x] { get { return M(); } set { } }
Diagnostic(ErrorCode.ERR_ManagedAddr, "this").WithArguments("S"),
// (10,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// int this[S* p] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_ManagedAddr, "p").WithArguments("S"),
// (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// public S* s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "s").WithArguments("S"));
}
[WorkItem(10195, "https://github.com/dotnet/roslyn/issues/10195")]
[Fact]
public void PointerToStructInPartialMethodSignature()
{
string text =
@"unsafe partial struct S
{
partial void M(S *p) { }
partial void M(S *p);
}";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void IsUnmanagedTypeSemanticModel()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
struct S1 { }
struct S2 { public S1 F1; }
struct S3 { public object F1; }
struct S4<T> { public T F1; }
struct S5<T> where T : unmanaged { public T F1; }
enum E1 { }
class C<T>
{
unsafe void M<U>() where U : unmanaged
{
var s1 = new S1();
var s2 = new S2();
var s3 = new S3();
var s4_0 = new S4<int>();
var s4_1 = new S4<object>();
var s4_2 = new S4<U>();
var s5 = new S5<int>();
var i0 = 0;
var e1 = new E1();
var o1 = new object();
var c1 = new C<int>;
var t1 = default(T);
var u1 = default(U);
void* p1 = null;
var a1 = new { X = 0 };
var a2 = new int[1];
var t2 = (0, 0);
}
}");
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var root = tree.GetRoot();
// The spec states the following are unmanaged types:
// sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
// Any enum_type.
// Any pointer_type.
// Any user-defined struct_type that contains fields of unmanaged_types only.
// A type parameter with an unmanaged constraint
Assert.True(getLocalType("s1").IsUnmanagedType);
Assert.True(getLocalType("s2").IsUnmanagedType);
Assert.False(getLocalType("s3").IsUnmanagedType);
Assert.True(getLocalType("s4_0").IsUnmanagedType);
Assert.False(getLocalType("s4_1").IsUnmanagedType);
Assert.True(getLocalType("s4_2").IsUnmanagedType);
Assert.True(getLocalType("s5").IsUnmanagedType);
Assert.True(getLocalType("i0").IsUnmanagedType);
Assert.True(getLocalType("e1").IsUnmanagedType);
Assert.False(getLocalType("o1").IsUnmanagedType);
Assert.False(getLocalType("c1").IsUnmanagedType);
Assert.False(getLocalType("t1").IsUnmanagedType);
Assert.True(getLocalType("u1").IsUnmanagedType);
Assert.True(getLocalType("p1").IsUnmanagedType);
Assert.False(getLocalType("a1").IsUnmanagedType);
Assert.False(getLocalType("a2").IsUnmanagedType);
Assert.True(getLocalType("t2").IsUnmanagedType);
ITypeSymbol getLocalType(string name)
{
var decl = root.DescendantNodes()
.OfType<VariableDeclaratorSyntax>()
.Single(n => n.Identifier.ValueText == name);
return ((ILocalSymbol)model.GetDeclaredSymbol(decl)).Type;
}
}
[Fact]
public void GenericStructPrivateFieldInMetadata()
{
var externalCode = @"
public struct External<T>
{
private T field;
}
";
var metadata = CreateCompilation(externalCode).EmitToImageReference();
var code = @"
public class C
{
public unsafe void M<T, U>() where T : unmanaged
{
var good = new External<int>();
var goodPtr = &good;
var good2 = new External<T>();
var goodPtr2 = &good2;
var bad = new External<object>();
var badPtr = &bad;
var bad2 = new External<U>();
var badPtr2 = &bad2;
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(code, TestOptions.Regular);
var compilation = CreateCompilation(tree, new[] { metadata }, TestOptions.UnsafeReleaseDll);
compilation.VerifyDiagnostics(
// (13,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('External<object>')
// var badPtr = &bad;
Diagnostic(ErrorCode.ERR_ManagedAddr, "&bad").WithArguments("External<object>").WithLocation(13, 22),
// (16,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('External<U>')
// var badPtr2 = &bad2;
Diagnostic(ErrorCode.ERR_ManagedAddr, "&bad2").WithArguments("External<U>").WithLocation(16, 23)
);
var model = compilation.GetSemanticModel(tree);
var root = tree.GetRoot();
Assert.True(getLocalType("good").IsUnmanagedType);
Assert.True(getLocalType("good2").IsUnmanagedType);
Assert.False(getLocalType("bad").IsUnmanagedType);
Assert.False(getLocalType("bad2").IsUnmanagedType);
ITypeSymbol getLocalType(string name)
{
var decl = root.DescendantNodes()
.OfType<VariableDeclaratorSyntax>()
.Single(n => n.Identifier.ValueText == name);
return ((ILocalSymbol)model.GetDeclaredSymbol(decl)).Type;
}
}
#endregion IsManagedType
#region AddressOf operand kinds
[Fact]
public void AddressOfExpressionKinds_Simple()
{
var text = @"
unsafe class C
{
void M(int param)
{
int local;
int* p;
p = ¶m;
p = &local;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void AddressOfExpressionKinds_Dereference()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
p = &(*p);
p = &p[0];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void AddressOfExpressionKinds_Struct()
{
var text = @"
unsafe class C
{
void M()
{
S1 s;
S1* p1 = &s;
S2* p2 = &s.s;
S3* p3 = &s.s.s;
int* p4 = &s.s.s.x;
p2 = &(p1->s);
p3 = &(p2->s);
p4 = &(p3->x);
p2 = &((*p1).s);
p3 = &((*p2).s);
p4 = &((*p3).x);
}
}
struct S1
{
public S2 s;
}
struct S2
{
public S3 s;
}
struct S3
{
public int x;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[WorkItem(529267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529267")]
[Fact]
public void AddressOfExpressionKinds_RangeVariable()
{
var text = @"
using System.Linq;
unsafe class C
{
int M(int param)
{
var z = from x in new int[2] select Goo(&x);
return 0;
}
int Goo(int* p) { return 0; }
}
";
// NOTE: this is a breaking change - dev10 allows this.
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,50): error CS0211: Cannot take the address of the given expression
// var z = from x in new int[2] select Goo(&x);
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "x").WithArguments("x"));
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void AddressOfExpressionKinds_ReadOnlyLocal()
{
var text = @"
class Test { static void Main() { } }
unsafe class C
{
int[] array;
void M()
{
int* p;
const int x = 1;
p = &x; //CS0211
foreach (int y in new int[1])
{
p = &y;
}
using (S s = new S())
{
S* sp = &s;
}
fixed (int* a = &array[0])
{
int** pp = &a;
}
}
}
struct S : System.IDisposable
{
public void Dispose() { }
}
";
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,14): error CS0211: Cannot take the address of the given expression
// p = &x; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "x").WithLocation(13, 14),
// (6,11): warning CS0649: Field 'C.array' is never assigned to, and will always have its default value null
// int[] array;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "array").WithArguments("C.array", "null").WithLocation(6, 11)
);
}
[Fact]
public void AddressOfExpressionKinds_Failure()
{
var text = @"
class Base
{
public int f = 2;
}
unsafe class C : Base
{
event System.Action E;
event System.Action F { add { } remove { } }
int instanceField;
int staticField;
int this[int x] { get { return 0; } set { } }
int P { get; set; }
int M(int param)
{
int local;
int[] array = new int[1];
System.Func<int> func = () => 1;
int* p;
p = &1; //CS0211 (can't addr)
p = &array[0]; //CS0212 (need fixed)
p = &(local = 1); //CS0211
p = &goo; //CS0103 (no goo)
p = &base.f; //CS0212
p = &(local + local); //CS0211
p = &M(local); //CS0211
p = &func(); //CS0211
p = &(local += local); //CS0211
p = &(local == 0 ? local : param); //CS0211
p = &((int)param); //CS0211
p = &default(int); //CS0211
p = &delegate { return 1; }; //CS0211
p = &instanceField; //CS0212
p = &staticField; //CS0212
p = &(local++); //CS0211
p = &this[0]; //CS0211
p = &(() => 1); //CS0211
p = &M; //CS0211
p = &(new System.Int32()); //CS0211
p = &P; //CS0211
p = &sizeof(int); //CS0211
p = &this.instanceField; //CS0212
p = &(+local); //CS0211
int** pp;
pp = &(&local); //CS0211
var q = &(new { }); //CS0208, CS0211 (managed)
var r = &(new int[1]); //CS0208, CS0211 (managed)
var s = &(array as object); //CS0208, CS0211 (managed)
var t = &E; //CS0208
var u = &F; //CS0079 (can't use event like that)
var v = &(E += null); //CS0211
var w = &(F += null); //CS0211
var x = &(array is object); //CS0211
var y = &(array ?? array); //CS0208, CS0211 (managed)
var aa = &this; //CS0208
var bb = &typeof(int); //CS0208, CS0211 (managed)
var cc = &Color.Red; //CS0211
return 0;
}
int Goo(int* p) { return 0; }
static void Main() { }
}
unsafe struct S
{
S(int x)
{
var aa = &this; //CS0212 (need fixed)
}
}
enum Color
{
Red,
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (76,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// var aa = &this; //CS0212 (need fixed)
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this").WithLocation(76, 18),
// (23,14): error CS0211: Cannot take the address of the given expression
// p = &1; //CS0211 (can't addr)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "1").WithLocation(23, 14),
// (24,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &array[0]; //CS0212 (need fixed)
Diagnostic(ErrorCode.ERR_FixedNeeded, "&array[0]").WithLocation(24, 13),
// (25,15): error CS0211: Cannot take the address of the given expression
// p = &(local = 1); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local = 1").WithLocation(25, 15),
// (26,14): error CS0103: The name 'goo' does not exist in the current context
// p = &goo; //CS0103 (no goo)
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo").WithLocation(26, 14),
// (27,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &base.f; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.f").WithLocation(27, 13),
// (28,15): error CS0211: Cannot take the address of the given expression
// p = &(local + local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local + local").WithLocation(28, 15),
// (29,14): error CS0211: Cannot take the address of the given expression
// p = &M(local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "M(local)").WithLocation(29, 14),
// (30,14): error CS0211: Cannot take the address of the given expression
// p = &func(); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "func()").WithLocation(30, 14),
// (31,15): error CS0211: Cannot take the address of the given expression
// p = &(local += local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local += local").WithLocation(31, 15),
// (32,15): error CS0211: Cannot take the address of the given expression
// p = &(local == 0 ? local : param); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local == 0 ? local : param").WithLocation(32, 15),
// (33,15): error CS0211: Cannot take the address of the given expression
// p = &((int)param); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "(int)param").WithLocation(33, 15),
// (34,14): error CS0211: Cannot take the address of the given expression
// p = &default(int); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "default(int)").WithLocation(34, 14),
// (35,14): error CS0211: Cannot take the address of the given expression
// p = &delegate { return 1; }; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "delegate { return 1; }").WithLocation(35, 14),
// (36,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&instanceField").WithLocation(36, 13),
// (37,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&staticField").WithLocation(37, 13),
// (38,15): error CS0211: Cannot take the address of the given expression
// p = &(local++); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local++").WithLocation(38, 15),
// (39,14): error CS0211: Cannot take the address of the given expression
// p = &this[0]; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "this[0]").WithArguments("C.this[int]").WithLocation(39, 14),
// (40,15): error CS0211: Cannot take the address of the given expression
// p = &(() => 1); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "() => 1").WithLocation(40, 15),
// (41,13): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'int*'.
// p = &M; //CS0211
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "int*").WithLocation(41, 13),
// (42,15): error CS0211: Cannot take the address of the given expression
// p = &(new System.Int32()); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new System.Int32()").WithLocation(42, 15),
// (43,14): error CS0211: Cannot take the address of the given expression
// p = &P; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "P").WithArguments("C.P").WithLocation(43, 14),
// (44,14): error CS0211: Cannot take the address of the given expression
// p = &sizeof(int); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "sizeof(int)").WithLocation(44, 14),
// (45,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &this.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.instanceField").WithLocation(45, 13),
// (46,15): error CS0211: Cannot take the address of the given expression
// p = &(+local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "+local").WithLocation(46, 15),
// (49,16): error CS0211: Cannot take the address of the given expression
// pp = &(&local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "&local").WithLocation(49, 16),
// (51,19): error CS0211: Cannot take the address of the given expression
// var q = &(new { }); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new { }").WithLocation(51, 19),
// (52,19): error CS0211: Cannot take the address of the given expression
// var r = &(new int[1]); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new int[1]").WithLocation(52, 19),
// (53,19): error CS0211: Cannot take the address of the given expression
// var s = &(array as object); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array as object").WithLocation(53, 19),
// (54,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Action')
// var t = &E; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&E").WithArguments("System.Action").WithLocation(54, 17),
// (55,18): error CS0079: The event 'C.F' can only appear on the left hand side of += or -=
// var u = &F; //CS0079 (can't use event like that)
Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("C.F").WithLocation(55, 18),
// (56,19): error CS0211: Cannot take the address of the given expression
// var v = &(E += null); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "E += null").WithLocation(56, 19),
// (57,19): error CS0211: Cannot take the address of the given expression
// var w = &(F += null); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "F += null").WithLocation(57, 19),
// (58,19): error CS0211: Cannot take the address of the given expression
// var x = &(array is object); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array is object").WithLocation(58, 19),
// (59,19): error CS0211: Cannot take the address of the given expression
// var y = &(array ?? array); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array ?? array").WithLocation(59, 19),
// (60,19): error CS0211: Cannot take the address of the given expression
// var aa = &this; //CS0208
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "this").WithArguments("this").WithLocation(60, 19),
// (61,19): error CS0211: Cannot take the address of the given expression
// var bb = &typeof(int); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "typeof(int)").WithLocation(61, 19),
// (62,19): error CS0211: Cannot take the address of the given expression
// var cc = &Color.Red; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "Color.Red").WithLocation(62, 19)
);
}
#endregion AddressOf operand kinds
#region AddressOf diagnostics
[Fact]
public void AddressOfManaged()
{
var text = @"
unsafe class C
{
void M<T>(T t)
{
var p0 = &t; //CS0208
C c = new C();
var p1 = &c; //CS0208
S s = new S();
var p2 = &s; //CS0208
var anon = new { };
var p3 = &anon; //CS0208
}
}
public struct S
{
public string s;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
// var p0 = &t; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&t").WithArguments("T"),
// (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')
// var p1 = &c; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&c").WithArguments("C"),
// (12,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// var p2 = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"),
// (15,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>')
// var p3 = &anon; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&anon").WithArguments("<empty anonymous type>"));
}
[Fact]
public void AddressOfManaged_Cycle()
{
var text = @"
unsafe class C
{
void M()
{
S s = new S();
var p = &s; //CS0208
}
}
public struct S
{
public S s; //CS0523
public object o;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,14): error CS0523: Struct member 'S.s' of type 'S' causes a cycle in the struct layout
// public S s; //CS0523
Diagnostic(ErrorCode.ERR_StructLayoutCycle, "s").WithArguments("S.s", "S"),
// (7,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// var p = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"));
}
[Fact]
public void AddressOfVariablesThatRequireFixing()
{
var text = @"
class Base
{
public int instanceField;
public int staticField;
}
unsafe class Derived : Base
{
void M(ref int refParam, out int outParam)
{
Derived d = this;
int[] array = new int[2];
int* p;
p = &instanceField; //CS0212
p = &this.instanceField; //CS0212
p = &base.instanceField; //CS0212
p = &d.instanceField; //CS0212
p = &staticField; //CS0212
p = &this.staticField; //CS0212
p = &base.staticField; //CS0212
p = &d.staticField; //CS0212
p = &array[0]; //CS0212
p = &refParam; //CS0212
p = &outParam; //CS0212
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (17,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&instanceField"),
// (18,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &this.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.instanceField"),
// (19,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &base.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.instanceField"),
// (20,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &d.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&d.instanceField"),
// (22,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&staticField"),
// (23,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &this.staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.staticField"),
// (24,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &base.staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.staticField"),
// (25,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &d.staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&d.staticField"),
// (27,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &array[0]; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&array[0]"),
// (29,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &refParam; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&refParam"),
// (30,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &outParam; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&outParam"));
}
[Fact]
public void AddressOfInitializes()
{
var text = @"
public struct S
{
public int x;
public int y;
}
unsafe class C
{
void M()
{
S s;
int* p = &s.x;
int x = s.x; //fine
int y = s.y; //cs0170 (uninitialized)
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (15,17): error CS0170: Use of possibly unassigned field 'y'
// int y = s.y; //cs0170 (uninitialized)
Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.y").WithArguments("y"));
}
[Fact]
public void AddressOfCapturedLocal1()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x;
int* p = &x; //before capture
M(() => { x++; });
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,11): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(&x, () => { x++; });
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedLocal2()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x = 1;
M(() => { x++; });
int* p = &x; //after capture
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,18): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &x;
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedLocal3()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x;
M(() => { int* p = &x; }); // in lambda
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,28): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(() => { int* p = &x; }); // in lambda
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedLocal4()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x;
int* p = &x; //only report the first
M(() => { p = &x; });
p = &x;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,28): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(() => { int* p = &x; }); // in lambda
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedStructField1()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
int* p = &s.x; //before capture
M(() => { s.x++; });
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &s.x; //before capture
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedStructField2()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
s.x = 1;
M(() => { s.x++; });
int* p = &s.x; //after capture
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (11,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &s.x; //after capture
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedStructField3()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
M(() => { int* p = &s.x; }); // in lambda
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,28): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(() => { int* p = &s.x; }); // in lambda
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedStructField4()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
int* p = &s.x; //only report the first
M(() => { p = &s.x; });
p = &s.x;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &s.x; //only report the first
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedParameters()
{
var text = @"
unsafe struct S
{
int x;
void M(int x, S s, System.Action a)
{
M(x, s, () =>
{
int* p1 = &x;
int* p2 = &s.x;
});
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,23): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p1 = &x;
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"),
// (11,23): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p2 = &s.x;
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s")
);
}
[WorkItem(657083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657083")]
[Fact]
public void CaptureStructWithFixedArray()
{
var text = @"
unsafe public struct Test
{
private delegate int D();
public fixed int i[1];
public int goo()
{
Test t = this;
t.i[0] = 5;
D d = () => t.i[0];
return d();
}
}";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "t.i").WithArguments("t")
);
}
[Fact]
public void AddressOfCapturedFixed1()
{
var text = @"
unsafe class C
{
int x;
void M(System.Action a)
{
fixed(int* p = &x) //fine - error only applies to variables that require fixing
{
M(() => x++);
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void AddressOfCapturedFixed2()
{
var text = @"
unsafe class C
{
void M(ref int x, System.Action a)
{
fixed (int* p = &x) //fine - error only applies to variables that require fixing
{
M(ref x, () => x++);
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,28): error CS1628: Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, or query expression
// M(ref x, () => x++);
Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x"));
}
[WorkItem(543989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543989")]
[Fact]
public void AddressOfInsideAnonymousTypes()
{
var text = @"
public class C
{
public static void Main()
{
int x = 10;
unsafe
{
var t = new { p1 = &x };
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
//(9,27): error CS0828: Cannot assign int* to anonymous type property
// p1 = &x
Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "p1 = &x").WithArguments("int*"));
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[WorkItem(544537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544537")]
[Fact]
public void AddressOfStaticReadonlyFieldInsideFixed()
{
var text = @"
public class Test
{
static readonly int R1 = 45;
unsafe public static void Main()
{
fixed (int* v1 = &R1) { }
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
#endregion AddressOf diagnostics
#region AddressOf SemanticModel tests
[Fact]
public void AddressOfSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal(TypeKind.Pointer, type.TypeKind);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)type).PointedAtType.SpecialType);
var declaredSymbol = model.GetDeclaredSymbol(syntax.Ancestors().OfType<VariableDeclaratorSyntax>().First());
Assert.NotNull(declaredSymbol);
Assert.Equal(SymbolKind.Local, declaredSymbol.Kind);
Assert.Equal("p", declaredSymbol.Name);
Assert.Equal(type, ((ILocalSymbol)declaredSymbol).Type);
}
[Fact]
public void SpeculativelyBindPointerToManagedType()
{
var text = @"
unsafe struct S
{
public object o;
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single();
Assert.Equal(SyntaxKind.FieldDeclaration, syntax.Kind());
model.GetSpeculativeTypeInfo(syntax.SpanStart, SyntaxFactory.ParseTypeName("S*"), SpeculativeBindingOption.BindAsTypeOrNamespace);
// Specifically don't see diagnostic from speculative binding.
compilation.VerifyDiagnostics(
// (4,19): warning CS0649: Field 'S.o' is never assigned to, and will always have its default value null
// public object o;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "o").WithArguments("S.o", "null"));
}
[WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")]
[Fact]
public void AddressOfLambdaExpr1()
{
var text = @"
unsafe class C
{
void M()
{
var i1 = &()=>5;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
Assert.Equal("&()", syntax.ToString()); //NOTE: not actually lambda
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal("?*", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Pointer, typeInfo.Type.TypeKind);
Assert.Equal(TypeKind.Error, ((IPointerTypeSymbol)typeInfo.Type).PointedAtType.TypeKind);
}
[WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")]
[Fact]
public void AddressOfLambdaExpr2()
{
var text = @"
unsafe class C
{
void M()
{
var i1 = &(()=>5);
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
Assert.Equal("&(()=>5)", syntax.ToString());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal("?*", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Pointer, typeInfo.Type.TypeKind);
Assert.Equal(TypeKind.Error, ((IPointerTypeSymbol)typeInfo.Type).PointedAtType.TypeKind);
}
[WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")]
[Fact]
public void AddressOfMethodGroup()
{
var text = @"
unsafe class C
{
void M()
{
var i1 = &M;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
compilation.VerifyDiagnostics(
// (6,13): error CS0815: Cannot assign &method group to an implicitly-typed variable
// var i1 = &M;
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "i1 = &M").WithArguments("&method group").WithLocation(6, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal("void C.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.Null(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
}
#endregion AddressOf SemanticModel tests
#region Dereference diagnostics
[Fact]
public void DereferenceSuccess()
{
var text = @"
unsafe class C
{
int M(int* p)
{
return *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void DereferenceNullLiteral()
{
var text = @"
unsafe class C
{
void M()
{
int x = *null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0193: The * or -> operator must be applied to a pointer
// int x = *null;
Diagnostic(ErrorCode.ERR_PtrExpected, "*null"));
}
[Fact]
public void DereferenceNonPointer()
{
var text = @"
unsafe class C
{
void M()
{
int p = 1;
int x = *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,17): error CS0193: The * or -> operator must be applied to a pointer
// int x = *p;
Diagnostic(ErrorCode.ERR_PtrExpected, "*p"));
}
[Fact]
public void DereferenceVoidPointer()
{
var text = @"
unsafe class C
{
void M(void* p)
{
var x = *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0242: The operation in question is undefined on void pointers
// var x = *p;
Diagnostic(ErrorCode.ERR_VoidError, "*p"));
}
[Fact]
public void DereferenceUninitialized()
{
var text = @"
unsafe class C
{
void M()
{
int* p;
int x = *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,18): error CS0165: Use of unassigned local variable 'p'
// int x = *p;
Diagnostic(ErrorCode.ERR_UseDefViolation, "p").WithArguments("p"));
}
#endregion Dereference diagnostics
#region Dereference SemanticModel tests
[Fact]
public void DereferenceSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
x = *p;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Last();
Assert.Equal(SyntaxKind.PointerIndirectionExpression, syntax.Kind());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal(SpecialType.System_Int32, type.SpecialType);
}
#endregion Dereference SemanticModel tests
#region PointerMemberAccess diagnostics
[Fact]
public void PointerMemberAccessSuccess()
{
var text = @"
unsafe class C
{
string M(int* p)
{
return p->ToString();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerMemberAccessAddress()
{
var text = @"
unsafe struct S
{
int x;
void M(S* sp)
{
int* ip = &(sp->x);
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerMemberAccessNullLiteral()
{
var text = @"
unsafe class C
{
void M()
{
string x = null->ToString(); //Roslyn: CS0193 / Dev10: CS0023
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0193: The * or -> operator must be applied to a pointer
// string x = null->ToString(); //Roslyn: CS0193 / Dev10: CS0023
Diagnostic(ErrorCode.ERR_PtrExpected, "null->ToString"));
}
[Fact]
public void PointerMemberAccessMethodGroup()
{
var text = @"
unsafe class C
{
void M()
{
string x = M->ToString(); //Roslyn: CS0193 / Dev10: CS0023
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0193: The * or -> operator must be applied to a pointer
// string x = M->ToString(); //Roslyn: CS0193 / Dev10: CS0023
Diagnostic(ErrorCode.ERR_PtrExpected, "M->ToString"));
}
[Fact]
public void PointerMemberAccessLambda()
{
var text = @"
unsafe class C
{
void M()
{
string x = (z => z)->ToString(); //Roslyn: CS0193 / Dev10: CS0023
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0193: The * or -> operator must be applied to a pointer
// string x = (z => z)->ToString(); //Roslyn: CS0193 / Dev10: CS0023
Diagnostic(ErrorCode.ERR_PtrExpected, "(z => z)->ToString"));
}
[Fact]
public void PointerMemberAccessNonPointer()
{
var text = @"
unsafe class C
{
void M()
{
int p = 1;
int x = p->GetHashCode();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,17): error CS0193: The * or -> operator must be applied to a pointer
// int x = p->GetHashCode();
Diagnostic(ErrorCode.ERR_PtrExpected, "p->GetHashCode"));
}
[Fact]
public void PointerMemberAccessVoidPointer()
{
var text = @"
unsafe class C
{
void M(void* p)
{
var x = p->GetHashCode();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0242: The operation in question is undefined on void pointers
// var x = p->GetHashCode();
Diagnostic(ErrorCode.ERR_VoidError, "p->GetHashCode"));
}
[Fact]
public void PointerMemberAccessUninitialized()
{
var text = @"
unsafe class C
{
void M()
{
int* p;
int x = p->GetHashCode();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,18): error CS0165: Use of unassigned local variable 'p'
// int x = *p;
Diagnostic(ErrorCode.ERR_UseDefViolation, "p").WithArguments("p"));
}
[Fact]
public void PointerMemberAccessMemberKinds()
{
var text = @"
unsafe struct S
{
int InstanceField;
static int StaticField;
int InstanceProperty { get; set; }
static int StaticProperty { get; set; }
// No syntax for indexer access.
//int this[int x] { get { return 0; } set { } }
void InstanceMethod() { }
static void StaticMethod() { }
// No syntax for type member access.
//delegate void Delegate();
//struct Type { }
static void Main()
{
S s;
S* p = &s;
p->InstanceField = 1;
p->StaticField = 1; //CS0176
p->InstanceProperty = 2;
p->StaticProperty = 2; //CS0176
p->InstanceMethod();
p->StaticMethod(); //CS0176
p->ExtensionMethod();
System.Action a;
a = p->InstanceMethod;
a = p->StaticMethod; //CS0176
a = p->ExtensionMethod; //CS1113
}
}
static class Extensions
{
public static void ExtensionMethod(this S s)
{
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (26,9): error CS0176: Member 'S.StaticField' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticField = 1; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticField").WithArguments("S.StaticField").WithLocation(26, 9),
// (29,9): error CS0176: Member 'S.StaticProperty' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticProperty = 2; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticProperty").WithArguments("S.StaticProperty").WithLocation(29, 9),
// (32,9): error CS0176: Member 'S.StaticMethod()' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticMethod(); //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticMethod").WithArguments("S.StaticMethod()").WithLocation(32, 9),
// (38,13): error CS0176: Member 'S.StaticMethod()' cannot be accessed with an instance reference; qualify it with a type name instead
// a = p->StaticMethod; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticMethod").WithArguments("S.StaticMethod()").WithLocation(38, 13),
// (39,13): error CS1113: Extension method 'Extensions.ExtensionMethod(S)' defined on value type 'S' cannot be used to create delegates
// a = p->ExtensionMethod; //CS1113
Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "p->ExtensionMethod").WithArguments("Extensions.ExtensionMethod(S)", "S").WithLocation(39, 13)
);
}
// NOTE: a type with events is managed, so this is always an error case.
[Fact]
public void PointerMemberAccessEvents()
{
var text = @"
unsafe struct S
{
event System.Action InstanceFieldLikeEvent;
static event System.Action StaticFieldLikeEvent;
event System.Action InstanceCustomEvent { add { } remove { } }
static event System.Action StaticCustomEvent { add { } remove { } }
static void Main()
{
S s;
S* p = &s; //CS0208
p->InstanceFieldLikeEvent += null;
p->StaticFieldLikeEvent += null; //CS0176
p->InstanceCustomEvent += null;
p->StaticCustomEvent += null; //CS0176
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* p = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"),
// (13,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* p = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"),
// (16,9): error CS0176: Member 'S.StaticFieldLikeEvent' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticFieldLikeEvent += null; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticFieldLikeEvent").WithArguments("S.StaticFieldLikeEvent"),
// (19,9): error CS0176: Member 'S.StaticCustomEvent' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticCustomEvent += null; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticCustomEvent").WithArguments("S.StaticCustomEvent"),
// (5,32): warning CS0067: The event 'S.StaticFieldLikeEvent' is never used
// static event System.Action StaticFieldLikeEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "StaticFieldLikeEvent").WithArguments("S.StaticFieldLikeEvent"),
// (4,25): warning CS0067: The event 'S.InstanceFieldLikeEvent' is never used
// event System.Action InstanceFieldLikeEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "InstanceFieldLikeEvent").WithArguments("S.InstanceFieldLikeEvent")
);
}
#endregion PointerMemberAccess diagnostics
#region PointerMemberAccess SemanticModel tests
[Fact]
public void PointerMemberAccessSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
S s;
S* p = &s;
p->M();
}
}
struct S
{
public void M() { }
public void M(int x) { }
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.PointerMemberAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var methodGroupSyntax = syntax;
var callSyntax = syntax.Parent;
var structType = compilation.GlobalNamespace.GetMember<TypeSymbol>("S");
var structPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(structType));
var structMethod1 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 0);
var structMethod2 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 1);
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Local, receiverSymbol.Kind);
Assert.Equal(structPointerType.GetPublicSymbol(), ((ILocalSymbol)receiverSymbol).Type);
Assert.Equal("p", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(structPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(structPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var methodGroupSummary = model.GetSemanticInfoSummary(methodGroupSyntax);
Assert.Equal(structMethod1, methodGroupSummary.Symbol.GetSymbol());
Assert.Equal(CandidateReason.None, methodGroupSummary.CandidateReason);
Assert.Equal(0, methodGroupSummary.CandidateSymbols.Length);
Assert.Null(methodGroupSummary.Type);
Assert.Null(methodGroupSummary.ConvertedType);
Assert.Equal(ConversionKind.Identity, methodGroupSummary.ImplicitConversion.Kind);
Assert.True(methodGroupSummary.MethodGroup.SetEquals(ImmutableArray.Create<IMethodSymbol>(structMethod1.GetPublicSymbol(), structMethod2.GetPublicSymbol()), EqualityComparer<IMethodSymbol>.Default));
var callSummary = model.GetSemanticInfoSummary(callSyntax);
Assert.Equal(structMethod1, callSummary.Symbol.GetSymbol());
Assert.Equal(CandidateReason.None, callSummary.CandidateReason);
Assert.Equal(0, callSummary.CandidateSymbols.Length);
Assert.Equal(SpecialType.System_Void, callSummary.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, callSummary.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, callSummary.ImplicitConversion.Kind);
Assert.Equal(0, callSummary.MethodGroup.Length);
}
[Fact]
public void PointerMemberAccessSemanticModelAPIs_ErrorScenario()
{
var text = @"
unsafe class C
{
void M()
{
S s;
S* p = &s;
s->M(); //should be 'p'
}
}
struct S
{
public void M() { }
public void M(int x) { }
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.PointerMemberAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var methodGroupSyntax = syntax;
var callSyntax = syntax.Parent;
var structType = compilation.GlobalNamespace.GetMember<TypeSymbol>("S");
var structMethod1 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 0);
var structMethod2 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 1);
var structMethods = ImmutableArray.Create<MethodSymbol>(structMethod1, structMethod2);
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Local, receiverSymbol.Kind);
Assert.Equal(structType.GetPublicSymbol(), ((ILocalSymbol)receiverSymbol).Type);
Assert.Equal("s", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(structType, receiverSummary.Type.GetSymbol());
Assert.Equal(structType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var methodGroupSummary = model.GetSemanticInfoSummary(methodGroupSyntax);
Assert.Equal(structMethod1, methodGroupSummary.Symbol.GetSymbol()); // Have enough info for overload resolution.
Assert.Null(methodGroupSummary.Type);
Assert.Null(methodGroupSummary.ConvertedType);
Assert.Equal(ConversionKind.Identity, methodGroupSummary.ImplicitConversion.Kind);
Assert.True(methodGroupSummary.MethodGroup.SetEquals(structMethods.GetPublicSymbols(), EqualityComparer<IMethodSymbol>.Default));
var callSummary = model.GetSemanticInfoSummary(callSyntax);
Assert.Equal(structMethod1, callSummary.Symbol.GetSymbol()); // Have enough info for overload resolution.
Assert.Equal(SpecialType.System_Void, callSummary.Type.SpecialType);
Assert.Equal(callSummary.Type, callSummary.ConvertedType);
Assert.Equal(ConversionKind.Identity, callSummary.ImplicitConversion.Kind);
Assert.Equal(0, callSummary.MethodGroup.Length);
}
#endregion PointerMemberAccess SemanticModel tests
#region PointerElementAccess
[Fact]
public void PointerElementAccess_NoIndices()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
S s = p[];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0443: Syntax error; value expected
// S s = p[];
Diagnostic(ErrorCode.ERR_ValueExpected, "]"));
}
[Fact]
public void PointerElementAccess_MultipleIndices()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
S s = p[1, 2];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,15): error CS0196: A pointer must be indexed by only one value
// S s = p[1, 2];
Diagnostic(ErrorCode.ERR_PtrIndexSingle, "p[1, 2]"));
}
[Fact]
public void PointerElementAccess_RefIndex()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
int x = 1;
S s = p[ref x];
}
}
";
// Dev10 gives an unhelpful syntax error.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 should not be passed with the 'ref' keyword
// S s = p[ref x];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "ref"));
}
[Fact]
public void PointerElementAccess_OutIndex()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
int x = 1;
S s = p[out x];
}
}
";
// Dev10 gives an unhelpful syntax error.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 should not be passed with the 'out' keyword
// S s = p[out x];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "out"));
}
[Fact]
public void PointerElementAccess_NamedOffset()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
int x = 1;
S s = p[index: x];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,15): error CS1742: An array access may not have a named argument specifier
// S s = p[index: x];
Diagnostic(ErrorCode.ERR_NamedArgumentForArray, "p[index: x]"));
}
[Fact]
public void PointerElementAccess_VoidPointer()
{
var text = @"
unsafe struct S
{
void M(void* p)
{
p[0] = null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS0242: The operation in question is undefined on void pointers
// p[0] = null;
Diagnostic(ErrorCode.ERR_VoidError, "p"));
}
[Fact, WorkItem(27945, "https://github.com/dotnet/roslyn/issues/27945")]
public void TakingAddressOfPointerFieldsIsLegal_Static()
{
CreateCompilation(@"
unsafe class C
{
static int* x;
static void Main()
{
fixed (int* y = new int[1])
{
x = y;
}
int* element = &x[0];
*element = 5;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact, WorkItem(27945, "https://github.com/dotnet/roslyn/issues/27945")]
public void TakingAddressOfPointerFieldsIsLegal_Instance()
{
CreateCompilation(@"
unsafe class C
{
int* x;
void Calculate()
{
fixed (int* y = new int[1])
{
x = y;
}
int* element = &x[0];
*element = 5;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact, WorkItem(27945, "https://github.com/dotnet/roslyn/issues/27945")]
public void TakingAddressOfPointerFieldsIsLegal_Local()
{
CreateCompilation(@"
unsafe class C
{
static void Main()
{
int* x;
fixed (int* y = new int[1])
{
x = y;
}
int* element = &x[0];
*element = 5;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
#endregion PointerElementAccess diagnostics
#region PointerElementAccess SemanticModel tests
[Fact]
public void PointerElementAccessSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
const int size = 3;
fixed(int* p = new int[size])
{
for (int i = 0; i < size; i++)
{
p[i] = i * i;
}
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression;
var accessSyntax = syntax;
var intType = compilation.GetSpecialType(SpecialType.System_Int32);
var intPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(intType));
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Local, receiverSymbol.Kind);
Assert.Equal(intPointerType.GetPublicSymbol(), ((ILocalSymbol)receiverSymbol).Type);
Assert.Equal("p", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(intPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(intPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var indexSummary = model.GetSemanticInfoSummary(indexSyntax);
var indexSymbol = indexSummary.Symbol;
Assert.Equal(SymbolKind.Local, indexSymbol.Kind);
Assert.Equal(intType.GetPublicSymbol(), ((ILocalSymbol)indexSymbol).Type);
Assert.Equal("i", indexSymbol.Name);
Assert.Equal(CandidateReason.None, indexSummary.CandidateReason);
Assert.Equal(0, indexSummary.CandidateSymbols.Length);
Assert.Equal(intType, indexSummary.Type.GetSymbol());
Assert.Equal(intType, indexSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, indexSummary.ImplicitConversion.Kind);
Assert.Equal(0, indexSummary.MethodGroup.Length);
var accessSummary = model.GetSemanticInfoSummary(accessSyntax);
Assert.Null(accessSummary.Symbol);
Assert.Equal(CandidateReason.None, accessSummary.CandidateReason);
Assert.Equal(0, accessSummary.CandidateSymbols.Length);
Assert.Equal(intType, accessSummary.Type.GetSymbol());
Assert.Equal(intType, accessSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind);
Assert.Equal(0, accessSummary.MethodGroup.Length);
}
[Fact]
public void PointerElementAccessSemanticModelAPIs_Fixed_Unmovable()
{
var text = @"
unsafe class C
{
struct S1
{
public fixed int f[10];
}
void M()
{
S1 p = default;
p.f[i] = 123;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression;
var accessSyntax = syntax;
var intType = compilation.GetSpecialType(SpecialType.System_Int32);
var intPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(intType));
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Field, receiverSymbol.Kind);
Assert.Equal(intPointerType.GetPublicSymbol(), ((IFieldSymbol)receiverSymbol).Type);
Assert.Equal("f", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(intPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(intPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var indexSummary = model.GetSemanticInfoSummary(indexSyntax);
var indexSymbol = indexSummary.Symbol;
Assert.Null(indexSymbol);
var accessSummary = model.GetSemanticInfoSummary(accessSyntax);
Assert.Null(accessSummary.Symbol);
Assert.Equal(CandidateReason.None, accessSummary.CandidateReason);
Assert.Equal(0, accessSummary.CandidateSymbols.Length);
Assert.Equal(intType, accessSummary.Type.GetSymbol());
Assert.Equal(intType, accessSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind);
Assert.Equal(0, accessSummary.MethodGroup.Length);
}
[Fact]
public void PointerElementAccessSemanticModelAPIs_Fixed_Movable()
{
var text = @"
unsafe class C
{
struct S1
{
public fixed int f[10];
}
S1 p = default;
void M()
{
p.f[i] = 123;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression;
var accessSyntax = syntax;
var intType = compilation.GetSpecialType(SpecialType.System_Int32);
var intPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(intType));
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Field, receiverSymbol.Kind);
Assert.Equal(intPointerType.GetPublicSymbol(), ((IFieldSymbol)receiverSymbol).Type);
Assert.Equal("f", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(intPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(intPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var indexSummary = model.GetSemanticInfoSummary(indexSyntax);
var indexSymbol = indexSummary.Symbol;
Assert.Null(indexSymbol);
var accessSummary = model.GetSemanticInfoSummary(accessSyntax);
Assert.Null(accessSummary.Symbol);
Assert.Equal(CandidateReason.None, accessSummary.CandidateReason);
Assert.Equal(0, accessSummary.CandidateSymbols.Length);
Assert.Equal(intType, accessSummary.Type.GetSymbol());
Assert.Equal(intType, accessSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind);
Assert.Equal(0, accessSummary.MethodGroup.Length);
}
#endregion PointerElementAccess SemanticModel tests
#region Pointer conversion tests
[Fact]
public void NullLiteralConversion()
{
var text = @"
unsafe struct S
{
void M()
{
byte* b = null;
int* i = null;
S* s = null;
void* v = null;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var nullSyntax in tree.GetCompilationUnitRoot().DescendantTokens().Where(token => token.IsKind(SyntaxKind.NullKeyword)))
{
var node = (ExpressionSyntax)nullSyntax.Parent;
var typeInfo = model.GetTypeInfo(node);
var conv = model.GetConversion(node);
Assert.Null(typeInfo.Type);
Assert.Equal(TypeKind.Pointer, typeInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNullToPointer, conv.Kind);
}
}
[Fact]
public void VoidPointerConversion1()
{
var text = @"
unsafe struct S
{
void M()
{
byte* b = null;
int* i = null;
S* s = null;
void* v1 = b;
void* v2 = i;
void* v3 = s;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var declarationSyntax in tree.GetCompilationUnitRoot().DescendantTokens().OfType<VariableDeclarationSyntax>().Where(syntax => syntax.GetFirstToken().IsKind(SyntaxKind.VoidKeyword)))
{
var value = declarationSyntax.Variables.Single().Initializer.Value;
var typeInfo = model.GetTypeInfo(value);
var type = typeInfo.Type;
Assert.Equal(TypeKind.Pointer, type.TypeKind);
Assert.NotEqual(SpecialType.System_Void, ((IPointerTypeSymbol)type).PointedAtType.SpecialType);
var convertedType = typeInfo.ConvertedType;
Assert.Equal(TypeKind.Pointer, convertedType.TypeKind);
Assert.Equal(SpecialType.System_Void, ((IPointerTypeSymbol)convertedType).PointedAtType.SpecialType);
var conv = model.GetConversion(value);
Assert.Equal(ConversionKind.ImplicitPointerToVoid, conv.Kind);
}
}
[Fact]
public void VoidPointerConversion2()
{
var text = @"
unsafe struct S
{
void M()
{
void* v = null;
void* vv1 = &v;
void** vv2 = &v;
void* vv3 = vv2;
void** vv4 = vv3;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,22): error CS0266: Cannot implicitly convert type 'void*' to 'void**'. An explicit conversion exists (are you missing a cast?)
// void** vv4 = vv3;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "vv3").WithArguments("void*", "void**"));
}
[Fact]
public void ExplicitPointerConversion()
{
var text = @"
unsafe struct S
{
void M(int* i, byte* b, void* v, int** ii, byte** bb, void** vv)
{
i = (int*)b;
i = (int*)v;
i = (int*)ii;
i = (int*)bb;
i = (int*)vv;
b = (byte*)i;
b = (byte*)v;
b = (byte*)ii;
b = (byte*)bb;
b = (byte*)vv;
v = (void*)i;
v = (void*)b;
v = (void*)ii;
v = (void*)bb;
v = (void*)vv;
ii = (int**)i;
ii = (int**)b;
ii = (int**)v;
ii = (int**)bb;
ii = (int**)vv;
bb = (byte**)i;
bb = (byte**)b;
bb = (byte**)v;
bb = (byte**)ii;
bb = (byte**)vv;
vv = (void**)i;
vv = (void**)b;
vv = (void**)v;
vv = (void**)ii;
vv = (void**)bb;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ExplicitPointerNumericConversion()
{
var text = @"
unsafe struct S
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ExplicitPointerNumericConversion_Illegal()
{
var text = @"
unsafe struct S
{
void M(int* pi, void* pv, bool b, char c, double d, decimal e, float f)
{
b = (bool)pi;
c = (char)pi;
d = (double)pi;
e = (decimal)pi;
f = (float)pi;
b = (bool)pv;
c = (char)pv;
d = (double)pv;
e = (decimal)pv;
f = (float)pv;
pi = (int*)b;
pi = (int*)c;
pi = (int*)d;
pi = (int*)d;
pi = (int*)f;
pv = (void*)b;
pv = (void*)c;
pv = (void*)d;
pv = (void*)e;
pv = (void*)f;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0030: Cannot convert type 'int*' to 'bool'
// b = (bool)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(bool)pi").WithArguments("int*", "bool"),
// (7,13): error CS0030: Cannot convert type 'int*' to 'char'
// c = (char)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(char)pi").WithArguments("int*", "char"),
// (8,13): error CS0030: Cannot convert type 'int*' to 'double'
// d = (double)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double)pi").WithArguments("int*", "double"),
// (9,13): error CS0030: Cannot convert type 'int*' to 'decimal'
// e = (decimal)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(decimal)pi").WithArguments("int*", "decimal"),
// (10,13): error CS0030: Cannot convert type 'int*' to 'float'
// f = (float)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(float)pi").WithArguments("int*", "float"),
// (12,13): error CS0030: Cannot convert type 'void*' to 'bool'
// b = (bool)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(bool)pv").WithArguments("void*", "bool"),
// (13,13): error CS0030: Cannot convert type 'void*' to 'char'
// c = (char)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(char)pv").WithArguments("void*", "char"),
// (14,13): error CS0030: Cannot convert type 'void*' to 'double'
// d = (double)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double)pv").WithArguments("void*", "double"),
// (15,13): error CS0030: Cannot convert type 'void*' to 'decimal'
// e = (decimal)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(decimal)pv").WithArguments("void*", "decimal"),
// (16,13): error CS0030: Cannot convert type 'void*' to 'float'
// f = (float)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(float)pv").WithArguments("void*", "float"),
// (18,14): error CS0030: Cannot convert type 'bool' to 'int*'
// pi = (int*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)b").WithArguments("bool", "int*"),
// (19,14): error CS0030: Cannot convert type 'char' to 'int*'
// pi = (int*)c;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)c").WithArguments("char", "int*"),
// (20,14): error CS0030: Cannot convert type 'double' to 'int*'
// pi = (int*)d;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)d").WithArguments("double", "int*"),
// (21,14): error CS0030: Cannot convert type 'double' to 'int*'
// pi = (int*)d;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)d").WithArguments("double", "int*"),
// (22,14): error CS0030: Cannot convert type 'float' to 'int*'
// pi = (int*)f;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)f").WithArguments("float", "int*"),
// (24,14): error CS0030: Cannot convert type 'bool' to 'void*'
// pv = (void*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)b").WithArguments("bool", "void*"),
// (25,14): error CS0030: Cannot convert type 'char' to 'void*'
// pv = (void*)c;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)c").WithArguments("char", "void*"),
// (26,14): error CS0030: Cannot convert type 'double' to 'void*'
// pv = (void*)d;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)d").WithArguments("double", "void*"),
// (27,14): error CS0030: Cannot convert type 'decimal' to 'void*'
// pv = (void*)e;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)e").WithArguments("decimal", "void*"),
// (28,14): error CS0030: Cannot convert type 'float' to 'void*'
// pv = (void*)f;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)f").WithArguments("float", "void*"));
}
[Fact]
public void ExplicitPointerNumericConversion_Nullable()
{
var text = @"
unsafe struct S
{
void M(int* pi, void* pv, sbyte? sb, byte? b, short? s, ushort? us, int? i, uint? ui, long? l, ulong? ul)
{
sb = (sbyte?)pi;
b = (byte?)pi;
s = (short?)pi;
us = (ushort?)pi;
i = (int?)pi;
ui = (uint?)pi;
l = (long?)pi;
ul = (ulong?)pi;
sb = (sbyte?)pv;
b = (byte?)pv;
s = (short?)pv;
us = (ushort?)pv;
i = (int?)pv;
ui = (uint?)pv;
l = (long?)pv;
ul = (ulong?)pv;
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (24,14): error CS0030: Cannot convert type 'sbyte?' to 'int*'
// pi = (int*)sb;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)sb").WithArguments("sbyte?", "int*"),
// (25,14): error CS0030: Cannot convert type 'byte?' to 'int*'
// pi = (int*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)b").WithArguments("byte?", "int*"),
// (26,14): error CS0030: Cannot convert type 'short?' to 'int*'
// pi = (int*)s;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)s").WithArguments("short?", "int*"),
// (27,14): error CS0030: Cannot convert type 'ushort?' to 'int*'
// pi = (int*)us;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)us").WithArguments("ushort?", "int*"),
// (28,14): error CS0030: Cannot convert type 'int?' to 'int*'
// pi = (int*)i;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)i").WithArguments("int?", "int*"),
// (29,14): error CS0030: Cannot convert type 'uint?' to 'int*'
// pi = (int*)ui;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)ui").WithArguments("uint?", "int*"),
// (30,14): error CS0030: Cannot convert type 'long?' to 'int*'
// pi = (int*)l;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)l").WithArguments("long?", "int*"),
// (31,14): error CS0030: Cannot convert type 'ulong?' to 'int*'
// pi = (int*)ul;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)ul").WithArguments("ulong?", "int*"),
// (33,14): error CS0030: Cannot convert type 'sbyte?' to 'void*'
// pv = (void*)sb;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)sb").WithArguments("sbyte?", "void*"),
// (34,14): error CS0030: Cannot convert type 'byte?' to 'void*'
// pv = (void*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)b").WithArguments("byte?", "void*"),
// (35,14): error CS0030: Cannot convert type 'short?' to 'void*'
// pv = (void*)s;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)s").WithArguments("short?", "void*"),
// (36,14): error CS0030: Cannot convert type 'ushort?' to 'void*'
// pv = (void*)us;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)us").WithArguments("ushort?", "void*"),
// (37,14): error CS0030: Cannot convert type 'int?' to 'void*'
// pv = (void*)i;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)i").WithArguments("int?", "void*"),
// (38,14): error CS0030: Cannot convert type 'uint?' to 'void*'
// pv = (void*)ui;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)ui").WithArguments("uint?", "void*"),
// (39,14): error CS0030: Cannot convert type 'long?' to 'void*'
// pv = (void*)l;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)l").WithArguments("long?", "void*"),
// (40,14): error CS0030: Cannot convert type 'ulong?' to 'void*'
// pv = (void*)ul;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)ul").WithArguments("ulong?", "void*"));
}
[Fact]
public void PointerArrayConversion()
{
var text = @"
using System;
unsafe class C
{
void M(int*[] api, void*[] apv, Array a)
{
a = api;
a.GetValue(0); //runtime error
a = apv;
a.GetValue(0); //runtime error
api = a; //CS0266
apv = a; //CS0266
api = (int*[])a;
apv = (void*[])a;
apv = api; //CS0029
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,15): error CS0266: Cannot implicitly convert type 'System.Array' to 'int*[]'. An explicit conversion exists (are you missing a cast?)
// api = a; //CS0266
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("System.Array", "int*[]"),
// (14,15): error CS0266: Cannot implicitly convert type 'System.Array' to 'void*[]'. An explicit conversion exists (are you missing a cast?)
// apv = a; //CS0266
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("System.Array", "void*[]"),
// (19,15): error CS0029: Cannot implicitly convert type 'int*[]' to 'void*[]'
// apv = api; //CS0029
Diagnostic(ErrorCode.ERR_NoImplicitConv, "api").WithArguments("int*[]", "void*[]"));
}
[Fact]
public void PointerArrayToListConversion()
{
var text = @"
using System.Collections.Generic;
unsafe class C
{
void M(int*[] api, void*[] apv)
{
To(api);
To(apv);
api = From(api[0]);
apv = From(apv[0]);
}
void To<T>(IList<T> list)
{
}
IList<T> From<T>(T t)
{
return null;
}
}
";
// NOTE: dev10 also reports some rather silly cascading CS0266s.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,9): error CS0306: The type 'int*' may not be used as a type argument
// To(api);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "To").WithArguments("int*"),
// (9,9): error CS0306: The type 'void*' may not be used as a type argument
// To(apv);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "To").WithArguments("void*"),
// (11,15): error CS0306: The type 'int*' may not be used as a type argument
// api = From(api[0]);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "From").WithArguments("int*"),
// (12,15): error CS0306: The type 'void*' may not be used as a type argument
// apv = From(apv[0]);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "From").WithArguments("void*"));
}
[Fact]
public void PointerArrayToEnumerableConversion()
{
var text = @"
using System.Collections;
unsafe class C
{
void M(int*[] api, void*[] apv)
{
IEnumerable e = api;
e = apv;
}
}
";
// NOTE: as in Dev10, there's a runtime error if you try to access an element.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
#endregion Pointer conversion tests
#region Pointer arithmetic tests
[Fact]
public void PointerArithmetic_LegalNumeric()
{
var text = @"
unsafe class C
{
void M(byte* p, int i, uint ui, long l, ulong ul)
{
p = p + i;
p = i + p;
p = p - i;
p = p + ui;
p = ui + p;
p = p - ui;
p = p + l;
p = l + p;
p = p - l;
p = p + ul;
p = ul + p;
p = p - ul;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
var methodSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
var pointerType = methodSymbol.Parameters[0].Type;
Assert.Equal(TypeKind.Pointer, pointerType.TypeKind);
foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>())
{
var summary = model.GetSemanticInfoSummary(binOpSyntax);
if (binOpSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression)
{
Assert.Null(summary.Symbol);
}
else
{
Assert.NotNull(summary.Symbol);
Assert.Equal(MethodKind.BuiltinOperator, ((IMethodSymbol)summary.Symbol).MethodKind);
}
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(pointerType, summary.Type.GetSymbol());
Assert.Equal(pointerType, summary.ConvertedType.GetSymbol());
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
Assert.False(summary.IsCompileTimeConstant);
Assert.False(summary.ConstantValue.HasValue);
}
}
[Fact]
public void PointerArithmetic_LegalPointer()
{
var text = @"
unsafe class C
{
void M(byte* p)
{
var diff = p - p;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>())
{
var summary = model.GetSemanticInfoSummary(binOpSyntax);
Assert.Equal("System.Int64 System.Byte*.op_Subtraction(System.Byte* left, System.Byte* right)", summary.Symbol.ToTestDisplayString());
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(SpecialType.System_Int64, summary.Type.SpecialType);
Assert.Equal(SpecialType.System_Int64, summary.ConvertedType.SpecialType);
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
Assert.False(summary.IsCompileTimeConstant);
Assert.False(summary.ConstantValue.HasValue);
}
}
[Fact]
public void PointerArithmetic_IllegalNumericSubtraction()
{
var text = @"
unsafe class C
{
void M(byte* p, int i, uint ui, long l, ulong ul)
{
p = i - p;
p = ui - p;
p = l - p;
p = ul - p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'byte*'
// p = i - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - p").WithArguments("-", "int", "byte*"),
// (7,13): error CS0019: Operator '-' cannot be applied to operands of type 'uint' and 'byte*'
// p = ui - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ui - p").WithArguments("-", "uint", "byte*"),
// (8,13): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'byte*'
// p = l - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "l - p").WithArguments("-", "long", "byte*"),
// (9,13): error CS0019: Operator '-' cannot be applied to operands of type 'ulong' and 'byte*'
// p = ul - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ul - p").WithArguments("-", "ulong", "byte*"));
}
[Fact]
public void PointerArithmetic_IllegalPointerSubtraction()
{
var text = @"
unsafe class C
{
void M(byte* b, int* i, byte** bb, int** ii)
{
long l;
l = b - i;
l = b - bb;
l = b - ii;
l = i - b;
l = i - bb;
l = i - ii;
l = bb - b;
l = bb - i;
l = bb - ii;
l = ii - b;
l = ii - i;
l = ii - bb;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'int*'
// l = b - i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - i").WithArguments("-", "byte*", "int*"),
// (9,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'byte**'
// l = b - bb;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - bb").WithArguments("-", "byte*", "byte**"),
// (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'int**'
// l = b - ii;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - ii").WithArguments("-", "byte*", "int**"),
// (12,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'byte*'
// l = i - b;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - b").WithArguments("-", "int*", "byte*"),
// (13,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'byte**'
// l = i - bb;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - bb").WithArguments("-", "int*", "byte**"),
// (14,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'int**'
// l = i - ii;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - ii").WithArguments("-", "int*", "int**"),
// (16,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'byte*'
// l = bb - b;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - b").WithArguments("-", "byte**", "byte*"),
// (17,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'int*'
// l = bb - i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - i").WithArguments("-", "byte**", "int*"),
// (18,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'int**'
// l = bb - ii;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - ii").WithArguments("-", "byte**", "int**"),
// (20,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'byte*'
// l = ii - b;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - b").WithArguments("-", "int**", "byte*"),
// (21,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'int*'
// l = ii - i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - i").WithArguments("-", "int**", "int*"),
// (22,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'byte**'
// l = ii - bb;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - bb").WithArguments("-", "int**", "byte**"));
}
[Fact]
public void PointerArithmetic_OtherOperators()
{
var text = @"
unsafe class C
{
void M(byte* p, int i)
{
var r01 = p * i;
var r02 = i * p;
var r03 = p / i;
var r04 = i / p;
var r05 = p % i;
var r06 = i % p;
var r07 = p << i;
var r08 = i << p;
var r09 = p >> i;
var r10 = i >> p;
var r11 = p & i;
var r12 = i & p;
var r13 = p | i;
var r14 = i | p;
var r15 = p ^ i;
var r16 = i ^ p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,19): error CS0019: Operator '*' cannot be applied to operands of type 'byte*' and 'int'
// var r01 = p * i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p * i").WithArguments("*", "byte*", "int"),
// (7,19): error CS0019: Operator '*' cannot be applied to operands of type 'int' and 'byte*'
// var r02 = i * p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i * p").WithArguments("*", "int", "byte*"),
// (8,19): error CS0019: Operator '/' cannot be applied to operands of type 'byte*' and 'int'
// var r03 = p / i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p / i").WithArguments("/", "byte*", "int"),
// (9,19): error CS0019: Operator '/' cannot be applied to operands of type 'int' and 'byte*'
// var r04 = i / p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i / p").WithArguments("/", "int", "byte*"),
// (10,19): error CS0019: Operator '%' cannot be applied to operands of type 'byte*' and 'int'
// var r05 = p % i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p % i").WithArguments("%", "byte*", "int"),
// (11,19): error CS0019: Operator '%' cannot be applied to operands of type 'int' and 'byte*'
// var r06 = i % p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i % p").WithArguments("%", "int", "byte*"),
// (12,19): error CS0019: Operator '<<' cannot be applied to operands of type 'byte*' and 'int'
// var r07 = p << i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p << i").WithArguments("<<", "byte*", "int"),
// (13,19): error CS0019: Operator '<<' cannot be applied to operands of type 'int' and 'byte*'
// var r08 = i << p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i << p").WithArguments("<<", "int", "byte*"),
// (14,19): error CS0019: Operator '>>' cannot be applied to operands of type 'byte*' and 'int'
// var r09 = p >> i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >> i").WithArguments(">>", "byte*", "int"),
// (15,19): error CS0019: Operator '>>' cannot be applied to operands of type 'int' and 'byte*'
// var r10 = i >> p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i >> p").WithArguments(">>", "int", "byte*"),
// (16,19): error CS0019: Operator '&' cannot be applied to operands of type 'byte*' and 'int'
// var r11 = p & i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p & i").WithArguments("&", "byte*", "int"),
// (17,19): error CS0019: Operator '&' cannot be applied to operands of type 'int' and 'byte*'
// var r12 = i & p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i & p").WithArguments("&", "int", "byte*"),
// (18,19): error CS0019: Operator '|' cannot be applied to operands of type 'byte*' and 'int'
// var r13 = p | i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p | i").WithArguments("|", "byte*", "int"),
// (19,19): error CS0019: Operator '|' cannot be applied to operands of type 'int' and 'byte*'
// var r14 = i | p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i | p").WithArguments("|", "int", "byte*"),
// (20,19): error CS0019: Operator '^' cannot be applied to operands of type 'byte*' and 'int'
// var r15 = p ^ i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p ^ i").WithArguments("^", "byte*", "int"),
// (21,19): error CS0019: Operator '^' cannot be applied to operands of type 'int' and 'byte*'
// var r16 = i ^ p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i ^ p").WithArguments("^", "int", "byte*"));
}
[Fact]
public void PointerArithmetic_NumericWidening()
{
var text = @"
unsafe class C
{
void M(int* p, sbyte sb, byte b, short s, ushort us)
{
p = p + sb;
p = p + b;
p = p + s;
p = p + us;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerArithmetic_NumericUDC()
{
var text = @"
unsafe class C
{
void M(int* p)
{
p = p + this;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerArithmetic_Nullable()
{
var text = @"
unsafe class C
{
void M(int* p, int? i)
{
p = p + i;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0019: Operator '+' cannot be applied to operands of type 'int*' and 'int?'
// p = p + i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p + i").WithArguments("+", "int*", "int?"));
}
[Fact]
public void PointerArithmetic_Compound()
{
var text = @"
unsafe class C
{
void M(int* p, int i)
{
p++;
++p;
p--;
--p;
p += i;
p -= i;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerArithmetic_VoidPointer()
{
var text = @"
unsafe class C
{
void M(void* p)
{
var diff = p - p;
p = p + 1;
p = p - 1;
p = 1 + p;
p = 1 - p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0242: The operation in question is undefined on void pointers
// var diff = p - p;
Diagnostic(ErrorCode.ERR_VoidError, "p - p"),
// (7,13): error CS0242: The operation in question is undefined on void pointers
// p = p + 1;
Diagnostic(ErrorCode.ERR_VoidError, "p + 1"),
// (8,13): error CS0242: The operation in question is undefined on void pointers
// p = p - 1;
Diagnostic(ErrorCode.ERR_VoidError, "p - 1"),
// (9,13): error CS0242: The operation in question is undefined on void pointers
// p = 1 + p;
Diagnostic(ErrorCode.ERR_VoidError, "1 + p"),
// (10,13): error CS0242: The operation in question is undefined on void pointers
// p = 1 - p;
Diagnostic(ErrorCode.ERR_VoidError, "1 - p"),
// (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'void*'
// p = 1 - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - p").WithArguments("-", "int", "void*"));
}
[Fact]
public void PointerArithmetic_VoidPointerPointer()
{
var text = @"
unsafe class C
{
void M(void** p) //void** is not a void pointer
{
var diff = p - p;
p = p + 1;
p = p - 1;
p = 1 + p;
p = 1 - p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'void**'
// p = 1 - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - p").WithArguments("-", "int", "void**"));
}
#endregion Pointer arithmetic tests
#region Pointer comparison tests
[WorkItem(546712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546712")]
[Fact]
public void PointerComparison_Null()
{
// We had a bug whereby overload resolution was failing if the null
// was on the left. This test regresses the bug.
var text = @"
unsafe struct S
{
bool M(byte* pb, S* ps)
{
return null != pb && null == ps;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerComparison_Pointer()
{
var text = @"
unsafe class C
{
void M(byte* b, int* i, void* v)
{
bool result;
byte* b2 = b;
int* i2 = i;
void* v2 = v;
result = b == b2;
result = b == i2;
result = b == v2;
result = i != i2;
result = i != v2;
result = i != b2;
result = v <= v2;
result = v <= b2;
result = v <= i2;
result = b >= b2;
result = b >= i2;
result = b >= v2;
result = i < i2;
result = i < v2;
result = i < b2;
result = v > v2;
result = v > b2;
result = v > i2;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>())
{
var summary = model.GetSemanticInfoSummary(binOpSyntax);
if (binOpSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression)
{
Assert.Null(summary.Symbol);
}
else
{
Assert.NotNull(summary.Symbol);
Assert.Equal(MethodKind.BuiltinOperator, ((IMethodSymbol)summary.Symbol).MethodKind);
}
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(SpecialType.System_Boolean, summary.Type.SpecialType);
Assert.Equal(SpecialType.System_Boolean, summary.ConvertedType.SpecialType);
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
Assert.False(summary.IsCompileTimeConstant);
Assert.False(summary.ConstantValue.HasValue);
}
}
[Fact]
public void PointerComparison_PointerPointer()
{
var text = @"
unsafe class C
{
void M(byte* b, byte** bb)
{
bool result;
result = b == bb;
result = b != bb;
result = b <= bb;
result = b >= bb;
result = b < bb;
result = b > bb;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerComparison_Numeric()
{
var text = @"
unsafe class C
{
void M(char* p, int i, uint ui, long l, ulong ul)
{
bool result;
result = p == i;
result = p != i;
result = p <= i;
result = p >= i;
result = p < i;
result = p > i;
result = p == ui;
result = p != ui;
result = p <= ui;
result = p >= ui;
result = p < ui;
result = p > ui;
result = p == l;
result = p != l;
result = p <= l;
result = p >= l;
result = p < l;
result = p > l;
result = p == ul;
result = p != ul;
result = p <= ul;
result = p >= ul;
result = p < ul;
result = p > ul;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'int'
// result = p == i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == i").WithArguments("==", "char*", "int"),
// (9,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'int'
// result = p != i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != i").WithArguments("!=", "char*", "int"),
// (10,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'int'
// result = p <= i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= i").WithArguments("<=", "char*", "int"),
// (11,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'int'
// result = p >= i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= i").WithArguments(">=", "char*", "int"),
// (12,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'int'
// result = p < i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < i").WithArguments("<", "char*", "int"),
// (13,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'int'
// result = p > i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > i").WithArguments(">", "char*", "int"),
// (15,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'uint'
// result = p == ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == ui").WithArguments("==", "char*", "uint"),
// (16,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'uint'
// result = p != ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != ui").WithArguments("!=", "char*", "uint"),
// (17,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'uint'
// result = p <= ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= ui").WithArguments("<=", "char*", "uint"),
// (18,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'uint'
// result = p >= ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= ui").WithArguments(">=", "char*", "uint"),
// (19,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'uint'
// result = p < ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < ui").WithArguments("<", "char*", "uint"),
// (20,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'uint'
// result = p > ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > ui").WithArguments(">", "char*", "uint"),
// (22,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'long'
// result = p == l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == l").WithArguments("==", "char*", "long"),
// (23,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'long'
// result = p != l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != l").WithArguments("!=", "char*", "long"),
// (24,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'long'
// result = p <= l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= l").WithArguments("<=", "char*", "long"),
// (25,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'long'
// result = p >= l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= l").WithArguments(">=", "char*", "long"),
// (26,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'long'
// result = p < l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < l").WithArguments("<", "char*", "long"),
// (27,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'long'
// result = p > l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > l").WithArguments(">", "char*", "long"),
// (29,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'ulong'
// result = p == ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == ul").WithArguments("==", "char*", "ulong"),
// (30,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'ulong'
// result = p != ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != ul").WithArguments("!=", "char*", "ulong"),
// (31,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'ulong'
// result = p <= ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= ul").WithArguments("<=", "char*", "ulong"),
// (32,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'ulong'
// result = p >= ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= ul").WithArguments(">=", "char*", "ulong"),
// (33,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'ulong'
// result = p < ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < ul").WithArguments("<", "char*", "ulong"),
// (34,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'ulong'
// result = p > ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > ul").WithArguments(">", "char*", "ulong"));
}
#endregion Pointer comparison tests
#region Fixed statement diagnostics
[Fact]
public void ERR_BadFixedInitType()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (int p = &x) //not a pointer
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int p = &x) //not a pointer
Diagnostic(ErrorCode.ERR_BadFixedInitType, "p = &x"));
}
[Fact]
public void ERR_FixedMustInit()
{
var text = @"
unsafe class C
{
void M()
{
fixed (int* p) //missing initializer
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,21): error CS0210: You must provide an initializer in a fixed or using statement declaration
// fixed (int* p) //missing initializer
Diagnostic(ErrorCode.ERR_FixedMustInit, "p"));
}
[Fact]
public void ERR_ImplicitlyTypedLocalCannotBeFixed1()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (var p = &x) //implicitly typed
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,20): error CS0821: Implicitly-typed local variables cannot be fixed
// fixed (var p = &x) //implicitly typed
Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "p = &x"));
}
[Fact]
public void ERR_ImplicitlyTypedLocalCannotBeFixed2()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (var p = &x) //not implicitly typed
{
}
}
}
class var
{
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (var p = &x) //not implicitly typed
Diagnostic(ErrorCode.ERR_BadFixedInitType, "p = &x"));
}
[Fact]
public void ERR_MultiTypeInDeclaration()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,29): error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_MultiTypeInDeclaration, "var"),
// (8,33): error CS1026: ) expected
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_CloseParenExpected, "q"),
// (8,38): error CS1002: ; expected
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"),
// (8,38): error CS1513: } expected
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_RbraceExpected, ")"),
// (8,29): error CS0210: You must provide an initializer in a fixed or using statement declaration
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_FixedMustInit, "var"),
// (8,33): error CS0103: The name 'q' does not exist in the current context
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_NameNotInContext, "q").WithArguments("q"));
}
[Fact]
public void ERR_BadCastInFixed_String()
{
var text = @"
unsafe class C
{
public NotString n;
void M()
{
fixed (char* p = (string)""hello"")
{
}
fixed (char* p = (string)n)
{
}
}
}
class NotString
{
unsafe public static implicit operator string(NotString n)
{
return null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,22): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null
// public NotString n;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null"));
}
[Fact]
public void ERR_BadCastInFixed_Array()
{
var text = @"
unsafe class C
{
public NotArray n;
void M()
{
fixed (byte* p = (byte[])new byte[0])
{
}
fixed (int* p = (int[])n)
{
}
}
}
class NotArray
{
unsafe public static implicit operator int[](NotArray n)
{
return null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,21): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null
// public NotArray n;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null"));
}
[Fact]
public void ERR_BadCastInFixed_Pointer()
{
var text = @"
unsafe class C
{
public byte x;
public NotPointer n;
void M()
{
fixed (byte* p = (byte*)&x)
{
}
fixed (int* p = n) //CS0213 (confusing, but matches dev10)
{
}
fixed (int* p = (int*)n)
{
}
}
}
class NotPointer
{
unsafe public static implicit operator int*(NotPointer n)
{
return null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (byte* p = (byte*)&x)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(byte*)&x").WithLocation(9, 26),
// (13,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = n) //CS0213 (confusing, but matches dev10)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "n").WithLocation(13, 25),
// (17,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (int*)n)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(int*)n").WithLocation(17, 25),
// (5,23): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null
// public NotPointer n;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null").WithLocation(5, 23)
);
}
[Fact]
public void ERR_FixedLocalInLambda()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
System.Action a;
a = () => Console.WriteLine(*p);
a = () => Console.WriteLine(*q);
a = () => Console.WriteLine(*r);
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (15,42): error CS1764: Cannot use fixed local 'p' inside an anonymous method, lambda expression, or query expression
// a = () => Console.WriteLine(*p);
Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "p").WithArguments("p"),
// (16,42): error CS1764: Cannot use fixed local 'q' inside an anonymous method, lambda expression, or query expression
// a = () => Console.WriteLine(*q);
Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "q").WithArguments("q"),
// (17,42): error CS1764: Cannot use fixed local 'r' inside an anonymous method, lambda expression, or query expression
// a = () => Console.WriteLine(*r);
Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "r").WithArguments("r"));
}
[Fact]
public void NormalAddressOfInFixedStatement()
{
var text = @"
class Program
{
int x;
int[] a;
unsafe static void Main()
{
Program p = new Program();
int q;
fixed (int* px = (&(p.a[*(&q)]))) //fine
{
}
fixed (int* px = &(p.a[*(&p.x)])) //CS0212
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (15,34): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// fixed (int* px = &(p.a[*(&p.x)])) //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&p.x"),
// (5,11): warning CS0649: Field 'Program.a' is never assigned to, and will always have its default value null
// int[] a;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("Program.a", "null"));
}
[Fact]
public void StackAllocInFixedStatement()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = stackalloc int[2]) //CS0213 - already fixed
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = stackalloc int[2]) //CS0213 - already fixed
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int[2]").WithLocation(6, 25));
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = stackalloc int[2]) //CS0213 - already fixed
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int[2]").WithLocation(6, 25));
}
[Fact]
public void FixedInitializerRefersToPreviousVariable()
{
var text = @"
unsafe class C
{
int f;
int[] a;
void Goo()
{
fixed (int* q = &f, r = &q[1]) //CS0213
{
}
fixed (int* q = &f, r = &a[*q]) //fine
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,33): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* q = &f, r = &q[1]) //CS0213
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&q[1]"),
// (5,11): warning CS0649: Field 'C.a' is never assigned to, and will always have its default value null
// int[] a;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("C.a", "null"));
}
[Fact]
public void NormalInitializerType_Null()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = null)
{
}
fixed (int* p = &null)
{
}
fixed (int* p = _)
{
}
fixed (int* p = &_)
{
}
fixed (int* p = ()=>throw null)
{
}
fixed (int* p = &(()=>throw null))
{
}
}
}
";
// Confusing, but matches Dev10.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = null)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "null").WithLocation(6, 25),
// (10,26): error CS0211: Cannot take the address of the given expression
// fixed (int* p = &null)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "null").WithLocation(10, 26),
// (14,25): error CS0103: The name '_' does not exist in the current context
// fixed (int* p = _)
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 25),
// (18,26): error CS0103: The name '_' does not exist in the current context
// fixed (int* p = &_)
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(18, 26),
// (22,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = ()=>throw null)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "()=>throw null").WithLocation(22, 25),
// (26,27): error CS0211: Cannot take the address of the given expression
// fixed (int* p = &(()=>throw null))
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "()=>throw null").WithLocation(26, 27)
);
}
[Fact]
public void NormalInitializerType_Lambda()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = (x => x))
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (x => x))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "x => x").WithLocation(6, 26));
}
[Fact]
public void NormalInitializerType_MethodGroup()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = Main)
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = Main)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "Main").WithLocation(6, 25));
}
[Fact]
public void NormalInitializerType_String()
{
var text = @"
class Program
{
unsafe static void Main()
{
string s = ""hello"";
fixed (char* p = s) //fine
{
}
fixed (void* p = s) //fine
{
}
fixed (int* p = s) //can't convert char* to int*
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?)
// fixed (int* p = s) //can't convert char* to int*
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("char*", "int*"));
}
[Fact]
public void NormalInitializerType_ArrayOfManaged()
{
var text = @"
class Program
{
unsafe static void Main()
{
string[] a = new string[2];
fixed (void* p = a) //string* is not a valid type
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// fixed (void* p = a)
Diagnostic(ErrorCode.ERR_ManagedAddr, "a").WithArguments("string"));
}
[Fact]
public void NormalInitializerType_ArrayOfGenericStruct()
{
var text = @"
public struct MyStruct<T>
{
public T field;
}
class Program
{
unsafe static void Main()
{
var a = new MyStruct<int>[2];
a[0].field = 42;
fixed (MyStruct<int>* p = a)
{
System.Console.Write(p->field);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42");
}
[Fact]
public void NormalInitializerType_ArrayOfGenericStruct_RequiresCSharp8()
{
var text = @"
public struct MyStruct<T>
{
public T field;
}
class Program
{
unsafe static void Main()
{
var a = new MyStruct<int>[2];
fixed (void* p = a)
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (13,26): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater.
// fixed (void* p = a)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "a").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 26));
}
[Fact]
public void NormalInitializerType_Array()
{
var text = @"
class Program
{
unsafe static void Main()
{
char[] a = new char[2];
fixed (char* p = a) //fine
{
}
fixed (void* p = a) //fine
{
}
fixed (int* p = a) //can't convert char* to int*
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?)
// fixed (int* p = a) //can't convert char* to int*
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("char*", "int*"));
}
[Fact]
public void NormalInitializerType_MultiDimensionalArray()
{
var text = @"
class Program
{
unsafe static void Main()
{
char[,] a = new char[2,2];
fixed (char* p = a) //fine
{
}
fixed (void* p = a) //fine
{
}
fixed (int* p = a) //can't convert char* to int*
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?)
// fixed (int* p = a) //can't convert char* to int*
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("char*", "int*"));
}
[Fact]
public void NormalInitializerType_JaggedArray()
{
var text = @"
class Program
{
unsafe static void Main()
{
char[][] a = new char[2][];
fixed (void* p = a) //char[]* is not a valid type
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('char[]')
// fixed (void* p = a) //char[]* is not a valid type
Diagnostic(ErrorCode.ERR_ManagedAddr, "a").WithArguments("char[]"));
}
#endregion Fixed statement diagnostics
#region Fixed statement semantic model tests
[Fact]
public void FixedSemanticModelDeclaredSymbols()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(3).Reverse().ToArray();
var declaredSymbols = declarators.Select(syntax => (ILocalSymbol)model.GetDeclaredSymbol(syntax)).ToArray();
foreach (var symbol in declaredSymbols)
{
Assert.NotNull(symbol);
Assert.Equal(LocalDeclarationKind.FixedVariable, symbol.GetSymbol().DeclarationKind);
Assert.True(((ILocalSymbol)symbol).IsFixed);
ITypeSymbol type = symbol.Type;
Assert.Equal(TypeKind.Pointer, type.TypeKind);
Assert.Equal(SpecialType.System_Char, ((IPointerTypeSymbol)type).PointedAtType.SpecialType);
}
}
[Fact]
public void FixedSemanticModelSymbolInfo()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.WriteLine(*p);
Console.WriteLine(*q);
Console.WriteLine(*r);
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var stringSymbol = compilation.GetSpecialType(SpecialType.System_String);
var charSymbol = compilation.GetSpecialType(SpecialType.System_Char);
var charPointerSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(charSymbol));
const int numSymbols = 3;
var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(numSymbols).Reverse().ToArray();
var dereferences = tree.GetCompilationUnitRoot().DescendantNodes().Where(syntax => syntax.IsKind(SyntaxKind.PointerIndirectionExpression)).ToArray();
Assert.Equal(numSymbols, dereferences.Length);
var declaredSymbols = declarators.Select(syntax => (ILocalSymbol)model.GetDeclaredSymbol(syntax)).ToArray();
var initializerSummaries = declarators.Select(syntax => model.GetSemanticInfoSummary(syntax.Initializer.Value)).ToArray();
for (int i = 0; i < numSymbols; i++)
{
var summary = initializerSummaries[i];
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(charPointerSymbol, summary.ConvertedType.GetSymbol());
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
}
var summary0 = initializerSummaries[0];
Assert.Null(summary0.Symbol);
Assert.Equal(charPointerSymbol, summary0.Type.GetSymbol());
var summary1 = initializerSummaries[1];
var arraySymbol = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
Assert.Equal(arraySymbol, summary1.Symbol.GetSymbol());
Assert.Equal(arraySymbol.Type, summary1.Type.GetSymbol());
var summary2 = initializerSummaries[2];
Assert.Null(summary2.Symbol);
Assert.Equal(stringSymbol, summary2.Type.GetSymbol());
var accessSymbolInfos = dereferences.Select(syntax => model.GetSymbolInfo(((PrefixUnaryExpressionSyntax)syntax).Operand)).ToArray();
for (int i = 0; i < numSymbols; i++)
{
SymbolInfo info = accessSymbolInfos[i];
Assert.Equal(declaredSymbols[i], info.Symbol);
Assert.Equal(0, info.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, info.CandidateReason);
}
}
[Fact]
public void FixedSemanticModelSymbolInfoConversions()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (void* p = &c.c, q = c.a, r = ""hello"")
{
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var stringSymbol = compilation.GetSpecialType(SpecialType.System_String);
var charSymbol = compilation.GetSpecialType(SpecialType.System_Char);
var charPointerSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(charSymbol));
var voidSymbol = compilation.GetSpecialType(SpecialType.System_Void);
var voidPointerSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(voidSymbol));
const int numSymbols = 3;
var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(numSymbols).Reverse().ToArray();
var initializerSummaries = declarators.Select(syntax => model.GetSemanticInfoSummary(syntax.Initializer.Value)).ToArray();
for (int i = 0; i < numSymbols; i++)
{
var summary = initializerSummaries[i];
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
}
var summary0 = initializerSummaries[0];
Assert.Null(summary0.Symbol);
Assert.Equal(charPointerSymbol, summary0.Type.GetSymbol());
Assert.Equal(voidPointerSymbol, summary0.ConvertedType.GetSymbol());
Assert.Equal(Conversion.PointerToVoid, summary0.ImplicitConversion);
var summary1 = initializerSummaries[1];
var arraySymbol = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
Assert.Equal(arraySymbol, summary1.Symbol.GetSymbol());
Assert.Equal(arraySymbol.Type, summary1.Type.GetSymbol());
Assert.Equal(voidPointerSymbol, summary1.ConvertedType.GetSymbol());
Assert.Equal(Conversion.PointerToVoid, summary1.ImplicitConversion);
var summary2 = initializerSummaries[2];
Assert.Null(summary2.Symbol);
Assert.Equal(stringSymbol, summary2.Type.GetSymbol());
Assert.Equal(voidPointerSymbol, summary2.ConvertedType.GetSymbol());
Assert.Equal(Conversion.PointerToVoid, summary2.ImplicitConversion);
}
#endregion Fixed statement semantic model tests
#region sizeof diagnostic tests
[Fact]
public void SizeOfManaged()
{
var text = @"
unsafe class C
{
void M<T>(T t)
{
int x;
x = sizeof(T); //CS0208
x = sizeof(C); //CS0208
x = sizeof(S); //CS0208
}
}
public struct S
{
public string s;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
// x = sizeof(T); //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(T)").WithArguments("T"),
// (8,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')
// x = sizeof(C); //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(C)").WithArguments("C"),
// (9,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// x = sizeof(S); //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(S)").WithArguments("S"));
}
[Fact]
public void SizeOfUnsafe1()
{
var template = @"
{0} struct S
{{
{1} void M()
{{
int x;
x = sizeof(S); // Type isn't unsafe, but expression is.
}}
}}
";
CompareUnsafeDiagnostics(template,
// (7,13): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(S);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(S)").WithArguments("S"));
}
[Fact]
public void SizeOfUnsafe2()
{
var template = @"
{0} class C
{{
{1} void M()
{{
int x;
x = sizeof(int*);
x = sizeof(int**);
x = sizeof(void*);
x = sizeof(void**);
}}
}}
";
// CONSIDER: Dev10 reports ERR_SizeofUnsafe for each sizeof, but that seems redundant.
CompareUnsafeDiagnostics(template,
// (7,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(int*);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,13): error CS0233: 'int*' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(int*);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(int*)").WithArguments("int*"),
// (8,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(int**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(int**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int**"),
// (8,13): error CS0233: 'int**' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(int**);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(int**)").WithArguments("int**"),
// (9,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(void*);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"),
// (9,13): error CS0233: 'void*' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(void*);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(void*)").WithArguments("void*"),
// (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(void**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"),
// (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(void**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void**"),
// (10,13): error CS0233: 'void**' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(void**);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(void**)").WithArguments("void**")
);
}
[Fact]
public void SizeOfUnsafeInIterator()
{
var text = @"
struct S
{
System.Collections.Generic.IEnumerable<int> M()
{
yield return sizeof(S);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,22): error CS1629: Unsafe code may not appear in iterators
// yield return sizeof(S);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "sizeof(S)"));
}
[Fact]
public void SizeOfNonType1()
{
var text = @"
unsafe struct S
{
void M()
{
S s = new S();
int i = 0;
i = sizeof(s);
i = sizeof(i);
i = sizeof(M);
}
}
";
// Not identical to Dev10, but same meaning.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,20): error CS0118: 's' is a variable but is used like a type
// i = sizeof(s);
Diagnostic(ErrorCode.ERR_BadSKknown, "s").WithArguments("s", "variable", "type"),
// (10,20): error CS0118: 'i' is a variable but is used like a type
// i = sizeof(i);
Diagnostic(ErrorCode.ERR_BadSKknown, "i").WithArguments("i", "variable", "type"),
// (11,20): error CS0246: The type or namespace name 'M' could not be found (are you missing a using directive or an assembly reference?)
// i = sizeof(M);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M").WithArguments("M"),
// (6,11): warning CS0219: The variable 's' is assigned but its value is never used
// S s = new S();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s"));
}
[Fact]
public void SizeOfNonType2()
{
var text = @"
unsafe struct S
{
void M()
{
int i;
i = sizeof(void);
i = sizeof(this); //parser error
i = sizeof(x => x); //parser error
}
}
";
// Not identical to Dev10, but same meaning.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,20): error CS1547: Keyword 'void' cannot be used in this context
// i = sizeof(void);
Diagnostic(ErrorCode.ERR_NoVoidHere, "void"),
// (8,20): error CS1031: Type expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_TypeExpected, "this"),
// (8,20): error CS1026: ) expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_CloseParenExpected, "this"),
// (8,20): error CS1002: ; expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "this"),
// (8,24): error CS1002: ; expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"),
// (8,24): error CS1513: } expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_RbraceExpected, ")"),
// (9,22): error CS1026: ) expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_CloseParenExpected, "=>"),
// (9,22): error CS1002: ; expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=>"),
// (9,22): error CS1513: } expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>"),
// (9,26): error CS1002: ; expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"),
// (9,26): error CS1513: } expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_RbraceExpected, ")"),
// (9,20): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x"),
// (9,25): error CS0103: The name 'x' does not exist in the current context
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"));
}
[Fact, WorkItem(529318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529318")]
public void SizeOfNull()
{
string text = @"
class Program
{
int F1 = sizeof(null);
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,21): error CS1031: Type expected
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_TypeExpected, "null"),
// (4,21): error CS1026: ) expected
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "null"),
// (4,21): error CS1003: Syntax error, ',' expected
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_SyntaxError, "null").WithArguments(",", "null"),
// (4,14): error CS0233: '?' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(").WithArguments("?"));
}
#endregion sizeof diagnostic tests
#region sizeof semantic model tests
private static readonly Dictionary<SpecialType, int> s_specialTypeSizeOfMap = new Dictionary<SpecialType, int>
{
{ SpecialType.System_SByte, 1 },
{ SpecialType.System_Byte, 1 },
{ SpecialType.System_Int16, 2 },
{ SpecialType.System_UInt16, 2 },
{ SpecialType.System_Int32, 4 },
{ SpecialType.System_UInt32, 4 },
{ SpecialType.System_Int64, 8 },
{ SpecialType.System_UInt64, 8 },
{ SpecialType.System_Char, 2 },
{ SpecialType.System_Single, 4 },
{ SpecialType.System_Double, 8 },
{ SpecialType.System_Boolean, 1 },
{ SpecialType.System_Decimal, 16 },
};
[Fact]
public void SizeOfSemanticModelSafe()
{
var text = @"
class Program
{
static void Main()
{
int x;
x = sizeof(sbyte);
x = sizeof(byte);
x = sizeof(short);
x = sizeof(ushort);
x = sizeof(int);
x = sizeof(uint);
x = sizeof(long);
x = sizeof(ulong);
x = sizeof(char);
x = sizeof(float);
x = sizeof(double);
x = sizeof(bool);
x = sizeof(decimal); //Supported by dev10, but not spec.
}
}
";
// NB: not unsafe
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>();
foreach (var syntax in syntaxes)
{
var typeSummary = model.GetSemanticInfoSummary(syntax.Type);
var type = typeSummary.Symbol as ITypeSymbol;
Assert.NotNull(type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.NotEqual(SpecialType.None, type.SpecialType);
Assert.Equal(type, typeSummary.Type);
Assert.Equal(type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var sizeOfSummary = model.GetSemanticInfoSummary(syntax);
Assert.Null(sizeOfSummary.Symbol);
Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason);
Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType);
Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType);
Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion);
Assert.Equal(0, sizeOfSummary.MethodGroup.Length);
Assert.Null(sizeOfSummary.Alias);
Assert.True(sizeOfSummary.IsCompileTimeConstant);
Assert.Equal(s_specialTypeSizeOfMap[type.SpecialType], sizeOfSummary.ConstantValue);
}
}
[Fact]
public void SizeOfSemanticModelEnum()
{
var text = @"
class Program
{
static void Main()
{
int x;
x = sizeof(E1);
x = sizeof(E2);
}
}
enum E1 : short
{
A
}
enum E2 : long
{
A
}
";
// NB: not unsafe
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>();
foreach (var syntax in syntaxes)
{
var typeSummary = model.GetSemanticInfoSummary(syntax.Type);
var type = typeSummary.Symbol as ITypeSymbol;
Assert.NotNull(type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.Equal(TypeKind.Enum, type.TypeKind);
Assert.Equal(type, typeSummary.Type);
Assert.Equal(type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var sizeOfSummary = model.GetSemanticInfoSummary(syntax);
Assert.Null(sizeOfSummary.Symbol);
Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason);
Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType);
Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType);
Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion);
Assert.Equal(0, sizeOfSummary.MethodGroup.Length);
Assert.Null(sizeOfSummary.Alias);
Assert.True(sizeOfSummary.IsCompileTimeConstant);
Assert.Equal(s_specialTypeSizeOfMap[type.GetEnumUnderlyingType().SpecialType], sizeOfSummary.ConstantValue);
}
}
[Fact]
public void SizeOfSemanticModelUnsafe()
{
var text = @"
struct Outer
{
unsafe static void Main()
{
int x;
x = sizeof(Outer);
x = sizeof(Inner);
x = sizeof(Outer*);
x = sizeof(Inner*);
x = sizeof(Outer**);
x = sizeof(Inner**);
}
struct Inner
{
}
}
";
// NB: not unsafe
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>();
foreach (var syntax in syntaxes)
{
var typeSummary = model.GetSemanticInfoSummary(syntax.Type);
var type = typeSummary.Symbol as ITypeSymbol;
Assert.NotNull(type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.Equal(SpecialType.None, type.SpecialType);
Assert.Equal(type, typeSummary.Type);
Assert.Equal(type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var sizeOfSummary = model.GetSemanticInfoSummary(syntax);
Assert.Null(sizeOfSummary.Symbol);
Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason);
Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType);
Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType);
Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion);
Assert.Equal(0, sizeOfSummary.MethodGroup.Length);
Assert.Null(sizeOfSummary.Alias);
Assert.False(sizeOfSummary.IsCompileTimeConstant);
Assert.False(sizeOfSummary.ConstantValue.HasValue);
}
}
#endregion sizeof semantic model tests
#region stackalloc diagnostic tests
[Fact]
public void StackAllocUnsafe()
{
var template = @"
{0} struct S
{{
{1} void M()
{{
int* p = stackalloc int[1];
}}
}}
";
CompareUnsafeDiagnostics(template,
// (6,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1]")
);
}
[Fact]
public void StackAllocUnsafeInIterator()
{
var text = @"
struct S
{
System.Collections.Generic.IEnumerable<int> M()
{
var p = stackalloc int[1];
yield return 1;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,17): error CS1629: Unsafe code may not appear in iterators
// var p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "stackalloc int[1]"));
}
[Fact]
public void ERR_NegativeStackAllocSize()
{
var text = @"
unsafe struct S
{
void M()
{
int* p = stackalloc int[-1];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,33): error CS0247: Cannot use a negative size with stackalloc
// int* p = stackalloc int[-1];
Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, "-1"));
}
[Fact]
public void ERR_StackallocInCatchFinally_Catch()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
catch
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
});
static int M(System.Action action)
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
catch
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (17,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (23,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (32,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (51,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (57,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (66,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"));
}
[Fact]
public void ERR_StackallocInCatchFinally_Finally()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
finally
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
});
static int M(System.Action action)
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
finally
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (17,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (23,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (32,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (51,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (57,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (66,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"));
}
[Fact]
public void ERR_BadStackAllocExpr()
{
var text = @"
unsafe class C
{
static void Main()
{
int* p = stackalloc int;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,29): error CS1575: A stackalloc expression requires [] after type
// int* p = stackalloc int;
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int"));
}
[Fact]
public void StackAllocCountType()
{
var text = @"
unsafe class C
{
static void Main()
{
{ int* p = stackalloc int[1]; } //fine
{ int* p = stackalloc int[1L]; } //CS0266 (could cast), even though constant value is fine
{ int* p = stackalloc int['c']; } //fine
{ int* p = stackalloc int[""hello""]; } // CS0029 (no conversion)
{ int* p = stackalloc int[Main]; } //CS0428 (method group conversion)
{ int* p = stackalloc int[x => x]; } //CS1660 (lambda conversion)
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,35): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
// { int* p = stackalloc int[1L]; } //CS0266 (could cast), even though constant value is fine
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int"),
// (9,35): error CS0029: Cannot implicitly convert type 'string' to 'int'
// { int* p = stackalloc int["hello"]; } // CS0029 (no conversion)
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int"),
// (10,35): error CS0428: Cannot convert method group 'Main' to non-delegate type 'int'. Did you intend to invoke the method?
// { int* p = stackalloc int[Main]; } //CS0428 (method group conversion)
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "int"),
// (11,35): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type
// { int* p = stackalloc int[x => x]; } //CS1660 (lambda conversion)
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "int"));
}
[Fact]
public void StackAllocCountQuantity()
{
// These all give unhelpful parser errors in Dev10. Let's see if we can do better.
var text = @"
unsafe class C
{
static void Main()
{
{ int* p = stackalloc int[]; }
{ int* p = stackalloc int[1, 1]; }
{ int* p = stackalloc int[][]; }
{ int* p = stackalloc int[][1]; }
{ int* p = stackalloc int[1][]; }
{ int* p = stackalloc int[1][1]; }
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,34): error CS1586: Array creation must have array size or array initializer
// { int* p = stackalloc int[]; }
Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34),
// (7,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[1, 1]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1, 1]").WithLocation(7, 31),
// (8,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[][]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(8, 31),
// (8,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[][]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(8, 31),
// (9,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[][1]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(9, 31),
// (9,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[][1]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][1]").WithLocation(9, 31),
// (10,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[1][]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(10, 31),
// (10,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[1][]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1][]").WithLocation(10, 31),
// (11,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[1][1]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(11, 31),
// (11,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[1][1]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1][1]").WithLocation(11, 31)
);
}
[Fact]
public void StackAllocExplicitConversion()
{
var text = @"
unsafe class C
{
static void Main()
{
{ var p = (int*)stackalloc int[1]; }
{ var p = (void*)stackalloc int[1]; }
{ var p = (C)stackalloc int[1]; }
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// { var p = (int*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(int*)stackalloc int[1]").WithArguments("int", "int*").WithLocation(6, 19),
// (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'void*' is not possible.
// { var p = (void*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(void*)stackalloc int[1]").WithArguments("int", "void*").WithLocation(7, 19),
// (8,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'C' is not possible.
// { var p = (C)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(C)stackalloc int[1]").WithArguments("int", "C").WithLocation(8, 19));
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (6,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// { var p = (int*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(int*)stackalloc int[1]").WithArguments("int", "int*").WithLocation(6, 19),
// (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'void*' is not possible.
// { var p = (void*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(void*)stackalloc int[1]").WithArguments("int", "void*").WithLocation(7, 19),
// (8,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'C' is not possible.
// { var p = (C)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(C)stackalloc int[1]").WithArguments("int", "C").WithLocation(8, 19));
}
[Fact]
public void StackAllocNotExpression_FieldInitializer()
{
var text = @"
unsafe class C
{
int* p = stackalloc int[1];
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (4,14): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(4, 14)
);
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (4,14): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "int*").WithLocation(4, 14)
);
}
[Fact]
public void StackAllocNotExpression_DefaultParameterValue()
{
var text = @"
unsafe class C
{
void M(int* p = stackalloc int[1])
{
}
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,21): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void M(int* p = stackalloc int[1])
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "stackalloc int[1]").WithArguments("p").WithLocation(4, 21)
);
}
[Fact]
public void StackAllocNotExpression_ForLoop()
{
var text = @"
unsafe class C
{
void M()
{
for (int* p = stackalloc int[1]; p != null; p++) //fine
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void StackAllocNotExpression_GlobalDeclaration_01()
{
var text = @"
unsafe int* p = stackalloc int[1];
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (2,17): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// unsafe int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "int*").WithLocation(2, 17)
);
}
[Fact]
public void StackAllocNotExpression_GlobalDeclaration_02()
{
var text = @"
using System;
Span<int> p = stackalloc int[1];
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (3,1): error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct.
// Span<int> p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "Span<int>").WithArguments("System.Span<int>").WithLocation(3, 1)
);
}
[Fact]
public void StackAllocNotExpression_GlobalDeclaration_03()
{
var text = @"
var p = stackalloc int[1];
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (2,1): error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct.
// var p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "var").WithArguments("System.Span<int>").WithLocation(2, 1)
);
}
#endregion stackalloc diagnostic tests
#region stackalloc semantic model tests
[Fact]
public void StackAllocSemanticModel()
{
var text = @"
class C
{
unsafe static void Main()
{
const short count = 20;
void* p = stackalloc char[count];
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var stackAllocSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().Single();
var arrayTypeSyntax = (ArrayTypeSyntax)stackAllocSyntax.Type;
var typeSyntax = arrayTypeSyntax.ElementType;
var countSyntax = arrayTypeSyntax.RankSpecifiers.Single().Sizes.Single();
var stackAllocSummary = model.GetSemanticInfoSummary(stackAllocSyntax);
Assert.Equal(SpecialType.System_Char, ((IPointerTypeSymbol)stackAllocSummary.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Void, ((IPointerTypeSymbol)stackAllocSummary.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(Conversion.PointerToVoid, stackAllocSummary.ImplicitConversion);
Assert.Null(stackAllocSummary.Symbol);
Assert.Equal(0, stackAllocSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, stackAllocSummary.CandidateReason);
Assert.Equal(0, stackAllocSummary.MethodGroup.Length);
Assert.Null(stackAllocSummary.Alias);
Assert.False(stackAllocSummary.IsCompileTimeConstant);
Assert.False(stackAllocSummary.ConstantValue.HasValue);
var typeSummary = model.GetSemanticInfoSummary(typeSyntax);
Assert.Equal(SpecialType.System_Char, typeSummary.Type.SpecialType);
Assert.Equal(typeSummary.Type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Equal(typeSummary.Symbol, typeSummary.Type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.Equal(0, typeSummary.MethodGroup.Length);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var countSummary = model.GetSemanticInfoSummary(countSyntax);
Assert.Equal(SpecialType.System_Int16, countSummary.Type.SpecialType);
Assert.Equal(SpecialType.System_Int32, countSummary.ConvertedType.SpecialType);
Assert.Equal(Conversion.ImplicitNumeric, countSummary.ImplicitConversion);
var countSymbol = (ILocalSymbol)countSummary.Symbol;
Assert.Equal(countSummary.Type, countSymbol.Type);
Assert.Equal("count", countSymbol.Name);
Assert.Equal(0, countSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, countSummary.CandidateReason);
Assert.Equal(0, countSummary.MethodGroup.Length);
Assert.Null(countSummary.Alias);
Assert.True(countSummary.IsCompileTimeConstant);
Assert.True(countSummary.ConstantValue.HasValue);
Assert.Equal((short)20, countSummary.ConstantValue.Value);
}
#endregion stackalloc semantic model tests
#region PointerTypes tests
[WorkItem(5712, "https://github.com/dotnet/roslyn/issues/5712")]
[Fact]
public void PathologicalRefStructPtrMultiDimensionalArray()
{
var text = @"
class C
{
class Goo3 {
internal struct Struct1<U> {}
}
unsafe void NMethodCecilNameHelper_Parameter_AllTogether<U>(ref Goo3.Struct1<int>**[][,,] ppi) { }
}
";
CreateCompilation(text, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics();
}
[WorkItem(543990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543990")]
[Fact]
public void PointerTypeInVolatileField()
{
string text = @"
unsafe class Test
{
static volatile int *px;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,23): warning CS0169: The field 'Test.px' is never used
// static volatile int *px;
Diagnostic(ErrorCode.WRN_UnreferencedField, "px").WithArguments("Test.px"));
}
[WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")]
[Fact]
public void PointerTypesAsTypeArgs()
{
string text = @"
class A
{
public class B{}
}
class C<T> : A
{
private static C<T*[]>.B b;
}
";
var expected = new[]
{
// (8,30): warning CS0169: The field 'C<T>.b' is never used
// private static C<T*[]>.B b;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b")
};
CreateCompilation(text).VerifyDiagnostics(expected);
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected);
}
[WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")]
[WorkItem(544232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544232")]
[Fact]
public void PointerTypesAsTypeArgs2()
{
string text = @"
class A
{
public class B{}
}
class C<T> : A
{
// Dev10 and Roslyn both do not report an error here because they don't look for ERR_ManagedAddr until
// late in the binding process - at which point the type has been resolved to A.B.
private static C<T*[]>.B b;
// Workarounds
private static B b1;
private static A.B b2;
// Dev10 and Roslyn produce the same diagnostic here.
private static C<T*[]> c;
}
";
var expected = new[]
{
// (17,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
// private static C<T*[]> c;
Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("T"),
// (10,30): warning CS0169: The field 'C<T>.b' is never used
// private static C<T*[]>.B b;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b"),
// (13,22): warning CS0169: The field 'C<T>.b1' is never used
// private static B b1;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b1").WithArguments("C<T>.b1"),
// (14,24): warning CS0169: The field 'C<T>.b2' is never used
// private static A.B b2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b2").WithArguments("C<T>.b2"),
// (17,28): warning CS0169: The field 'C<T>.c' is never used
// private static C<T*[]> c;
Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c")
};
CreateCompilation(text).VerifyDiagnostics(expected);
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected);
}
[WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")]
[WorkItem(544232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544232")]
[Fact]
public void PointerTypesAsTypeArgs3()
{
string text = @"
class A
{
public class B{}
}
class C<T> : A
{
// Dev10 and Roslyn both do not report an error here because they don't look for ERR_ManagedAddr until
// late in the binding process - at which point the type has been resolved to A.B.
private static C<string*[]>.B b;
// Dev10 and Roslyn produce the same diagnostic here.
private static C<string*[]> c;
}
";
var expected = new[]
{
// (15,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// private static C<T*[]> c;
Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("string"),
// (10,30): warning CS0169: The field 'C<T>.b' is never used
// private static C<T*[]>.B b;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b"),
// (15,28): warning CS0169: The field 'C<T>.c' is never used
// private static C<T*[]> c;
Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c")
};
CreateCompilation(text).VerifyDiagnostics(expected);
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected);
}
[Fact]
[WorkItem(37051, "https://github.com/dotnet/roslyn/issues/37051")]
public void GenericPointer_Override()
{
var csharp = @"
public unsafe class A
{
public virtual T* M<T>() where T : unmanaged => throw null!;
}
public unsafe class B : A
{
public override T* M<T>() => throw null!;
}
";
var comp = CreateCompilation(csharp, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics();
}
#endregion PointerTypes tests
#region misc unsafe tests
[Fact, WorkItem(543988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543988")]
public void UnsafeFieldInitializerInStruct()
{
string sourceCode = @"
public struct Test
{
static unsafe int*[] myArray = new int*[100];
}
";
var tree = Parse(sourceCode);
var comp = CreateCompilation(tree, options: TestOptions.UnsafeReleaseDll);
var model = comp.GetSemanticModel(tree);
model.GetDiagnostics().Verify();
}
[Fact, WorkItem(544143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544143")]
public void ConvertFromPointerToSelf()
{
string text = @"
struct C
{
unsafe static public implicit operator long*(C* i)
{
return null;
}
unsafe static void Main()
{
C c = new C();
}
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (4,44): error CS0556: User-defined conversion must convert to or from the enclosing type
// unsafe static public implicit operator long*(C* i)
Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "long*"),
// (10,11): warning CS0219: The variable 'c' is assigned but its value is never used
// C c = new C();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c"));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
var info = model.GetSemanticInfoSummary(parameterSyntax.Type);
}
[Fact]
public void PointerVolatileField()
{
string text = @"
unsafe class C
{
volatile int* p; //Spec section 18.2 specifically allows this.
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,19): warning CS0169: The field 'C.p' is never used
// volatile int* p; //Spec section 18.2 specifically allows this.
Diagnostic(ErrorCode.WRN_UnreferencedField, "p").WithArguments("C.p"));
}
[Fact]
public void SemanticModelPointerArrayForeachInfo()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
foreach(int* element in new int*[3])
{
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var foreachSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single();
// Reports members of non-generic interfaces (pointers can't be type arguments).
var info = model.GetForEachStatementInfo(foreachSyntax);
Assert.Equal(default(ForEachStatementInfo), info);
}
[Fact, WorkItem(544336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544336")]
public void PointerTypeAsDelegateParamInAnonMethod()
{
// It is legal to use a delegate with pointer types in a "safe" context
// provided that you do not actually make a parameter of unsafe type!
string sourceCode = @"
unsafe delegate int D(int* p);
class C
{
static void Main()
{
D d = delegate { return 1;};
}
}
";
var tree = Parse(sourceCode);
var comp = CreateCompilation(tree, options: TestOptions.UnsafeReleaseDll);
var model = comp.GetSemanticModel(tree);
model.GetDiagnostics().Verify();
}
[Fact(Skip = "529402"), WorkItem(529402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529402")]
public void DotOperatorOnPointerTypes()
{
string text = @"
unsafe class Program
{
static void Main(string[] args)
{
int* i1 = null;
i1.ToString();
}
}
";
var comp = CreateCompilation(text, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (7,9): error CS0023: Operator '.' cannot be applied to operand of type 'int*'
// i1.ToString();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "i1.ToString").WithArguments(".", "int*"));
}
[Fact, WorkItem(545028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545028")]
public void PointerToEnumInGeneric()
{
string text = @"
class C<T>
{
enum E { }
unsafe E* ptr;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (5,15): warning CS0169: The field 'C<T>.ptr' is never used
// unsafe E* ptr;
Diagnostic(ErrorCode.WRN_UnreferencedField, "ptr").WithArguments("C<T>.ptr"));
}
[Fact]
public void InvalidAsConversions()
{
string text = @"
using System;
public class Test
{
unsafe void M<T>(T t)
{
int* p = null;
Console.WriteLine(t as int*); // CS0244
Console.WriteLine(p as T); // Dev10 reports CS0244 here as well, but CS0413 seems reasonable
Console.WriteLine(null as int*); // CS0244
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,27): error CS0244: Neither 'is' nor 'as' is valid on pointer types
// Console.WriteLine(t as int*); // pointer
Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "t as int*"),
// (10,27): error CS0413: The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint
// Console.WriteLine(p as T); // pointer
Diagnostic(ErrorCode.ERR_AsWithTypeVar, "p as T").WithArguments("T"),
// (11,27): error CS0244: Neither 'is' nor 'as' is valid on pointer types
// Console.WriteLine(null as int*); // pointer
Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "null as int*"));
}
[Fact]
public void UnsafeConstructorInitializer()
{
string template = @"
{0} class A
{{
{1} public A(params int*[] x) {{ }}
}}
{0} class B : A
{{
{1} B(int x) {{ }}
{1} B(double x) : base() {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public A(params int*[] x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// B(int x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "B"),
// (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// B(double x) : base() { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "base"));
}
[WorkItem(545985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545985")]
[Fact]
public void UnboxPointer()
{
var text = @"
class C
{
unsafe void Goo(object obj)
{
var x = (int*)obj;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0030: Cannot convert type 'object' to 'int*'
// var x = (int*)obj;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)obj").WithArguments("object", "int*"));
}
[Fact]
public void FixedBuffersNoDefiniteAssignmentCheck()
{
var text = @"
unsafe struct struct_ForTestingDefiniteAssignmentChecking
{
//Definite Assignment Checking
public fixed int FixedbuffInt[1024];
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void FixedBuffersNoErrorsOnValidTypes()
{
var text = @"
unsafe struct struct_ForTestingDefiniteAssignmentChecking
{
public fixed bool _Type1[10];
public fixed byte _Type12[10];
public fixed int _Type2[10];
public fixed short _Type3[10];
public fixed long _Type4[10];
public fixed char _Type5[10];
public fixed sbyte _Type6[10];
public fixed ushort _Type7[10];
public fixed uint _Type8[10];
public fixed ulong _Type9[10];
public fixed float _Type10[10];
public fixed double _Type11[10];
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact()]
[WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")]
public void FixedBuffersUsageScenarioInRange()
{
var text = @"
using System;
unsafe struct s
{
public fixed bool _buffer[5]; // This is a fixed buffer.
}
class Program
{
static s _fixedBufferExample = new s();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[1] = false;
buffer[2] = true;
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[1]);
Console.Write(buffer[2]);
}
}
}
";
var compilation = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compilation.VerifyIL("Program.Store", @"
{
// Code size 34 (0x22)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: stind.i1
IL_0015: dup
IL_0016: ldc.i4.1
IL_0017: add
IL_0018: ldc.i4.0
IL_0019: stind.i1
IL_001a: ldc.i4.2
IL_001b: add
IL_001c: ldc.i4.1
IL_001d: stind.i1
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.0
IL_0021: ret
}
");
compilation.VerifyIL("Program.Load", @"
{
// Code size 46 (0x2e)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldind.u1
IL_0014: call ""void System.Console.Write(bool)""
IL_0019: dup
IL_001a: ldc.i4.1
IL_001b: add
IL_001c: ldind.u1
IL_001d: call ""void System.Console.Write(bool)""
IL_0022: ldc.i4.2
IL_0023: add
IL_0024: ldind.u1
IL_0025: call ""void System.Console.Write(bool)""
IL_002a: ldc.i4.0
IL_002b: conv.u
IL_002c: stloc.0
IL_002d: ret
}
");
}
[Fact()]
[WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")]
public void FixedBuffersUsagescenarioOutOfRange()
{
// This should work as no range checking for unsafe code.
//however the fact that we are writing bad unsafe code has potential for encountering problems
var text = @"
using System;
unsafe struct s
{
public fixed bool _buffer[5]; // This is a fixed buffer.
}
class Program
{
static s _fixedBufferExample = new s();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[8] = false;
buffer[10] = true;
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[8]);
Console.Write(buffer[10]);
}
}
}
";
//IL Baseline rather than execute because I'm intentionally writing outside of bounds of buffer
// This will compile without warning but runtime behavior is unpredictable.
var compilation = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compilation.VerifyIL("Program.Load", @"
{
// Code size 47 (0x2f)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldind.u1
IL_0014: call ""void System.Console.Write(bool)""
IL_0019: dup
IL_001a: ldc.i4.8
IL_001b: add
IL_001c: ldind.u1
IL_001d: call ""void System.Console.Write(bool)""
IL_0022: ldc.i4.s 10
IL_0024: add
IL_0025: ldind.u1
IL_0026: call ""void System.Console.Write(bool)""
IL_002b: ldc.i4.0
IL_002c: conv.u
IL_002d: stloc.0
IL_002e: ret
}");
compilation.VerifyIL("Program.Store", @"
{
// Code size 35 (0x23)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: stind.i1
IL_0015: dup
IL_0016: ldc.i4.8
IL_0017: add
IL_0018: ldc.i4.0
IL_0019: stind.i1
IL_001a: ldc.i4.s 10
IL_001c: add
IL_001d: ldc.i4.1
IL_001e: stind.i1
IL_001f: ldc.i4.0
IL_0020: conv.u
IL_0021: stloc.0
IL_0022: ret
}");
}
[Fact]
public void FixedBufferUsageWith_this()
{
var text = @"
using System;
unsafe struct s
{
private fixed ushort _e_res[4];
void Error_UsingFixedBuffersWithThis()
{
fixed (ushort* abc = this._e_res)
{
abc[2] = 1;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
}
[Fact]
[WorkItem(547074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547074")]
public void FixedBufferWithNoSize()
{
var text = @"
unsafe struct S
{
fixed[
}
";
var s = CreateCompilation(text).GlobalNamespace.GetMember<TypeSymbol>("S");
foreach (var member in s.GetMembers())
{
var field = member as FieldSymbol;
if (field != null)
{
Assert.Equal(0, field.FixedSize);
Assert.True(field.Type.IsPointerType());
Assert.True(field.HasPointerType);
}
}
}
[Fact()]
[WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")]
public void FixedBufferUsageDifferentAssemblies()
{
// Ensure fixed buffers work as expected when fixed buffer is created in different assembly to where it is consumed.
var s1 =
@"using System;
namespace ClassLibrary1
{
public unsafe struct FixedBufferExampleForSizes
{
public fixed bool _buffer[5]; // This is a fixed buffer.
}
}";
var s2 =
@"using System; using ClassLibrary1;
namespace ConsoleApplication30
{
class Program
{
static FixedBufferExampleForSizes _fixedBufferExample = new FixedBufferExampleForSizes();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[10] = false;
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[10]);
}
}
}
}";
var comp1 = CompileAndVerify(s1, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).Compilation;
var comp2 = CompileAndVerify(s2,
options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails,
references: new MetadataReference[] { MetadataReference.CreateFromImage(comp1.EmitToArray()) },
expectedOutput: "TrueFalse").Compilation;
var s3 =
@"using System; using ClassLibrary1;
namespace ConsoleApplication30
{
class Program
{
static FixedBufferExampleForSizes _fixedBufferExample = new FixedBufferExampleForSizes();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[10] = false;
buffer[1024] = true; //Intentionally outside range
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[10]);
Console.Write(buffer[1024]);
}
}
}
}";
// Only compile this as its intentionally writing outside of fixed buffer boundaries and
// this doesn't warn but causes flakiness when executed.
var comp3 = CompileAndVerify(s3,
options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails,
references: new MetadataReference[] { MetadataReference.CreateFromImage(comp1.EmitToArray()) }).Compilation;
}
[Fact]
public void FixedBufferUsageSizeCheckChar()
{
//Determine the Correct size based upon expansion for different no of elements
var text = @"using System;
unsafe struct FixedBufferExampleForSizes1
{
public fixed char _buffer[1]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes2
{
public fixed char _buffer[2]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes3
{
public fixed char _buffer[3]; // This is a fixed buffer.
}
class Program
{
// Reference to struct containing a fixed buffer
static FixedBufferExampleForSizes1 _fixedBufferExample1 = new FixedBufferExampleForSizes1();
static FixedBufferExampleForSizes2 _fixedBufferExample2 = new FixedBufferExampleForSizes2();
static FixedBufferExampleForSizes3 _fixedBufferExample3 = new FixedBufferExampleForSizes3();
static unsafe void Main()
{
int x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample1);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample2);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample3);
Console.Write(x.ToString());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"246");
}
[Fact]
public void FixedBufferUsageSizeCheckInt()
{
//Determine the Correct size based upon expansion for different no of elements
var text = @"using System;
unsafe struct FixedBufferExampleForSizes1
{
public fixed int _buffer[1]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes2
{
public fixed int _buffer[2]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes3
{
public fixed int _buffer[3]; // This is a fixed buffer.
}
class Program
{
// Reference to struct containing a fixed buffer
static FixedBufferExampleForSizes1 _fixedBufferExample1 = new FixedBufferExampleForSizes1();
static FixedBufferExampleForSizes2 _fixedBufferExample2 = new FixedBufferExampleForSizes2();
static FixedBufferExampleForSizes3 _fixedBufferExample3 = new FixedBufferExampleForSizes3();
static unsafe void Main()
{
int x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample1);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample2);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample3);
Console.Write(x.ToString());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"4812");
}
[Fact]
public void CannotTakeAddressOfRefReadOnlyParameter()
{
CreateCompilation(@"
public class Test
{
unsafe void M(in int p)
{
int* pointer = &p;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,24): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// int* pointer = &p;
Diagnostic(ErrorCode.ERR_FixedNeeded, "&p").WithLocation(6, 24)
);
}
#endregion
[Fact]
public void AddressOfFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
fixed (int* a = &s.Buf) {}
fixed (int* b = &s_f.Buf) {}
int* c = &s.Buf;
int* d = &s_f.Buf;
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (12,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* a = &s.Buf) {}
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&s.Buf").WithLocation(12, 25),
// (13,26): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// fixed (int* b = &s_f.Buf) {}
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(13, 26),
// (14,18): error CS0266: Cannot implicitly convert type 'int**' to 'int*'. An explicit conversion exists (are you missing a cast?)
// int* c = &s.Buf;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "&s.Buf").WithArguments("int**", "int*").WithLocation(14, 18),
// (15,19): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// int* d = &s_f.Buf;
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(15, 19));
}
[Fact]
public void FixedFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
fixed (int* a = s.Buf) {}
fixed (int* b = s_f.Buf) {}
int* c = s.Buf;
int* d = s_f.Buf;
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (12,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* a = s.Buf) {}
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "s.Buf").WithLocation(12, 25),
// (15,18): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// int* d = s_f.Buf;
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(15, 18));
}
[Fact]
public void NoPointerDerefMoveableFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
int x = *s.Buf;
int y = *s_f.Buf;
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (13,18): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// int y = *s_f.Buf;
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(13, 18));
}
[Fact]
public void AddressOfElementAccessFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
fixed (int* a = &s.Buf[0]) { }
fixed (int* b = &s_f.Buf[0]) { }
int* c = &s.Buf[0];
int* d = &s_f.Buf[0];
int* e = &(s.Buf[0]);
int* f = &(s_f.Buf[0]);
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (12,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* a = &s.Buf[0]) { }
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&s.Buf[0]").WithLocation(12, 25),
// (15,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// int* d = &s_f.Buf[0];
Diagnostic(ErrorCode.ERR_FixedNeeded, "&s_f.Buf[0]").WithLocation(15, 18),
// (17,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// int* f = &(s_f.Buf[0]);
Diagnostic(ErrorCode.ERR_FixedNeeded, "&(s_f.Buf[0])").WithLocation(17, 18));
}
[Fact, WorkItem(34693, "https://github.com/dotnet/roslyn/issues/34693")]
public void Repro_34693()
{
var csharp = @"
namespace Interop
{
public unsafe struct PROPVARIANT
{
public CAPROPVARIANT ca;
}
public unsafe struct CAPROPVARIANT
{
public uint cElems;
public PROPVARIANT* pElems;
}
}";
var comp = CreateCompilation(csharp, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
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;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Tests related to binding (but not lowering) lock statements.
/// </summary>
public class UnsafeTests : CompilingTestBase
{
private static string GetEscapedNewLine()
{
if (Environment.NewLine == "\n")
{
return @"\n";
}
else if (Environment.NewLine == "\r\n")
{
return @"\r\n";
}
else
{
throw new Exception("Unrecognized new line");
}
}
#region Unsafe regions
[Fact]
public void FixedSizeBuffer()
{
var text1 = @"
using System;
using System.Runtime.InteropServices;
public static class R
{
public unsafe struct S
{
public fixed byte Buffer[16];
}
}";
var comp1 = CreateEmptyCompilation(text1, assemblyName: "assembly1", references: new[] { MscorlibRef_v20 },
options: TestOptions.UnsafeDebugDll);
var ref1 = comp1.EmitToImageReference();
var text2 = @"
using System;
class C
{
unsafe void M(byte* p)
{
R.S* p2 = (R.S*)p;
IntPtr p3 = M2((IntPtr)p2[0].Buffer);
}
unsafe IntPtr M2(IntPtr p) => p;
}";
var comp2 = CreateCompilationWithMscorlib45(text2,
references: new[] { ref1 },
options: TestOptions.UnsafeDebugDll);
comp2.VerifyDiagnostics(
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1),
// warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy
Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1));
}
[Fact]
public void FixedSizeBuffer_GenericStruct_01()
{
var code = @"
unsafe struct MyStruct<T>
{
public fixed char buf[16];
public static void M()
{
var ms = new MyStruct<int>();
var ptr = &ms;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void FixedSizeBuffer_GenericStruct_02()
{
var code = @"
unsafe struct MyStruct<T>
{
public fixed T buf[16];
public static void M()
{
var ms = new MyStruct<int>();
var ptr = &ms;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,18): 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
// public fixed T buf[16];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "T").WithLocation(4, 18)
);
}
[Fact]
public void FixedSizeBuffer_GenericStruct_03()
{
var code = @"
unsafe struct MyStruct<T> where T : unmanaged
{
public fixed T buf[16];
public static void M()
{
var ms = new MyStruct<int>();
var ptr = &ms;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,18): 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
// public fixed T buf[16];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "T").WithLocation(4, 18)
);
}
[Fact]
public void FixedSizeBuffer_GenericStruct_04()
{
var code = @"
public unsafe struct MyStruct<T>
{
public T field;
}
unsafe struct OuterStruct
{
public fixed MyStruct<int> buf[16];
public static void M()
{
var os = new OuterStruct();
var ptr = &os;
}
}
";
CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,18): 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
// public fixed MyStruct<int> buf[16];
Diagnostic(ErrorCode.ERR_IllegalFixedType, "MyStruct<int>").WithLocation(9, 18)
);
}
[Fact]
public void CompilationNotUnsafe1()
{
var text = @"
unsafe class C
{
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics(
// (2,14): error CS0227: Unsafe code may only appear if compiling with /unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "C"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void CompilationNotUnsafe2()
{
var text = @"
class C
{
unsafe void Goo()
{
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics(
// (4,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Goo"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void CompilationNotUnsafe3()
{
var text = @"
class C
{
void Goo()
{
/*<bind>*/unsafe
{
_ = 0;
}/*</bind>*/
}
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: '_ = 0')
Left:
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(text, expectedOperationTree,
compilationOptions: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false),
expectedDiagnostics: new DiagnosticDescription[] {
// file.cs(6,19): error CS0227: Unsafe code may only appear if compiling with /unsafe
// /*<bind>*/unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(6, 19)
});
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void IteratorUnsafe1()
{
var text = @"
unsafe class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void IteratorUnsafe2()
{
var text = @"
class C
{
unsafe System.Collections.Generic.IEnumerator<int> Goo()
{
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,56): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Goo"));
}
[Fact]
public void IteratorUnsafe3()
{
var text = @"
class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
unsafe { }
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"));
}
[Fact]
public void IteratorUnsafe4()
{
var text = @"
unsafe class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
unsafe { }
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"));
}
[WorkItem(546657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546657")]
[Fact]
public void IteratorUnsafe5()
{
var text = @"
unsafe class C
{
System.Collections.Generic.IEnumerator<int> Goo()
{
System.Action a = () => { unsafe { } };
yield return 1;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"));
}
[Fact]
public void UnsafeModifier()
{
var text = @"
unsafe class C
{
unsafe C() { }
unsafe ~C() { }
unsafe static void Static() { }
unsafe void Instance() { }
unsafe struct Inner { }
unsafe int field = 1;
unsafe event System.Action Event;
unsafe int Property { get; set; }
unsafe int this[int x] { get { return field; } set { } }
unsafe public static C operator +(C c1, C c2) { return c1; }
unsafe public static implicit operator int(C c) { return 0; }
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,32): warning CS0067: The event 'C.Event' is never used
// unsafe event System.Action Event;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("C.Event"));
}
[Fact]
public void TypeIsUnsafe()
{
var text = @"
unsafe class C<T>
{
int* f0;
int** f1;
int*[] f2;
int*[][] f3;
C<int*> f4;
C<int**> f5;
C<int*[]> f6;
C<int*[][]> f7;
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
compilation.VerifyDiagnostics(
// (8,13): error CS0306: The type 'int*' may not be used as a type argument
// C<int*> f4;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "f4").WithArguments("int*").WithLocation(8, 13),
// (9,14): error CS0306: The type 'int**' may not be used as a type argument
// C<int**> f5;
Diagnostic(ErrorCode.ERR_BadTypeArgument, "f5").WithArguments("int**").WithLocation(9, 14),
// (4,10): warning CS0169: The field 'C<T>.f0' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f0").WithArguments("C<T>.f0"),
// (5,11): warning CS0169: The field 'C<T>.f1' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f1").WithArguments("C<T>.f1"),
// (6,12): warning CS0169: The field 'C<T>.f2' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f2").WithArguments("C<T>.f2"),
// (7,14): warning CS0169: The field 'C<T>.f3' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f3").WithArguments("C<T>.f3"),
// (8,13): warning CS0169: The field 'C<T>.f4' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f4").WithArguments("C<T>.f4"),
// (9,14): warning CS0169: The field 'C<T>.f5' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f5").WithArguments("C<T>.f5"),
// (10,15): warning CS0169: The field 'C<T>.f6' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f6").WithArguments("C<T>.f6"),
// (11,17): warning CS0169: The field 'C<T>.f7' is never used
Diagnostic(ErrorCode.WRN_UnreferencedField, "f7").WithArguments("C<T>.f7"));
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var fieldTypes = Enumerable.Range(0, 8).Select(i => type.GetMember<FieldSymbol>("f" + i).TypeWithAnnotations).ToArray();
Assert.True(fieldTypes[0].Type.IsUnsafe());
Assert.True(fieldTypes[1].Type.IsUnsafe());
Assert.True(fieldTypes[2].Type.IsUnsafe());
Assert.True(fieldTypes[3].Type.IsUnsafe());
Assert.False(fieldTypes[4].Type.IsUnsafe());
Assert.False(fieldTypes[5].Type.IsUnsafe());
Assert.False(fieldTypes[6].Type.IsUnsafe());
Assert.False(fieldTypes[7].Type.IsUnsafe());
}
[Fact]
public void UnsafeFieldTypes()
{
var template = @"
{0} class C
{{
public {1} int* f = null, g = null;
}}
";
CompareUnsafeDiagnostics(template,
// (4,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public int* f = null, g = null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
);
}
[Fact]
public void UnsafeLocalTypes()
{
var template = @"
{0} class C
{{
void M()
{{
{1}
{{
int* f = null, g = null;
}}
}}
}}
";
CompareUnsafeDiagnostics(template,
// (6,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeMethodSignatures()
{
var template = @"
{0} interface I
{{
{1} int* M(long* p, byte* q);
}}
{0} class C
{{
{1} int* M(long* p, byte* q) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void DelegateSignatures()
{
var template = @"
{0} class C
{{
{1} delegate int* M(long* p, byte* q);
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,31): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (4,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeConstructorSignatures()
{
var template = @"
{0} class C
{{
{1} C(long* p, byte* q) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"));
}
[Fact]
public void UnsafeOperatorSignatures()
{
var template = @"
{0} class C
{{
public static {1} C operator +(C c, int* p) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeConversionSignatures()
{
var template = @"
{0} class C
{{
public static {1} explicit operator C(int* p) {{ throw null; }}
public static {1} explicit operator byte*(C c) {{ throw null; }}
public static {1} implicit operator C(short* p) {{ throw null; }}
public static {1} implicit operator long*(C c) {{ throw null; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,40): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (6,40): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "short*"),
// (7,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"));
}
[Fact]
public void UnsafePropertySignatures()
{
var template = @"
{0} interface I
{{
{1} int* P {{ get; set; }}
}}
{0} class C
{{
{1} int* P {{ get; set; }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeIndexerSignatures()
{
var template = @"
{0} interface I
{{
{1} int* this[long* p, byte* q] {{ get; set; }}
}}
{0} class C
{{
{1} int* this[long* p, byte* q] {{ get {{ throw null; }} set {{ throw null; }} }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (4,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"));
}
[Fact]
public void UnsafeEventSignatures()
{
var template = @"
{0} interface I
{{
{1} event int* E;
}}
{0} class C
{{
{1} event int* E1;
{1} event int* E2 {{ add {{ }} remove {{ }} }}
}}
";
DiagnosticDescription[] expected =
{
// (4,17): error CS0066: 'I.E': event must be of a delegate type
Diagnostic(ErrorCode.ERR_EventNotDelegate, "E").WithArguments("I.E"),
// (9,17): error CS0066: 'C.E1': event must be of a delegate type
Diagnostic(ErrorCode.ERR_EventNotDelegate, "E1").WithArguments("C.E1"),
// (10,17): error CS0066: 'C.E2': event must be of a delegate type
Diagnostic(ErrorCode.ERR_EventNotDelegate, "E2").WithArguments("C.E2"),
// (9,17): warning CS0067: The event 'C.E1' is never used
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1")
};
CompareUnsafeDiagnostics(template, expected, expected);
}
[Fact]
public void UnsafeTypeArguments()
{
var template = @"
{0} interface I<T>
{{
{1} void Test(I<int*> i);
}}
{0} class C<T>
{{
{1} void Test(C<int*> c) {{ }}
}}
";
DiagnosticDescription[] expected =
{
// (4,24): error CS0306: The type 'int*' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "i").WithArguments("int*"),
// (9,24): error CS0306: The type 'int*' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "c").WithArguments("int*")
};
CompareUnsafeDiagnostics(template, expected, expected);
}
[Fact]
public void UnsafeExpressions1()
{
var template = @"
{0} class C
{{
void Test()
{{
{1}
{{
Unsafe(); //CS0214
}}
{1}
{{
var x = Unsafe(); //CS0214
}}
{1}
{{
var x = Unsafe(); //CS0214
var y = Unsafe(); //CS0214 suppressed
}}
{1}
{{
Unsafe(null); //CS0214
}}
}}
{1} int* Unsafe() {{ return null; }} //CS0214
{1} void Unsafe(int* p) {{ }} //CS0214
}}
";
CompareUnsafeDiagnostics(template,
// (28,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* Unsafe() { return null; } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (29,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// void Unsafe(int* p) { } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (13,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x = Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (18,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var x = Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (19,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// var y = Unsafe(); //CS0214 suppressed
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (24,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (24,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe(null)")
);
}
[Fact]
public void UnsafeExpressions2()
{
var template = @"
{0} class C
{{
{1} int* Field = Unsafe(); //CS0214 * 2
{1} C()
{{
Unsafe(); //CS0214
}}
{1} ~C()
{{
Unsafe(); //CS0214
}}
{1} void Test()
{{
Unsafe(); //CS0214
}}
{1} event System.Action E
{{
add {{ Unsafe(); }} //CS0214
remove {{ Unsafe(); }} //CS0214
}}
{1} int P
{{
set {{ Unsafe(); }} //CS0214
}}
{1} int this[int x]
{{
set {{ Unsafe(); }} //CS0214
}}
{1} public static implicit operator int(C c)
{{
Unsafe(); //CS0214
return 0;
}}
{1} public static C operator +(C c)
{{
Unsafe(); //CS0214
return c;
}}
{1} static int* Unsafe() {{ return null; }} //CS0214
}}
";
CompareUnsafeDiagnostics(template,
// (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* Field = Unsafe(); //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* Field = Unsafe(); //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (8,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (13,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (18,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (23,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// add { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (24,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// remove { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (29,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// set { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (34,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// set { Unsafe(); } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (39,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (45,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (49,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static int* Unsafe() { return null; } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[Fact]
public void UnsafeExpressions3()
{
var template = @"
{0} class C
{{
{1} void Test(int* p = Unsafe()) //CS0214 * 2
{{
System.Action a1 = () => Unsafe(); //CS0214
System.Action a2 = () =>
{{
Unsafe(); //CS0214
}};
}}
{1} static int* Unsafe() {{ return null; }} //CS0214
}}
";
DiagnosticDescription[] expectedWithoutUnsafe =
{
// (4,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (4,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Unsafe()").WithArguments("p"),
// (6,34): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// System.Action a1 = () => Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (10,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Unsafe(); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"),
// (14,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static int* Unsafe() { return null; } //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
};
DiagnosticDescription[] expectedWithUnsafe =
{
// (4,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test(int* p = Unsafe()) //CS0214 * 2
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Unsafe()").WithArguments("p")
};
CompareUnsafeDiagnostics(template, expectedWithoutUnsafe, expectedWithUnsafe);
}
[Fact]
public void UnsafeIteratorSignatures()
{
var template = @"
{0} class C
{{
{1} System.Collections.Generic.IEnumerable<int> Iterator(int* p)
{{
yield return 1;
}}
}}
";
var withoutUnsafe = string.Format(template, "", "");
CreateCompilation(withoutUnsafe, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// CONSIDER: We should probably suppress CS0214 (like Dev10 does) because it's
// confusing, but we don't have a good way to do so, because we don't know that
// the method is an iterator until we bind the body and we certainly don't want
// to do that just to figure out the types of the parameters.
// (4,59): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"));
var withUnsafeOnType = string.Format(template, "unsafe", "");
CreateCompilation(withUnsafeOnType, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"));
var withUnsafeOnMembers = string.Format(template, "", "unsafe");
CreateCompilation(withUnsafeOnMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"),
// (4,56): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Iterator")); //this is for putting "unsafe" on an iterator, not for the parameter type
var withUnsafeOnTypeAndMembers = string.Format(template, "unsafe", "unsafe");
CreateCompilation(withUnsafeOnTypeAndMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"),
// (4,56): error CS1629: Unsafe code may not appear in iterators
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Iterator")); //this is for putting "unsafe" on an iterator, not for the parameter type
}
[Fact]
public void UnsafeInAttribute1()
{
var text = @"
unsafe class Attr : System.Attribute
{
[Attr(null)] // Dev10: doesn't matter that the type and member are both 'unsafe'
public unsafe Attr(int* i)
{
}
}
";
// CONSIDER: Dev10 reports CS0214 (unsafe) and CS0182 (not a constant), but this makes
// just as much sense.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,6): error CS0181: Attribute constructor parameter 'i' has type 'int*', which is not a valid attribute parameter type
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("i", "int*"));
}
[Fact]
public void UnsafeInAttribute2()
{
var text = @"
unsafe class Attr : System.Attribute
{
[Attr(Unsafe() == null)] // Not a constant
public unsafe Attr(bool b)
{
}
static int* Unsafe()
{
return null;
}
}
";
// CONSIDER: Dev10 reports both CS0214 (unsafe) and CS0182 (not a constant), but this makes
// just as much sense.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Unsafe() == null"));
}
[Fact]
public void TypeofNeverUnsafe()
{
var text = @"
class C<T>
{
void Test()
{
System.Type t;
t = typeof(int*);
t = typeof(int**);
t = typeof(int*[]);
t = typeof(int*[][]);
t = typeof(C<int*>); // CS0306
t = typeof(C<int**>); // CS0306
t = typeof(C<int*[]>);
t = typeof(C<int*[][]>);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (13,22): error CS0306: The type 'int*' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*"),
// (14,22): error CS0306: The type 'int**' may not be used as a type argument
Diagnostic(ErrorCode.ERR_BadTypeArgument, "int**").WithArguments("int**"));
}
[Fact]
public void UnsafeOnEnum()
{
var text = @"
unsafe enum E
{
A
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (2,13): error CS0106: The modifier 'unsafe' is not valid for this item
Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("unsafe"));
}
[WorkItem(543834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543834")]
[Fact]
public void UnsafeOnDelegates()
{
var text = @"
public unsafe delegate void TestDelegate();
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics(
// (2,29): error CS0227: Unsafe code may only appear if compiling with /unsafe
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "TestDelegate"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[WorkItem(543835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543835")]
[Fact]
public void UnsafeOnConstField()
{
var text = @"
public class Main
{
unsafe public const int number = 0;
}
";
CreateCompilation(text).VerifyDiagnostics(
// (4,29): error CS0106: The modifier 'unsafe' is not valid for this item
Diagnostic(ErrorCode.ERR_BadMemberFlag, "number").WithArguments("unsafe"));
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,29): error CS0106: The modifier 'unsafe' is not valid for this item
Diagnostic(ErrorCode.ERR_BadMemberFlag, "number").WithArguments("unsafe"));
}
[Fact]
public void UnsafeOnExplicitInterfaceImplementation()
{
var text = @"
interface I
{
int P { get; set; }
void M();
event System.Action E;
}
class C : I
{
unsafe int I.P { get; set; }
unsafe void I.M() { }
unsafe event System.Action I.E { add { } remove { } }
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[WorkItem(544417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544417")]
[Fact]
public void UnsafeCallParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
{{ Goo(); }}
{{ Goo(null); }}
{{ Goo((int*)1); }}
{{ Goo(new int*[2]); }}
}}
{1} static void Goo(params int*[] x) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (12,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(params int*[] x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (6,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo()"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)"),
// (8,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo((int*)1)"),
// (9,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"),
// (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(new int*[2])")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeCallOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
{{ Goo(); }}
{{ Goo(null); }}
{{ Goo((int*)1); }}
}}
{1} static void Goo(int* p = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (11,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(int* p = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (6,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo()"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)"),
// (8,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { Goo((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo((int*)1)")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeDelegateCallParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
D d = null;
{{ d(); }}
{{ d(null); }}
{{ d((int*)1); }}
{{ d(new int*[2]); }}
}}
{1} delegate void D(params int*[] x);
}}
";
CompareUnsafeDiagnostics(template,
// (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void D(params int*[] x);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d()"),
// (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(null)"),
// (9,14): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d((int*)1)"),
// (10,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"),
// (10,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(new int*[2])")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeDelegateCallOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
D d = null;
{{ d(); }}
{{ d(null); }}
{{ d((int*)1); }}
}}
{1} delegate void D(int* p = null);
}}
";
CompareUnsafeDiagnostics(template,
// (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void D(int* p = null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d()"),
// (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(null)"),
// (9,14): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d((int*)1)")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeObjectCreationParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c;
{{ c = new C(); }}
{{ c = new C(null); }}
{{ c = new C((int*)1); }}
{{ c = new C(new int*[2]); }}
}}
{1} C(params int*[] x) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (13,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// C(params int*[] x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C()"),
// (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(null)"),
// (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C((int*)1)"),
// (10,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"),
// (10,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(new int*[2]); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(new int*[2])")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeObjectCreationOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c;
{{ c = new C(); }}
{{ c = new C(null); }}
{{ c = new C((int*)1); }}
}}
{1} C(int* p = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (12,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// C(int* p = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C()"),
// (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C(null); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(null)"),
// (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { c = new C((int*)1); }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C((int*)1)")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeIndexerParamArrays()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c = new C();
{{ int x = c[1]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, null]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, (int*)1]; }}
{{ int x = c[1, new int*[2]]; }}
}}
{1} int this[int x, params int*[] a] {{ get {{ return 0; }} set {{ }} }}
}}
";
CompareUnsafeDiagnostics(template,
// (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int this[int x, params int*[] a] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"),
// (10,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, new int*[2]]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, new int*[2]]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeIndexerOptionalParameters()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
C c = new C();
{{ int x = c[1]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, null]; }} // NOTE: as in dev10, this does not produce an error (would for a call).
{{ int x = c[1, (int*)1]; }}
}}
{1} int this[int x, int* p = null] {{ get {{ return 0; }} set {{ }} }}
}}
";
CompareUnsafeDiagnostics(template,
// (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int this[int x, int* p = null] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { int x = c[1, (int*)1]; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1")
);
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeAttributeParamArrays()
{
var template = @"
[A]
{0} class A : System.Attribute
{{
{1} A(params int*[] a) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'a' has type 'int*[]', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "int*[]"),
// (5,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// A(params int*[] a) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
},
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'a' has type 'int*[]', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "int*[]")
});
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeAttributeOptionalParameters()
{
var template = @"
[A]
{0} class A : System.Attribute
{{
{1} A(int* p = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'p' has type 'int*', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("p", "int*"),
// (5,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// A(int* p = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")
},
new[]
{
// CONSIDER: this differs slightly from dev10, but is clearer.
// (2,2): error CS0181: Attribute constructor parameter 'p' has type 'int*', which is not a valid attribute parameter type
// [A]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("p", "int*")
});
}
[WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")]
[Fact]
public void UnsafeDelegateAssignment()
{
var template = @"
{0} class C
{{
{1} static void Main()
{{
D d;
{{ d = delegate {{ }}; }}
{{ d = null; }}
{{ d = Goo; }}
}}
{1} delegate void D(int* x = null);
{1} static void Goo(int* x = null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// { d = Goo; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo"),
// (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void D(int* x = null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (13,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(int* x = null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
private static void CompareUnsafeDiagnostics(string template, params DiagnosticDescription[] expectedWithoutUnsafe)
{
CompareUnsafeDiagnostics(template, expectedWithoutUnsafe, new DiagnosticDescription[0]);
}
private static void CompareUnsafeDiagnostics(string template, DiagnosticDescription[] expectedWithoutUnsafe, DiagnosticDescription[] expectedWithUnsafe)
{
// NOTE: ERR_UnsafeNeeded is not affected by the presence/absence of the /unsafe flag.
var withoutUnsafe = string.Format(template, "", "");
CreateCompilation(withoutUnsafe).VerifyDiagnostics(expectedWithoutUnsafe);
CreateCompilation(withoutUnsafe, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithoutUnsafe);
var withUnsafeOnType = string.Format(template, "unsafe", "");
CreateCompilation(withUnsafeOnType, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe);
var withUnsafeOnMembers = string.Format(template, "", "unsafe");
CreateCompilation(withUnsafeOnMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe);
var withUnsafeOnTypeAndMembers = string.Format(template, "unsafe", "unsafe");
CreateCompilation(withUnsafeOnTypeAndMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe);
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void MethodCallWithNullAsPointerArg()
{
var template = @"
{0} class Test
{{
{1} static void Goo(void* p) {{ }}
{1} static void Main()
{{
Goo(null);
}}
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// static void Goo(void* p) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"),
// (7,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Goo(null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (7,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Goo(null);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)")
);
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void MethodCallWithUnsafeArgument()
{
var template = @"
{0} class Test
{{
{1} int M(params int*[] p) {{ return 0; }}
{1} public static implicit operator int*(Test t) {{ return null; }}
{1} void M()
{{
{{
int x = M(null); //CS0214
}}
{{
int x = M(null, null); //CS0214
}}
{{
int x = M(this); //CS0214
}}
}}
}}
";
CompareUnsafeDiagnostics(template,
// (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public static implicit operator int*(Test t) { return null; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (4,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int M(params int*[] p) { return 0; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (10,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (10,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(null)"),
// (13,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null, null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null, null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (13,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(null, null); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(null, null)"),
// (16,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(this); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "this"),
// (16,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int x = M(this); //CS0214
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(this)")
);
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void IndexerAccessWithUnsafeArgument()
{
var template = @"
{0} class Test
{{
{1} int this[params int*[] p] {{ get {{ return 0; }} set {{ }} }}
{1} public static implicit operator int*(Test t) {{ return null; }}
{1} void M()
{{
{{
int x = this[null]; //CS0214 seems appropriate, but dev10 accepts
}}
{{
int x = this[null, null]; //CS0214 seems appropriate, but dev10 accepts
}}
{{
int x = this[this]; //CS0214 seems appropriate, but dev10 accepts
}}
}}
}}
";
CompareUnsafeDiagnostics(template,
// (4,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int this[int* p] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public static implicit operator int*(Test t) { return null; }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"));
}
[WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")]
[Fact]
public void ConstructorInitializerWithUnsafeArgument()
{
var template = @"
{0} class Base
{{
{1} public Base(int* p) {{ }}
}}
{0} class Derived : Base
{{
{1} public Derived() : base(null) {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public Base(int* p) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public Derived() : base(null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"),
// (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public Derived() : base(null) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "base")
);
}
[WorkItem(544286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544286")]
[Fact]
public void UnsafeLambdaParameterType()
{
var template = @"
{0} class Program
{{
{1} delegate void F(int* x);
{1} static void Main()
{{
F e = x => {{ }};
}}
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// delegate void F(int* x);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// F e = x => { };
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "x"));
}
#endregion Unsafe regions
#region Variables that need fixing
[Fact]
public void FixingVariables_Parameters()
{
var text = @"
class C
{
void M(int x, ref int y, out int z, params int[] p)
{
M(x, ref y, out z, p);
}
}
";
var expected = @"
Yes, Call 'M(x, ref y, out z, p)' requires fixing.
Yes, ThisReference 'M' requires fixing.
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
Yes, Parameter 'y' requires fixing.
Yes, Parameter 'z' requires fixing.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Locals()
{
var text = @"
class C
{
void M(params object[] p)
{
C c = null;
int x = 0;
M(c, x);
}
}
";
var expected = @"
Yes, TypeExpression 'C' requires fixing.
Yes, Conversion 'null' requires fixing.
Yes, Literal 'null' requires fixing.
Yes, TypeExpression 'int' requires fixing.
Yes, Literal '0' requires fixing.
Yes, Call 'M(c, x)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'x' requires fixing.
No, Local 'x' does not require fixing. It has an underlying symbol 'x'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields1()
{
var text = @"
class C
{
public S1 s;
public C c;
void M(params object[] p)
{
C c = new C();
S1 s = new S1();
M(this, this.s, this.s.s, this.s.c, this.c.s, this.c.c);
M(c, c.s, c.s.s, c.s.c, c.c.s, c.c.c);
M(s, s.s, s.s.i);
}
}
struct S1
{
public S2 s;
public C c;
}
struct S2
{
public int i;
}
";
var expected = @"
Yes, TypeExpression 'C' requires fixing.
Yes, ObjectCreationExpression 'new C()' requires fixing.
Yes, TypeExpression 'S1' requires fixing.
Yes, ObjectCreationExpression 'new S1()' requires fixing.
Yes, Call 'M(this, this.s, this.s.s, this.s.c, this.c.s, this.c.c)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'this' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.s' requires fixing.
Yes, FieldAccess 'this.s' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.s.s' requires fixing.
Yes, FieldAccess 'this.s.s' requires fixing.
Yes, FieldAccess 'this.s' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.s.c' requires fixing.
Yes, FieldAccess 'this.s.c' requires fixing.
Yes, FieldAccess 'this.s' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.c.s' requires fixing.
Yes, FieldAccess 'this.c.s' requires fixing.
Yes, FieldAccess 'this.c' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Conversion 'this.c.c' requires fixing.
Yes, FieldAccess 'this.c.c' requires fixing.
Yes, FieldAccess 'this.c' requires fixing.
Yes, ThisReference 'this' requires fixing.
Yes, Call 'M(c, c.s, c.s.s, c.s.c, c.c.s, c.c.c)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.s' requires fixing.
Yes, FieldAccess 'c.s' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.s.s' requires fixing.
Yes, FieldAccess 'c.s.s' requires fixing.
Yes, FieldAccess 'c.s' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.s.c' requires fixing.
Yes, FieldAccess 'c.s.c' requires fixing.
Yes, FieldAccess 'c.s' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.c.s' requires fixing.
Yes, FieldAccess 'c.c.s' requires fixing.
Yes, FieldAccess 'c.c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.c.c' requires fixing.
Yes, FieldAccess 'c.c.c' requires fixing.
Yes, FieldAccess 'c.c' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Call 'M(s, s.s, s.s.i)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 's' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
Yes, Conversion 's.s' requires fixing.
No, FieldAccess 's.s' does not require fixing. It has an underlying symbol 's'
No, Local 's' does not require fixing. It has an underlying symbol 's'
Yes, Conversion 's.s.i' requires fixing.
No, FieldAccess 's.s.i' does not require fixing. It has an underlying symbol 's'
No, FieldAccess 's.s' does not require fixing. It has an underlying symbol 's'
No, Local 's' does not require fixing. It has an underlying symbol 's'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields2()
{
var text = @"
class Base
{
public int i;
}
class Derived : Base
{
void M()
{
base.i = 0;
}
}
";
var expected = @"
Yes, AssignmentOperator 'base.i = 0' requires fixing.
Yes, FieldAccess 'base.i' requires fixing.
Yes, BaseReference 'base' requires fixing.
Yes, Literal '0' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields3()
{
var text = @"
struct S
{
static int i;
void M()
{
S.i = 0;
}
}
";
var expected = @"
Yes, AssignmentOperator 'S.i = 0' requires fixing.
Yes, FieldAccess 'S.i' requires fixing.
Yes, TypeExpression 'S' requires fixing.
Yes, Literal '0' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Fields4()
{
var text = @"
struct S
{
int i;
void M(params object[] p)
{
// rvalues always require fixing.
M(new S().i, default(S).i, MakeS().i, (new S[1])[0].i);
}
S MakeS()
{
return default(S);
}
}
";
var expected = @"
Yes, Call 'M(new S().i, default(S).i, MakeS().i, (new S[1])[0].i)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'new S().i' requires fixing.
Yes, FieldAccess 'new S().i' requires fixing.
Yes, ObjectCreationExpression 'new S()' requires fixing.
Yes, Conversion 'default(S).i' requires fixing.
Yes, FieldAccess 'default(S).i' requires fixing.
Yes, DefaultExpression 'default(S)' requires fixing.
Yes, Conversion 'MakeS().i' requires fixing.
Yes, FieldAccess 'MakeS().i' requires fixing.
Yes, Call 'MakeS()' requires fixing.
Yes, ThisReference 'MakeS' requires fixing.
Yes, Conversion '(new S[1])[0].i' requires fixing.
Yes, FieldAccess '(new S[1])[0].i' requires fixing.
Yes, ArrayAccess '(new S[1])[0]' requires fixing.
Yes, ArrayCreation 'new S[1]' requires fixing.
Yes, Literal '1' requires fixing.
Yes, Literal '0' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Events()
{
var text = @"
struct S
{
public event System.Action E;
public event System.Action F { add { } remove { } }
void M(params object[] p)
{
C c = new C();
S s = new S();
M(c.E, c.F); //note: note legal to pass F
M(s.E, s.F); //note: note legal to pass F
}
}
class C
{
public event System.Action E;
public event System.Action F { add { } remove { } }
}
";
var expected = @"
Yes, TypeExpression 'C' requires fixing.
Yes, ObjectCreationExpression 'new C()' requires fixing.
Yes, TypeExpression 'S' requires fixing.
Yes, ObjectCreationExpression 'new S()' requires fixing.
Yes, Call 'M(c.E, c.F)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 'c.E' requires fixing.
Yes, BadExpression 'c.E' requires fixing.
Yes, EventAccess 'c.E' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'c.F' requires fixing.
Yes, BadExpression 'c.F' requires fixing.
Yes, EventAccess 'c.F' requires fixing.
No, Local 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Call 'M(s.E, s.F)' requires fixing.
Yes, ThisReference 'M' requires fixing.
Yes, Conversion 's.E' requires fixing.
No, EventAccess 's.E' does not require fixing. It has an underlying symbol 's'
No, Local 's' does not require fixing. It has an underlying symbol 's'
Yes, Conversion 's.F' requires fixing.
Yes, BadExpression 's.F' requires fixing.
Yes, EventAccess 's.F' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
".Trim();
CheckIfVariablesNeedFixing(text, expected, expectError: true);
}
[Fact]
public void FixingVariables_Lambda1()
{
var text = @"
class C
{
void M(params object[] p)
{
int i = 0; // NOTE: does not require fixing even though it will be hoisted - lambdas handled separately.
i++;
System.Action a = () =>
{
int j = i;
j++;
};
}
}
";
var expected = string.Format(@"
Yes, TypeExpression 'int' requires fixing.
Yes, Literal '0' requires fixing.
Yes, IncrementOperator 'i++' requires fixing.
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
Yes, TypeExpression 'System.Action' requires fixing.
Yes, Conversion '() =>{0} {{{0} int j = i;{0} j++;{0} }}' requires fixing.
Yes, Lambda '() =>{0} {{{0} int j = i;{0} j++;{0} }}' requires fixing.
Yes, TypeExpression 'int' requires fixing.
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
Yes, IncrementOperator 'j++' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
", GetEscapedNewLine()).Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Lambda2()
{
var text = @"
class C
{
void M()
{
int i = 0; // NOTE: does not require fixing even though it will be hoisted - lambdas handled separately.
i++;
System.Func<int, System.Func<int, int>> a = p => q => p + q + i;
}
}
";
var expected = @"
Yes, TypeExpression 'int' requires fixing.
Yes, Literal '0' requires fixing.
Yes, IncrementOperator 'i++' requires fixing.
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
Yes, TypeExpression 'System.Func<int, System.Func<int, int>>' requires fixing.
Yes, Conversion 'p => q => p + q + i' requires fixing.
Yes, Lambda 'p => q => p + q + i' requires fixing.
Yes, Conversion 'q => p + q + i' requires fixing.
Yes, Lambda 'q => p + q + i' requires fixing.
Yes, BinaryOperator 'p + q + i' requires fixing.
Yes, BinaryOperator 'p + q' requires fixing.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
No, Parameter 'q' does not require fixing. It has an underlying symbol 'q'
No, Local 'i' does not require fixing. It has an underlying symbol 'i'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_Dereference()
{
var text = @"
struct S
{
int i;
unsafe void Test(S* p)
{
S s;
s = *p;
s = p[0];
int j;
j = (*p).i;
j = p[0].i;
j = p->i;
}
}
";
var expected = @"
Yes, TypeExpression 'S' requires fixing.
Yes, AssignmentOperator 's = *p' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
No, PointerIndirectionOperator '*p' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, AssignmentOperator 's = p[0]' requires fixing.
No, Local 's' does not require fixing. It has an underlying symbol 's'
No, PointerElementAccess 'p[0]' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, Literal '0' requires fixing.
Yes, TypeExpression 'int' requires fixing.
Yes, AssignmentOperator 'j = (*p).i' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
No, FieldAccess '(*p).i' does not require fixing. It has no underlying symbol.
No, PointerIndirectionOperator '*p' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, AssignmentOperator 'j = p[0].i' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
No, FieldAccess 'p[0].i' does not require fixing. It has no underlying symbol.
No, PointerElementAccess 'p[0]' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
Yes, Literal '0' requires fixing.
Yes, AssignmentOperator 'j = p->i' requires fixing.
No, Local 'j' does not require fixing. It has an underlying symbol 'j'
No, FieldAccess 'p->i' does not require fixing. It has no underlying symbol.
No, PointerIndirectionOperator 'p' does not require fixing. It has no underlying symbol.
No, Parameter 'p' does not require fixing. It has an underlying symbol 'p'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_StackAlloc()
{
var text = @"
struct S
{
unsafe void Test()
{
int* p = stackalloc int[1];
}
}
";
var expected = @"
Yes, TypeExpression 'int*' requires fixing.
No, ConvertedStackAllocExpression 'stackalloc int[1]' does not require fixing. It has no underlying symbol.
Yes, Literal '1' requires fixing.
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_TypeParameters1()
{
var text = @"
class C
{
public C c;
void M<T>(T t, C c) where T : C
{
M(t, t.c);
}
}
";
var expected = @"
Yes, Call 'M(t, t.c)' requires fixing.
Yes, ThisReference 'M' requires fixing.
No, Parameter 't' does not require fixing. It has an underlying symbol 't'
Yes, FieldAccess 't.c' requires fixing.
No, Parameter 't' does not require fixing. It has an underlying symbol 't'
".Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_TypeParameters2()
{
var text = @"
class D : C<S>
{
public override void M<U>(U u, int j)
{
M(u, u.i); // effective base type (System.ValueType) does not have a member 'i'
}
}
abstract class C<T>
{
public abstract void M<U>(U u, int i) where U : T;
}
struct S
{
public int i;
}
";
var expected = @"
Yes, Call 'M(u, u.i)' requires fixing.
Yes, ThisReference 'M' requires fixing.
No, Parameter 'u' does not require fixing. It has an underlying symbol 'u'
Yes, BadExpression 'u.i' requires fixing.
No, Parameter 'u' does not require fixing. It has an underlying symbol 'u'
".Trim();
CheckIfVariablesNeedFixing(text, expected, expectError: true);
}
[Fact]
public void FixingVariables_RangeVariables1()
{
var text = @"
using System.Linq;
class C
{
void M(int[] array)
{
var result =
from i in array
from j in array
select i + j;
}
}
";
var expected = string.Format(@"
Yes, TypeExpression 'var' requires fixing.
Yes, QueryClause 'from i in array {0} from j in array {0} select i + j' requires fixing.
Yes, QueryClause 'select i + j' requires fixing.
Yes, QueryClause 'from j in array' requires fixing.
Yes, Call 'from j in array' requires fixing.
Yes, Conversion 'from i in array' requires fixing.
Yes, QueryClause 'from i in array' requires fixing.
No, Parameter 'array' does not require fixing. It has an underlying symbol 'array'
Yes, QueryClause 'from j in array' requires fixing.
Yes, Conversion 'array' requires fixing.
Yes, Lambda 'array' requires fixing.
Yes, Conversion 'array' requires fixing.
No, Parameter 'array' does not require fixing. It has an underlying symbol 'array'
Yes, Conversion 'i + j' requires fixing.
Yes, Lambda 'i + j' requires fixing.
Yes, BinaryOperator 'i + j' requires fixing.
No, RangeVariable 'i' does not require fixing. It has an underlying symbol 'i'
No, Parameter 'i' does not require fixing. It has an underlying symbol 'i'
No, RangeVariable 'j' does not require fixing. It has an underlying symbol 'j'
No, Parameter 'j' does not require fixing. It has an underlying symbol 'j'
", GetEscapedNewLine()).Trim();
CheckIfVariablesNeedFixing(text, expected);
}
[Fact]
public void FixingVariables_RangeVariables2()
{
var text = @"
using System;
class Test
{
void M(C c)
{
var result = from x in c
where x > 0 //int
where x.Length < 2 //string
select char.IsLetter(x); //char
}
}
class C
{
public D Where(Func<int, bool> predicate)
{
return new D();
}
}
class D
{
public char[] Where(Func<string, bool> predicate)
{
return new char[10];
}
}
static class Extensions
{
public static object Select(this char[] array, Func<char, bool> func)
{
return null;
}
}
";
var expected = string.Format(@"
Yes, TypeExpression 'var' requires fixing.
Yes, QueryClause 'from x in c{0} where x > 0 //int{0} where x.Length < 2 //string{0} select char.IsLetter(x)' requires fixing.
Yes, QueryClause 'select char.IsLetter(x)' requires fixing.
Yes, Call 'select char.IsLetter(x)' requires fixing.
Yes, QueryClause 'where x.Length < 2' requires fixing.
Yes, Call 'where x.Length < 2' requires fixing.
Yes, QueryClause 'where x > 0' requires fixing.
Yes, Call 'where x > 0' requires fixing.
Yes, QueryClause 'from x in c' requires fixing.
No, Parameter 'c' does not require fixing. It has an underlying symbol 'c'
Yes, Conversion 'x > 0' requires fixing.
Yes, Lambda 'x > 0' requires fixing.
Yes, BinaryOperator 'x > 0' requires fixing.
No, RangeVariable 'x' does not require fixing. It has an underlying symbol 'x'
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
Yes, Literal '0' requires fixing.
Yes, Conversion 'x.Length < 2' requires fixing.
Yes, Lambda 'x.Length < 2' requires fixing.
Yes, BinaryOperator 'x.Length < 2' requires fixing.
Yes, PropertyAccess 'x.Length' requires fixing.
No, RangeVariable 'x' does not require fixing. It has an underlying symbol 'x'
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
Yes, Literal '2' requires fixing.
Yes, Conversion 'char.IsLetter(x)' requires fixing.
Yes, Lambda 'char.IsLetter(x)' requires fixing.
Yes, Call 'char.IsLetter(x)' requires fixing.
Yes, TypeExpression 'char' requires fixing.
No, RangeVariable 'x' does not require fixing. It has an underlying symbol 'x'
No, Parameter 'x' does not require fixing. It has an underlying symbol 'x'
", GetEscapedNewLine()).Trim();
CheckIfVariablesNeedFixing(text, expected);
}
private static void CheckIfVariablesNeedFixing(string text, string expected, bool expectError = false)
{
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll);
var compilationDiagnostics = compilation.GetDiagnostics();
if (expectError != compilationDiagnostics.Any(diag => diag.Severity == DiagnosticSeverity.Error))
{
compilationDiagnostics.Verify();
Assert.True(false);
}
var tree = compilation.SyntaxTrees.Single();
var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
var methodBody = methodDecl.Body;
var model = compilation.GetSemanticModel(tree);
var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(methodBody.SpanStart);
Assert.NotNull(binder);
Assert.Equal(SymbolKind.Method, binder.ContainingMemberOrLambda.Kind);
var unusedDiagnostics = DiagnosticBag.GetInstance();
var block = binder.BindEmbeddedBlock(methodBody, unusedDiagnostics);
unusedDiagnostics.Free();
var builder = ArrayBuilder<string>.GetInstance();
CheckFixingVariablesVisitor.Process(block, binder, builder);
var actual = string.Join(Environment.NewLine, builder);
Assert.Equal(expected, actual);
builder.Free();
}
private class CheckFixingVariablesVisitor : BoundTreeWalkerWithStackGuard
{
private readonly Binder _binder;
private readonly ArrayBuilder<string> _builder;
private CheckFixingVariablesVisitor(Binder binder, ArrayBuilder<string> builder)
{
_binder = binder;
_builder = builder;
}
public static void Process(BoundBlock block, Binder binder, ArrayBuilder<string> builder)
{
var visitor = new CheckFixingVariablesVisitor(binder, builder);
visitor.Visit(block);
}
public override BoundNode Visit(BoundNode node)
{
var expr = node as BoundExpression;
if (expr != null)
{
var text = node.Syntax.ToString();
if (!string.IsNullOrEmpty(text))
{
text = SymbolDisplay.FormatLiteral(text, quote: false);
if (_binder.IsMoveableVariable(expr, out Symbol accessedLocalOrParameterOpt))
{
_builder.Add($"Yes, {expr.Kind} '{text}' requires fixing.");
}
else
{
_builder.Add(string.Concat($"No, {expr.Kind} '{text}' does not require fixing.", accessedLocalOrParameterOpt is null
? " It has no underlying symbol."
: $" It has an underlying symbol '{accessedLocalOrParameterOpt.Name}'"));
}
}
}
return base.Visit(node);
}
protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()
{
return false;
}
}
#endregion Variables that need fixing
#region IsManagedType
[Fact]
public void IsManagedType_Array()
{
var text = @"
class C
{
int[] f1;
int[,] f2;
int[][] f3;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Pointer()
{
var text = @"
unsafe class C
{
int* f1;
int** f2;
void* f3;
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => !field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Dynamic()
{
var text = @"
class C
{
dynamic f1;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Error()
{
var text = @"
class C<T>
{
C f1;
C<int, int> f2;
Garbage f3;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_TypeParameter()
{
var text = @"
class C<T, U> where U : struct
{
T f1;
U f2;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_AnonymousType()
{
var text = @"
class C
{
void M()
{
var local1 = new { };
var local2 = new { F = 1 };
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.True(tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().
Select(syntax => model.GetTypeInfo(syntax).Type).All(type => type.GetSymbol().IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_Class()
{
var text = @"
class Outer
{
Outer f1;
Outer.Inner f2;
string f3;
class Inner { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_GenericClass()
{
var text = @"
class Outer<T>
{
Outer<T> f1;
Outer<T>.Inner f2;
Outer<int> f1;
Outer<string>.Inner f2;
class Inner { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedTypeNoUseSiteDiagnostics));
}
[Fact]
public void IsManagedType_ManagedSpecialTypes()
{
var text = @"
class C
{
object f1;
string f2;
System.Collections.IEnumerable f3;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
foreach (var field in type.GetMembers().OfType<FieldSymbol>())
{
Assert.True(field.Type.IsManagedTypeNoUseSiteDiagnostics, field.ToString());
}
}
[Fact]
public void IsManagedType_NonManagedSpecialTypes()
{
var text = @"
class C
{
bool f1;
char f2;
sbyte f3;
byte f4;
short f5;
ushort f6;
int f7;
uint f8;
long f9;
ulong f10;
decimal f11;
float f12;
double f13;
System.IntPtr f14;
System.UIntPtr f15;
int? f16;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => !field.Type.IsManagedTypeNoUseSiteDiagnostics));
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetField("f16").Type.ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_Void()
{
var text = @"
class C
{
void M() { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var method = type.GetMember<MethodSymbol>("M");
Assert.False(method.ReturnType.IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_Enum()
{
var text = @"
enum E { A }
class C
{
enum E { A }
}
class D<T>
{
enum E { A }
}
struct S
{
enum E { A }
}
struct R<T>
{
enum E { A }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("R").GetMember<NamedTypeSymbol>("E").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_EmptyStruct()
{
var text = @"
struct S { }
struct P<T> { }
class C
{
struct S { }
}
class D<T>
{
struct S { }
}
struct Q
{
struct S { }
}
struct R<T>
{
struct S { }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Unmanaged, globalNamespace.GetMember<NamedTypeSymbol>("S").ManagedKindNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("P").IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, globalNamespace.GetMember<NamedTypeSymbol>("P").ManagedKindNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("Q").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("R").GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_SubstitutedStruct()
{
var text = @"
class C<U>
{
S<U> f1;
S<int> f2;
S<U>.R f3;
S<int>.R f4;
S<U>.R2 f5;
S<int>.R2 f6;
}
struct S<T>
{
struct R { }
internal struct R2 { }
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.False(type.GetMember<FieldSymbol>("f1").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f1").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f2").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f2").Type.ManagedKindNoUseSiteDiagnostics);
// these are managed due to S`1.R being ErrorType due to protection level (CS0169)
Assert.True(type.GetMember<FieldSymbol>("f3").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Managed, type.GetMember<FieldSymbol>("f3").Type.ManagedKindNoUseSiteDiagnostics);
Assert.True(type.GetMember<FieldSymbol>("f4").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Managed, type.GetMember<FieldSymbol>("f4").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f5").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f5").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f6").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f6").Type.ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_GenericStruct()
{
var text = @"
class C<U>
{
S<object> f1;
S<int> f2;
}
struct S<T>
{
T field;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMember<FieldSymbol>("f1").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.Managed, type.GetMember<FieldSymbol>("f1").Type.ManagedKindNoUseSiteDiagnostics);
Assert.False(type.GetMember<FieldSymbol>("f2").Type.IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, type.GetMember<FieldSymbol>("f2").Type.ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_GenericStruct_ErrorTypeArg()
{
var text = @"
class C<U>
{
S<Widget> f1;
}
struct S<T>
{
T field;
}
";
var compilation = CreateCompilation(text);
var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.True(type.GetMember<FieldSymbol>("f1").Type.IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_NonEmptyStruct()
{
var text = @"
struct S1
{
int f;
}
struct S2
{
object f;
}
struct S3
{
S1 s;
}
struct S4
{
S2 s;
}
struct S5
{
S1 s1;
S2 s2;
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_StaticFieldStruct()
{
var text = @"
struct S1
{
static object o;
int f;
}
struct S2
{
static object o;
object f;
}
struct S3
{
static object o;
S1 s;
}
struct S4
{
static object o;
S2 s;
}
struct S5
{
static object o;
S1 s1;
S2 s2;
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_AutoPropertyStruct()
{
var text = @"
struct S1
{
int f { get; set; }
}
struct S2
{
object f { get; set; }
}
struct S3
{
S1 s { get; set; }
}
struct S4
{
S2 s { get; set; }
}
struct S5
{
S1 s1 { get; set; }
S2 s2 { get; set; }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_PropertyStruct()
{
var text = @"
struct S1
{
object o { get { return null; } set { } }
int f { get; set; }
}
struct S2
{
object o { get { return null; } set { } }
object f { get; set; }
}
struct S3
{
object o { get { return null; } set { } }
S1 s { get; set; }
}
struct S4
{
object o { get { return null; } set { } }
S2 s { get; set; }
}
struct S5
{
object o { get { return null; } set { } }
S1 s1 { get; set; }
S2 s2 { get; set; }
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_EventStruct()
{
var text = @"
struct S1
{
event System.Action E; // has field
}
struct S2
{
event System.Action E { add { } remove { } } // no field
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_ExpandingStruct()
{
var text = @"
struct X<T> { public T t; }
struct W<T> { X<W<W<T>>> x; }
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("X").IsManagedTypeNoUseSiteDiagnostics); // because of X.t
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("W").IsManagedTypeNoUseSiteDiagnostics);
Assert.Equal(ManagedKind.UnmanagedWithGenerics, globalNamespace.GetMember<NamedTypeSymbol>("W").ManagedKindNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_CyclicStruct()
{
var text = @"
struct S
{
S s;
}
struct R
{
object o;
S s;
}
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("R").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_CyclicStructChain()
{
var text = @"
struct Q { R r; }
struct R { A a; object o }
struct S { A a; }
//cycle
struct A { B b; }
struct B { C c; }
struct C { D d; }
struct D { A a; }
";
var compilation = CreateCompilation(text);
var globalNamespace = compilation.GlobalNamespace;
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("Q").IsManagedTypeNoUseSiteDiagnostics);
Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("R").IsManagedTypeNoUseSiteDiagnostics);
Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void IsManagedType_SpecialClrTypes()
{
var text = @"
class C { }
";
var compilation = CreateCompilation(text);
Assert.False(compilation.GetSpecialType(SpecialType.System_ArgIterator).IsManagedTypeNoUseSiteDiagnostics);
Assert.False(compilation.GetSpecialType(SpecialType.System_RuntimeArgumentHandle).IsManagedTypeNoUseSiteDiagnostics);
Assert.False(compilation.GetSpecialType(SpecialType.System_TypedReference).IsManagedTypeNoUseSiteDiagnostics);
}
[Fact]
public void ERR_ManagedAddr_ShallowRecursive()
{
var text = @"
public unsafe struct S1
{
public S1* s; //CS0208
public object o;
}
public unsafe struct S2
{
public S2* s; //fine
public int i;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S1')
// public S1* s; //CS0523
Diagnostic(ErrorCode.ERR_ManagedAddr, "s").WithArguments("S1"));
}
[Fact]
public void ERR_ManagedAddr_DeepRecursive()
{
var text = @"
public unsafe struct A
{
public B** bb; //CS0208
public object o;
public struct B
{
public C*[] cc; //CS0208
public struct C
{
public A*[,][] aa; //CS0208
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A')
// public A*[,][] aa; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "aa").WithArguments("A"),
// (9,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A.B.C')
// public C*[] cc; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "cc").WithArguments("A.B.C"),
// (4,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A.B')
// public B** bb; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "bb").WithArguments("A.B"));
}
[Fact]
public void ERR_ManagedAddr_Alias()
{
var text = @"
using Alias = S;
public unsafe struct S
{
public Alias* s; //CS0208
public object o;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// public Alias* s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "s").WithArguments("S"));
}
[Fact()]
public void ERR_ManagedAddr_Members()
{
var text = @"
public unsafe struct S
{
S* M() { return M(); }
void M(S* p) { }
S* P { get; set; }
S* this[int x] { get { return M(); } set { } }
int this[S* p] { get { return 0; } set { } }
public S* s; //CS0208
public object o;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* M() { return M(); }
Diagnostic(ErrorCode.ERR_ManagedAddr, "M").WithArguments("S"),
// (5,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// void M(S* p) { }
Diagnostic(ErrorCode.ERR_ManagedAddr, "p").WithArguments("S"),
// (7,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* P { get; set; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "P").WithArguments("S"),
// (9,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* this[int x] { get { return M(); } set { } }
Diagnostic(ErrorCode.ERR_ManagedAddr, "this").WithArguments("S"),
// (10,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// int this[S* p] { get { return 0; } set { } }
Diagnostic(ErrorCode.ERR_ManagedAddr, "p").WithArguments("S"),
// (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// public S* s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "s").WithArguments("S"));
}
[WorkItem(10195, "https://github.com/dotnet/roslyn/issues/10195")]
[Fact]
public void PointerToStructInPartialMethodSignature()
{
string text =
@"unsafe partial struct S
{
partial void M(S *p) { }
partial void M(S *p);
}";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void IsUnmanagedTypeSemanticModel()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
struct S1 { }
struct S2 { public S1 F1; }
struct S3 { public object F1; }
struct S4<T> { public T F1; }
struct S5<T> where T : unmanaged { public T F1; }
enum E1 { }
class C<T>
{
unsafe void M<U>() where U : unmanaged
{
var s1 = new S1();
var s2 = new S2();
var s3 = new S3();
var s4_0 = new S4<int>();
var s4_1 = new S4<object>();
var s4_2 = new S4<U>();
var s5 = new S5<int>();
var i0 = 0;
var e1 = new E1();
var o1 = new object();
var c1 = new C<int>;
var t1 = default(T);
var u1 = default(U);
void* p1 = null;
var a1 = new { X = 0 };
var a2 = new int[1];
var t2 = (0, 0);
}
}");
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var root = tree.GetRoot();
// The spec states the following are unmanaged types:
// sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
// Any enum_type.
// Any pointer_type.
// Any user-defined struct_type that contains fields of unmanaged_types only.
// A type parameter with an unmanaged constraint
Assert.True(getLocalType("s1").IsUnmanagedType);
Assert.True(getLocalType("s2").IsUnmanagedType);
Assert.False(getLocalType("s3").IsUnmanagedType);
Assert.True(getLocalType("s4_0").IsUnmanagedType);
Assert.False(getLocalType("s4_1").IsUnmanagedType);
Assert.True(getLocalType("s4_2").IsUnmanagedType);
Assert.True(getLocalType("s5").IsUnmanagedType);
Assert.True(getLocalType("i0").IsUnmanagedType);
Assert.True(getLocalType("e1").IsUnmanagedType);
Assert.False(getLocalType("o1").IsUnmanagedType);
Assert.False(getLocalType("c1").IsUnmanagedType);
Assert.False(getLocalType("t1").IsUnmanagedType);
Assert.True(getLocalType("u1").IsUnmanagedType);
Assert.True(getLocalType("p1").IsUnmanagedType);
Assert.False(getLocalType("a1").IsUnmanagedType);
Assert.False(getLocalType("a2").IsUnmanagedType);
Assert.True(getLocalType("t2").IsUnmanagedType);
ITypeSymbol getLocalType(string name)
{
var decl = root.DescendantNodes()
.OfType<VariableDeclaratorSyntax>()
.Single(n => n.Identifier.ValueText == name);
return ((ILocalSymbol)model.GetDeclaredSymbol(decl)).Type;
}
}
[Fact]
public void GenericStructPrivateFieldInMetadata()
{
var externalCode = @"
public struct External<T>
{
private T field;
}
";
var metadata = CreateCompilation(externalCode).EmitToImageReference();
var code = @"
public class C
{
public unsafe void M<T, U>() where T : unmanaged
{
var good = new External<int>();
var goodPtr = &good;
var good2 = new External<T>();
var goodPtr2 = &good2;
var bad = new External<object>();
var badPtr = &bad;
var bad2 = new External<U>();
var badPtr2 = &bad2;
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(code, TestOptions.Regular);
var compilation = CreateCompilation(tree, new[] { metadata }, TestOptions.UnsafeReleaseDll);
compilation.VerifyDiagnostics(
// (13,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('External<object>')
// var badPtr = &bad;
Diagnostic(ErrorCode.ERR_ManagedAddr, "&bad").WithArguments("External<object>").WithLocation(13, 22),
// (16,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('External<U>')
// var badPtr2 = &bad2;
Diagnostic(ErrorCode.ERR_ManagedAddr, "&bad2").WithArguments("External<U>").WithLocation(16, 23)
);
var model = compilation.GetSemanticModel(tree);
var root = tree.GetRoot();
Assert.True(getLocalType("good").IsUnmanagedType);
Assert.True(getLocalType("good2").IsUnmanagedType);
Assert.False(getLocalType("bad").IsUnmanagedType);
Assert.False(getLocalType("bad2").IsUnmanagedType);
ITypeSymbol getLocalType(string name)
{
var decl = root.DescendantNodes()
.OfType<VariableDeclaratorSyntax>()
.Single(n => n.Identifier.ValueText == name);
return ((ILocalSymbol)model.GetDeclaredSymbol(decl)).Type;
}
}
#endregion IsManagedType
#region AddressOf operand kinds
[Fact]
public void AddressOfExpressionKinds_Simple()
{
var text = @"
unsafe class C
{
void M(int param)
{
int local;
int* p;
p = ¶m;
p = &local;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void AddressOfExpressionKinds_Dereference()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
p = &(*p);
p = &p[0];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void AddressOfExpressionKinds_Struct()
{
var text = @"
unsafe class C
{
void M()
{
S1 s;
S1* p1 = &s;
S2* p2 = &s.s;
S3* p3 = &s.s.s;
int* p4 = &s.s.s.x;
p2 = &(p1->s);
p3 = &(p2->s);
p4 = &(p3->x);
p2 = &((*p1).s);
p3 = &((*p2).s);
p4 = &((*p3).x);
}
}
struct S1
{
public S2 s;
}
struct S2
{
public S3 s;
}
struct S3
{
public int x;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[WorkItem(529267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529267")]
[Fact]
public void AddressOfExpressionKinds_RangeVariable()
{
var text = @"
using System.Linq;
unsafe class C
{
int M(int param)
{
var z = from x in new int[2] select Goo(&x);
return 0;
}
int Goo(int* p) { return 0; }
}
";
// NOTE: this is a breaking change - dev10 allows this.
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,50): error CS0211: Cannot take the address of the given expression
// var z = from x in new int[2] select Goo(&x);
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "x").WithArguments("x"));
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void AddressOfExpressionKinds_ReadOnlyLocal()
{
var text = @"
class Test { static void Main() { } }
unsafe class C
{
int[] array;
void M()
{
int* p;
const int x = 1;
p = &x; //CS0211
foreach (int y in new int[1])
{
p = &y;
}
using (S s = new S())
{
S* sp = &s;
}
fixed (int* a = &array[0])
{
int** pp = &a;
}
}
}
struct S : System.IDisposable
{
public void Dispose() { }
}
";
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,14): error CS0211: Cannot take the address of the given expression
// p = &x; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "x").WithLocation(13, 14),
// (6,11): warning CS0649: Field 'C.array' is never assigned to, and will always have its default value null
// int[] array;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "array").WithArguments("C.array", "null").WithLocation(6, 11)
);
}
[Fact]
public void AddressOfExpressionKinds_Failure()
{
var text = @"
class Base
{
public int f = 2;
}
unsafe class C : Base
{
event System.Action E;
event System.Action F { add { } remove { } }
int instanceField;
int staticField;
int this[int x] { get { return 0; } set { } }
int P { get; set; }
int M(int param)
{
int local;
int[] array = new int[1];
System.Func<int> func = () => 1;
int* p;
p = &1; //CS0211 (can't addr)
p = &array[0]; //CS0212 (need fixed)
p = &(local = 1); //CS0211
p = &goo; //CS0103 (no goo)
p = &base.f; //CS0212
p = &(local + local); //CS0211
p = &M(local); //CS0211
p = &func(); //CS0211
p = &(local += local); //CS0211
p = &(local == 0 ? local : param); //CS0211
p = &((int)param); //CS0211
p = &default(int); //CS0211
p = &delegate { return 1; }; //CS0211
p = &instanceField; //CS0212
p = &staticField; //CS0212
p = &(local++); //CS0211
p = &this[0]; //CS0211
p = &(() => 1); //CS0211
p = &M; //CS0211
p = &(new System.Int32()); //CS0211
p = &P; //CS0211
p = &sizeof(int); //CS0211
p = &this.instanceField; //CS0212
p = &(+local); //CS0211
int** pp;
pp = &(&local); //CS0211
var q = &(new { }); //CS0208, CS0211 (managed)
var r = &(new int[1]); //CS0208, CS0211 (managed)
var s = &(array as object); //CS0208, CS0211 (managed)
var t = &E; //CS0208
var u = &F; //CS0079 (can't use event like that)
var v = &(E += null); //CS0211
var w = &(F += null); //CS0211
var x = &(array is object); //CS0211
var y = &(array ?? array); //CS0208, CS0211 (managed)
var aa = &this; //CS0208
var bb = &typeof(int); //CS0208, CS0211 (managed)
var cc = &Color.Red; //CS0211
return 0;
}
int Goo(int* p) { return 0; }
static void Main() { }
}
unsafe struct S
{
S(int x)
{
var aa = &this; //CS0212 (need fixed)
}
}
enum Color
{
Red,
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (76,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// var aa = &this; //CS0212 (need fixed)
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this").WithLocation(76, 18),
// (23,14): error CS0211: Cannot take the address of the given expression
// p = &1; //CS0211 (can't addr)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "1").WithLocation(23, 14),
// (24,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &array[0]; //CS0212 (need fixed)
Diagnostic(ErrorCode.ERR_FixedNeeded, "&array[0]").WithLocation(24, 13),
// (25,15): error CS0211: Cannot take the address of the given expression
// p = &(local = 1); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local = 1").WithLocation(25, 15),
// (26,14): error CS0103: The name 'goo' does not exist in the current context
// p = &goo; //CS0103 (no goo)
Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo").WithLocation(26, 14),
// (27,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &base.f; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.f").WithLocation(27, 13),
// (28,15): error CS0211: Cannot take the address of the given expression
// p = &(local + local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local + local").WithLocation(28, 15),
// (29,14): error CS0211: Cannot take the address of the given expression
// p = &M(local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "M(local)").WithLocation(29, 14),
// (30,14): error CS0211: Cannot take the address of the given expression
// p = &func(); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "func()").WithLocation(30, 14),
// (31,15): error CS0211: Cannot take the address of the given expression
// p = &(local += local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local += local").WithLocation(31, 15),
// (32,15): error CS0211: Cannot take the address of the given expression
// p = &(local == 0 ? local : param); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local == 0 ? local : param").WithLocation(32, 15),
// (33,15): error CS0211: Cannot take the address of the given expression
// p = &((int)param); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "(int)param").WithLocation(33, 15),
// (34,14): error CS0211: Cannot take the address of the given expression
// p = &default(int); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "default(int)").WithLocation(34, 14),
// (35,14): error CS0211: Cannot take the address of the given expression
// p = &delegate { return 1; }; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "delegate { return 1; }").WithLocation(35, 14),
// (36,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&instanceField").WithLocation(36, 13),
// (37,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&staticField").WithLocation(37, 13),
// (38,15): error CS0211: Cannot take the address of the given expression
// p = &(local++); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local++").WithLocation(38, 15),
// (39,14): error CS0211: Cannot take the address of the given expression
// p = &this[0]; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "this[0]").WithArguments("C.this[int]").WithLocation(39, 14),
// (40,15): error CS0211: Cannot take the address of the given expression
// p = &(() => 1); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "() => 1").WithLocation(40, 15),
// (41,13): error CS8812: Cannot convert &method group 'M' to non-function pointer type 'int*'.
// p = &M; //CS0211
Diagnostic(ErrorCode.ERR_AddressOfToNonFunctionPointer, "&M").WithArguments("M", "int*").WithLocation(41, 13),
// (42,15): error CS0211: Cannot take the address of the given expression
// p = &(new System.Int32()); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new System.Int32()").WithLocation(42, 15),
// (43,14): error CS0211: Cannot take the address of the given expression
// p = &P; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "P").WithArguments("C.P").WithLocation(43, 14),
// (44,14): error CS0211: Cannot take the address of the given expression
// p = &sizeof(int); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "sizeof(int)").WithLocation(44, 14),
// (45,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &this.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.instanceField").WithLocation(45, 13),
// (46,15): error CS0211: Cannot take the address of the given expression
// p = &(+local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "+local").WithLocation(46, 15),
// (49,16): error CS0211: Cannot take the address of the given expression
// pp = &(&local); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "&local").WithLocation(49, 16),
// (51,19): error CS0211: Cannot take the address of the given expression
// var q = &(new { }); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new { }").WithLocation(51, 19),
// (52,19): error CS0211: Cannot take the address of the given expression
// var r = &(new int[1]); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new int[1]").WithLocation(52, 19),
// (53,19): error CS0211: Cannot take the address of the given expression
// var s = &(array as object); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array as object").WithLocation(53, 19),
// (54,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Action')
// var t = &E; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&E").WithArguments("System.Action").WithLocation(54, 17),
// (55,18): error CS0079: The event 'C.F' can only appear on the left hand side of += or -=
// var u = &F; //CS0079 (can't use event like that)
Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("C.F").WithLocation(55, 18),
// (56,19): error CS0211: Cannot take the address of the given expression
// var v = &(E += null); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "E += null").WithLocation(56, 19),
// (57,19): error CS0211: Cannot take the address of the given expression
// var w = &(F += null); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "F += null").WithLocation(57, 19),
// (58,19): error CS0211: Cannot take the address of the given expression
// var x = &(array is object); //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array is object").WithLocation(58, 19),
// (59,19): error CS0211: Cannot take the address of the given expression
// var y = &(array ?? array); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array ?? array").WithLocation(59, 19),
// (60,19): error CS0211: Cannot take the address of the given expression
// var aa = &this; //CS0208
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "this").WithArguments("this").WithLocation(60, 19),
// (61,19): error CS0211: Cannot take the address of the given expression
// var bb = &typeof(int); //CS0208, CS0211 (managed)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "typeof(int)").WithLocation(61, 19),
// (62,19): error CS0211: Cannot take the address of the given expression
// var cc = &Color.Red; //CS0211
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "Color.Red").WithLocation(62, 19)
);
}
#endregion AddressOf operand kinds
#region AddressOf diagnostics
[Fact]
public void AddressOfManaged()
{
var text = @"
unsafe class C
{
void M<T>(T t)
{
var p0 = &t; //CS0208
C c = new C();
var p1 = &c; //CS0208
S s = new S();
var p2 = &s; //CS0208
var anon = new { };
var p3 = &anon; //CS0208
}
}
public struct S
{
public string s;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
// var p0 = &t; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&t").WithArguments("T"),
// (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')
// var p1 = &c; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&c").WithArguments("C"),
// (12,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// var p2 = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"),
// (15,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>')
// var p3 = &anon; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&anon").WithArguments("<empty anonymous type>"));
}
[Fact]
public void AddressOfManaged_Cycle()
{
var text = @"
unsafe class C
{
void M()
{
S s = new S();
var p = &s; //CS0208
}
}
public struct S
{
public S s; //CS0523
public object o;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,14): error CS0523: Struct member 'S.s' of type 'S' causes a cycle in the struct layout
// public S s; //CS0523
Diagnostic(ErrorCode.ERR_StructLayoutCycle, "s").WithArguments("S.s", "S"),
// (7,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// var p = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"));
}
[Fact]
public void AddressOfVariablesThatRequireFixing()
{
var text = @"
class Base
{
public int instanceField;
public int staticField;
}
unsafe class Derived : Base
{
void M(ref int refParam, out int outParam)
{
Derived d = this;
int[] array = new int[2];
int* p;
p = &instanceField; //CS0212
p = &this.instanceField; //CS0212
p = &base.instanceField; //CS0212
p = &d.instanceField; //CS0212
p = &staticField; //CS0212
p = &this.staticField; //CS0212
p = &base.staticField; //CS0212
p = &d.staticField; //CS0212
p = &array[0]; //CS0212
p = &refParam; //CS0212
p = &outParam; //CS0212
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (17,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&instanceField"),
// (18,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &this.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.instanceField"),
// (19,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &base.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.instanceField"),
// (20,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &d.instanceField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&d.instanceField"),
// (22,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&staticField"),
// (23,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &this.staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.staticField"),
// (24,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &base.staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.staticField"),
// (25,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &d.staticField; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&d.staticField"),
// (27,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &array[0]; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&array[0]"),
// (29,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &refParam; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&refParam"),
// (30,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// p = &outParam; //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&outParam"));
}
[Fact]
public void AddressOfInitializes()
{
var text = @"
public struct S
{
public int x;
public int y;
}
unsafe class C
{
void M()
{
S s;
int* p = &s.x;
int x = s.x; //fine
int y = s.y; //cs0170 (uninitialized)
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (15,17): error CS0170: Use of possibly unassigned field 'y'
// int y = s.y; //cs0170 (uninitialized)
Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.y").WithArguments("y"));
}
[Fact]
public void AddressOfCapturedLocal1()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x;
int* p = &x; //before capture
M(() => { x++; });
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,11): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(&x, () => { x++; });
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedLocal2()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x = 1;
M(() => { x++; });
int* p = &x; //after capture
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,18): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &x;
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedLocal3()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x;
M(() => { int* p = &x; }); // in lambda
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,28): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(() => { int* p = &x; }); // in lambda
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedLocal4()
{
var text = @"
unsafe class C
{
void M(System.Action a)
{
int x;
int* p = &x; //only report the first
M(() => { p = &x; });
p = &x;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,28): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(() => { int* p = &x; }); // in lambda
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"));
}
[Fact]
public void AddressOfCapturedStructField1()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
int* p = &s.x; //before capture
M(() => { s.x++; });
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &s.x; //before capture
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedStructField2()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
s.x = 1;
M(() => { s.x++; });
int* p = &s.x; //after capture
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (11,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &s.x; //after capture
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedStructField3()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
M(() => { int* p = &s.x; }); // in lambda
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,28): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// M(() => { int* p = &s.x; }); // in lambda
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedStructField4()
{
var text = @"
unsafe struct S
{
int x;
void M(System.Action a)
{
S s;
int* p = &s.x; //only report the first
M(() => { p = &s.x; });
p = &s.x;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p = &s.x; //only report the first
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s"));
}
[Fact]
public void AddressOfCapturedParameters()
{
var text = @"
unsafe struct S
{
int x;
void M(int x, S s, System.Action a)
{
M(x, s, () =>
{
int* p1 = &x;
int* p2 = &s.x;
});
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,23): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p1 = &x;
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"),
// (11,23): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
// int* p2 = &s.x;
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s")
);
}
[WorkItem(657083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657083")]
[Fact]
public void CaptureStructWithFixedArray()
{
var text = @"
unsafe public struct Test
{
private delegate int D();
public fixed int i[1];
public int goo()
{
Test t = this;
t.i[0] = 5;
D d = () => t.i[0];
return d();
}
}";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "t.i").WithArguments("t")
);
}
[Fact]
public void AddressOfCapturedFixed1()
{
var text = @"
unsafe class C
{
int x;
void M(System.Action a)
{
fixed(int* p = &x) //fine - error only applies to variables that require fixing
{
M(() => x++);
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void AddressOfCapturedFixed2()
{
var text = @"
unsafe class C
{
void M(ref int x, System.Action a)
{
fixed (int* p = &x) //fine - error only applies to variables that require fixing
{
M(ref x, () => x++);
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,28): error CS1628: Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, or query expression
// M(ref x, () => x++);
Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x"));
}
[WorkItem(543989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543989")]
[Fact]
public void AddressOfInsideAnonymousTypes()
{
var text = @"
public class C
{
public static void Main()
{
int x = 10;
unsafe
{
var t = new { p1 = &x };
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
//(9,27): error CS0828: Cannot assign int* to anonymous type property
// p1 = &x
Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "p1 = &x").WithArguments("int*"));
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[WorkItem(544537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544537")]
[Fact]
public void AddressOfStaticReadonlyFieldInsideFixed()
{
var text = @"
public class Test
{
static readonly int R1 = 45;
unsafe public static void Main()
{
fixed (int* v1 = &R1) { }
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
#endregion AddressOf diagnostics
#region AddressOf SemanticModel tests
[Fact]
public void AddressOfSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal(TypeKind.Pointer, type.TypeKind);
Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)type).PointedAtType.SpecialType);
var declaredSymbol = model.GetDeclaredSymbol(syntax.Ancestors().OfType<VariableDeclaratorSyntax>().First());
Assert.NotNull(declaredSymbol);
Assert.Equal(SymbolKind.Local, declaredSymbol.Kind);
Assert.Equal("p", declaredSymbol.Name);
Assert.Equal(type, ((ILocalSymbol)declaredSymbol).Type);
}
[Fact]
public void SpeculativelyBindPointerToManagedType()
{
var text = @"
unsafe struct S
{
public object o;
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single();
Assert.Equal(SyntaxKind.FieldDeclaration, syntax.Kind());
model.GetSpeculativeTypeInfo(syntax.SpanStart, SyntaxFactory.ParseTypeName("S*"), SpeculativeBindingOption.BindAsTypeOrNamespace);
// Specifically don't see diagnostic from speculative binding.
compilation.VerifyDiagnostics(
// (4,19): warning CS0649: Field 'S.o' is never assigned to, and will always have its default value null
// public object o;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "o").WithArguments("S.o", "null"));
}
[WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")]
[Fact]
public void AddressOfLambdaExpr1()
{
var text = @"
unsafe class C
{
void M()
{
var i1 = &()=>5;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
Assert.Equal("&()", syntax.ToString()); //NOTE: not actually lambda
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal("?*", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Pointer, typeInfo.Type.TypeKind);
Assert.Equal(TypeKind.Error, ((IPointerTypeSymbol)typeInfo.Type).PointedAtType.TypeKind);
}
[WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")]
[Fact]
public void AddressOfLambdaExpr2()
{
var text = @"
unsafe class C
{
void M()
{
var i1 = &(()=>5);
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
Assert.Equal("&(()=>5)", syntax.ToString());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal("?*", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Pointer, typeInfo.Type.TypeKind);
Assert.Equal(TypeKind.Error, ((IPointerTypeSymbol)typeInfo.Type).PointedAtType.TypeKind);
}
[WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")]
[Fact]
public void AddressOfMethodGroup()
{
var text = @"
unsafe class C
{
void M()
{
var i1 = &M;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
compilation.VerifyDiagnostics(
// (6,13): error CS0815: Cannot assign &method group to an implicitly-typed variable
// var i1 = &M;
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "i1 = &M").WithArguments("&method group").WithLocation(6, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal("void C.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.Null(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
}
#endregion AddressOf SemanticModel tests
#region Dereference diagnostics
[Fact]
public void DereferenceSuccess()
{
var text = @"
unsafe class C
{
int M(int* p)
{
return *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void DereferenceNullLiteral()
{
var text = @"
unsafe class C
{
void M()
{
int x = *null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0193: The * or -> operator must be applied to a pointer
// int x = *null;
Diagnostic(ErrorCode.ERR_PtrExpected, "*null"));
}
[Fact]
public void DereferenceNonPointer()
{
var text = @"
unsafe class C
{
void M()
{
int p = 1;
int x = *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,17): error CS0193: The * or -> operator must be applied to a pointer
// int x = *p;
Diagnostic(ErrorCode.ERR_PtrExpected, "*p"));
}
[Fact]
public void DereferenceVoidPointer()
{
var text = @"
unsafe class C
{
void M(void* p)
{
var x = *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0242: The operation in question is undefined on void pointers
// var x = *p;
Diagnostic(ErrorCode.ERR_VoidError, "*p"));
}
[Fact]
public void DereferenceUninitialized()
{
var text = @"
unsafe class C
{
void M()
{
int* p;
int x = *p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,18): error CS0165: Use of unassigned local variable 'p'
// int x = *p;
Diagnostic(ErrorCode.ERR_UseDefViolation, "p").WithArguments("p"));
}
#endregion Dereference diagnostics
#region Dereference SemanticModel tests
[Fact]
public void DereferenceSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
x = *p;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Last();
Assert.Equal(SyntaxKind.PointerIndirectionExpression, syntax.Kind());
var symbolInfo = model.GetSymbolInfo(syntax);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var typeInfo = model.GetTypeInfo(syntax);
var type = typeInfo.Type;
var conv = model.GetConversion(syntax);
Assert.NotNull(type);
Assert.Equal(type, typeInfo.ConvertedType);
Assert.Equal(Conversion.Identity, conv);
Assert.Equal(SpecialType.System_Int32, type.SpecialType);
}
#endregion Dereference SemanticModel tests
#region PointerMemberAccess diagnostics
[Fact]
public void PointerMemberAccessSuccess()
{
var text = @"
unsafe class C
{
string M(int* p)
{
return p->ToString();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerMemberAccessAddress()
{
var text = @"
unsafe struct S
{
int x;
void M(S* sp)
{
int* ip = &(sp->x);
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerMemberAccessNullLiteral()
{
var text = @"
unsafe class C
{
void M()
{
string x = null->ToString(); //Roslyn: CS0193 / Dev10: CS0023
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0193: The * or -> operator must be applied to a pointer
// string x = null->ToString(); //Roslyn: CS0193 / Dev10: CS0023
Diagnostic(ErrorCode.ERR_PtrExpected, "null->ToString"));
}
[Fact]
public void PointerMemberAccessMethodGroup()
{
var text = @"
unsafe class C
{
void M()
{
string x = M->ToString(); //Roslyn: CS0193 / Dev10: CS0023
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0193: The * or -> operator must be applied to a pointer
// string x = M->ToString(); //Roslyn: CS0193 / Dev10: CS0023
Diagnostic(ErrorCode.ERR_PtrExpected, "M->ToString"));
}
[Fact]
public void PointerMemberAccessLambda()
{
var text = @"
unsafe class C
{
void M()
{
string x = (z => z)->ToString(); //Roslyn: CS0193 / Dev10: CS0023
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0193: The * or -> operator must be applied to a pointer
// string x = (z => z)->ToString(); //Roslyn: CS0193 / Dev10: CS0023
Diagnostic(ErrorCode.ERR_PtrExpected, "(z => z)->ToString"));
}
[Fact]
public void PointerMemberAccessNonPointer()
{
var text = @"
unsafe class C
{
void M()
{
int p = 1;
int x = p->GetHashCode();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,17): error CS0193: The * or -> operator must be applied to a pointer
// int x = p->GetHashCode();
Diagnostic(ErrorCode.ERR_PtrExpected, "p->GetHashCode"));
}
[Fact]
public void PointerMemberAccessVoidPointer()
{
var text = @"
unsafe class C
{
void M(void* p)
{
var x = p->GetHashCode();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0242: The operation in question is undefined on void pointers
// var x = p->GetHashCode();
Diagnostic(ErrorCode.ERR_VoidError, "p->GetHashCode"));
}
[Fact]
public void PointerMemberAccessUninitialized()
{
var text = @"
unsafe class C
{
void M()
{
int* p;
int x = p->GetHashCode();
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,18): error CS0165: Use of unassigned local variable 'p'
// int x = *p;
Diagnostic(ErrorCode.ERR_UseDefViolation, "p").WithArguments("p"));
}
[Fact]
public void PointerMemberAccessMemberKinds()
{
var text = @"
unsafe struct S
{
int InstanceField;
static int StaticField;
int InstanceProperty { get; set; }
static int StaticProperty { get; set; }
// No syntax for indexer access.
//int this[int x] { get { return 0; } set { } }
void InstanceMethod() { }
static void StaticMethod() { }
// No syntax for type member access.
//delegate void Delegate();
//struct Type { }
static void Main()
{
S s;
S* p = &s;
p->InstanceField = 1;
p->StaticField = 1; //CS0176
p->InstanceProperty = 2;
p->StaticProperty = 2; //CS0176
p->InstanceMethod();
p->StaticMethod(); //CS0176
p->ExtensionMethod();
System.Action a;
a = p->InstanceMethod;
a = p->StaticMethod; //CS0176
a = p->ExtensionMethod; //CS1113
}
}
static class Extensions
{
public static void ExtensionMethod(this S s)
{
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (26,9): error CS0176: Member 'S.StaticField' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticField = 1; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticField").WithArguments("S.StaticField").WithLocation(26, 9),
// (29,9): error CS0176: Member 'S.StaticProperty' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticProperty = 2; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticProperty").WithArguments("S.StaticProperty").WithLocation(29, 9),
// (32,9): error CS0176: Member 'S.StaticMethod()' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticMethod(); //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticMethod").WithArguments("S.StaticMethod()").WithLocation(32, 9),
// (38,13): error CS0176: Member 'S.StaticMethod()' cannot be accessed with an instance reference; qualify it with a type name instead
// a = p->StaticMethod; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticMethod").WithArguments("S.StaticMethod()").WithLocation(38, 13),
// (39,13): error CS1113: Extension method 'Extensions.ExtensionMethod(S)' defined on value type 'S' cannot be used to create delegates
// a = p->ExtensionMethod; //CS1113
Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "p->ExtensionMethod").WithArguments("Extensions.ExtensionMethod(S)", "S").WithLocation(39, 13)
);
}
// NOTE: a type with events is managed, so this is always an error case.
[Fact]
public void PointerMemberAccessEvents()
{
var text = @"
unsafe struct S
{
event System.Action InstanceFieldLikeEvent;
static event System.Action StaticFieldLikeEvent;
event System.Action InstanceCustomEvent { add { } remove { } }
static event System.Action StaticCustomEvent { add { } remove { } }
static void Main()
{
S s;
S* p = &s; //CS0208
p->InstanceFieldLikeEvent += null;
p->StaticFieldLikeEvent += null; //CS0176
p->InstanceCustomEvent += null;
p->StaticCustomEvent += null; //CS0176
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* p = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"),
// (13,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// S* p = &s; //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"),
// (16,9): error CS0176: Member 'S.StaticFieldLikeEvent' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticFieldLikeEvent += null; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticFieldLikeEvent").WithArguments("S.StaticFieldLikeEvent"),
// (19,9): error CS0176: Member 'S.StaticCustomEvent' cannot be accessed with an instance reference; qualify it with a type name instead
// p->StaticCustomEvent += null; //CS0176
Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticCustomEvent").WithArguments("S.StaticCustomEvent"),
// (5,32): warning CS0067: The event 'S.StaticFieldLikeEvent' is never used
// static event System.Action StaticFieldLikeEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "StaticFieldLikeEvent").WithArguments("S.StaticFieldLikeEvent"),
// (4,25): warning CS0067: The event 'S.InstanceFieldLikeEvent' is never used
// event System.Action InstanceFieldLikeEvent;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "InstanceFieldLikeEvent").WithArguments("S.InstanceFieldLikeEvent")
);
}
#endregion PointerMemberAccess diagnostics
#region PointerMemberAccess SemanticModel tests
[Fact]
public void PointerMemberAccessSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
S s;
S* p = &s;
p->M();
}
}
struct S
{
public void M() { }
public void M(int x) { }
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.PointerMemberAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var methodGroupSyntax = syntax;
var callSyntax = syntax.Parent;
var structType = compilation.GlobalNamespace.GetMember<TypeSymbol>("S");
var structPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(structType));
var structMethod1 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 0);
var structMethod2 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 1);
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Local, receiverSymbol.Kind);
Assert.Equal(structPointerType.GetPublicSymbol(), ((ILocalSymbol)receiverSymbol).Type);
Assert.Equal("p", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(structPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(structPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var methodGroupSummary = model.GetSemanticInfoSummary(methodGroupSyntax);
Assert.Equal(structMethod1, methodGroupSummary.Symbol.GetSymbol());
Assert.Equal(CandidateReason.None, methodGroupSummary.CandidateReason);
Assert.Equal(0, methodGroupSummary.CandidateSymbols.Length);
Assert.Null(methodGroupSummary.Type);
Assert.Null(methodGroupSummary.ConvertedType);
Assert.Equal(ConversionKind.Identity, methodGroupSummary.ImplicitConversion.Kind);
Assert.True(methodGroupSummary.MethodGroup.SetEquals(ImmutableArray.Create<IMethodSymbol>(structMethod1.GetPublicSymbol(), structMethod2.GetPublicSymbol()), EqualityComparer<IMethodSymbol>.Default));
var callSummary = model.GetSemanticInfoSummary(callSyntax);
Assert.Equal(structMethod1, callSummary.Symbol.GetSymbol());
Assert.Equal(CandidateReason.None, callSummary.CandidateReason);
Assert.Equal(0, callSummary.CandidateSymbols.Length);
Assert.Equal(SpecialType.System_Void, callSummary.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, callSummary.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, callSummary.ImplicitConversion.Kind);
Assert.Equal(0, callSummary.MethodGroup.Length);
}
[Fact]
public void PointerMemberAccessSemanticModelAPIs_ErrorScenario()
{
var text = @"
unsafe class C
{
void M()
{
S s;
S* p = &s;
s->M(); //should be 'p'
}
}
struct S
{
public void M() { }
public void M(int x) { }
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.PointerMemberAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var methodGroupSyntax = syntax;
var callSyntax = syntax.Parent;
var structType = compilation.GlobalNamespace.GetMember<TypeSymbol>("S");
var structMethod1 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 0);
var structMethod2 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 1);
var structMethods = ImmutableArray.Create<MethodSymbol>(structMethod1, structMethod2);
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Local, receiverSymbol.Kind);
Assert.Equal(structType.GetPublicSymbol(), ((ILocalSymbol)receiverSymbol).Type);
Assert.Equal("s", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(structType, receiverSummary.Type.GetSymbol());
Assert.Equal(structType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var methodGroupSummary = model.GetSemanticInfoSummary(methodGroupSyntax);
Assert.Equal(structMethod1, methodGroupSummary.Symbol.GetSymbol()); // Have enough info for overload resolution.
Assert.Null(methodGroupSummary.Type);
Assert.Null(methodGroupSummary.ConvertedType);
Assert.Equal(ConversionKind.Identity, methodGroupSummary.ImplicitConversion.Kind);
Assert.True(methodGroupSummary.MethodGroup.SetEquals(structMethods.GetPublicSymbols(), EqualityComparer<IMethodSymbol>.Default));
var callSummary = model.GetSemanticInfoSummary(callSyntax);
Assert.Equal(structMethod1, callSummary.Symbol.GetSymbol()); // Have enough info for overload resolution.
Assert.Equal(SpecialType.System_Void, callSummary.Type.SpecialType);
Assert.Equal(callSummary.Type, callSummary.ConvertedType);
Assert.Equal(ConversionKind.Identity, callSummary.ImplicitConversion.Kind);
Assert.Equal(0, callSummary.MethodGroup.Length);
}
#endregion PointerMemberAccess SemanticModel tests
#region PointerElementAccess
[Fact]
public void PointerElementAccess_NoIndices()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
S s = p[];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0443: Syntax error; value expected
// S s = p[];
Diagnostic(ErrorCode.ERR_ValueExpected, "]"));
}
[Fact]
public void PointerElementAccess_MultipleIndices()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
S s = p[1, 2];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,15): error CS0196: A pointer must be indexed by only one value
// S s = p[1, 2];
Diagnostic(ErrorCode.ERR_PtrIndexSingle, "p[1, 2]"));
}
[Fact]
public void PointerElementAccess_RefIndex()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
int x = 1;
S s = p[ref x];
}
}
";
// Dev10 gives an unhelpful syntax error.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 should not be passed with the 'ref' keyword
// S s = p[ref x];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "ref"));
}
[Fact]
public void PointerElementAccess_OutIndex()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
int x = 1;
S s = p[out x];
}
}
";
// Dev10 gives an unhelpful syntax error.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 should not be passed with the 'out' keyword
// S s = p[out x];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "out"));
}
[Fact]
public void PointerElementAccess_NamedOffset()
{
var text = @"
unsafe struct S
{
void M(S* p)
{
int x = 1;
S s = p[index: x];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,15): error CS1742: An array access may not have a named argument specifier
// S s = p[index: x];
Diagnostic(ErrorCode.ERR_NamedArgumentForArray, "p[index: x]"));
}
[Fact]
public void PointerElementAccess_VoidPointer()
{
var text = @"
unsafe struct S
{
void M(void* p)
{
p[0] = null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,9): error CS0242: The operation in question is undefined on void pointers
// p[0] = null;
Diagnostic(ErrorCode.ERR_VoidError, "p"));
}
[Fact, WorkItem(27945, "https://github.com/dotnet/roslyn/issues/27945")]
public void TakingAddressOfPointerFieldsIsLegal_Static()
{
CreateCompilation(@"
unsafe class C
{
static int* x;
static void Main()
{
fixed (int* y = new int[1])
{
x = y;
}
int* element = &x[0];
*element = 5;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact, WorkItem(27945, "https://github.com/dotnet/roslyn/issues/27945")]
public void TakingAddressOfPointerFieldsIsLegal_Instance()
{
CreateCompilation(@"
unsafe class C
{
int* x;
void Calculate()
{
fixed (int* y = new int[1])
{
x = y;
}
int* element = &x[0];
*element = 5;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact, WorkItem(27945, "https://github.com/dotnet/roslyn/issues/27945")]
public void TakingAddressOfPointerFieldsIsLegal_Local()
{
CreateCompilation(@"
unsafe class C
{
static void Main()
{
int* x;
fixed (int* y = new int[1])
{
x = y;
}
int* element = &x[0];
*element = 5;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
#endregion PointerElementAccess diagnostics
#region PointerElementAccess SemanticModel tests
[Fact]
public void PointerElementAccessSemanticModelAPIs()
{
var text = @"
unsafe class C
{
void M()
{
const int size = 3;
fixed(int* p = new int[size])
{
for (int i = 0; i < size; i++)
{
p[i] = i * i;
}
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression;
var accessSyntax = syntax;
var intType = compilation.GetSpecialType(SpecialType.System_Int32);
var intPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(intType));
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Local, receiverSymbol.Kind);
Assert.Equal(intPointerType.GetPublicSymbol(), ((ILocalSymbol)receiverSymbol).Type);
Assert.Equal("p", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(intPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(intPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var indexSummary = model.GetSemanticInfoSummary(indexSyntax);
var indexSymbol = indexSummary.Symbol;
Assert.Equal(SymbolKind.Local, indexSymbol.Kind);
Assert.Equal(intType.GetPublicSymbol(), ((ILocalSymbol)indexSymbol).Type);
Assert.Equal("i", indexSymbol.Name);
Assert.Equal(CandidateReason.None, indexSummary.CandidateReason);
Assert.Equal(0, indexSummary.CandidateSymbols.Length);
Assert.Equal(intType, indexSummary.Type.GetSymbol());
Assert.Equal(intType, indexSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, indexSummary.ImplicitConversion.Kind);
Assert.Equal(0, indexSummary.MethodGroup.Length);
var accessSummary = model.GetSemanticInfoSummary(accessSyntax);
Assert.Null(accessSummary.Symbol);
Assert.Equal(CandidateReason.None, accessSummary.CandidateReason);
Assert.Equal(0, accessSummary.CandidateSymbols.Length);
Assert.Equal(intType, accessSummary.Type.GetSymbol());
Assert.Equal(intType, accessSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind);
Assert.Equal(0, accessSummary.MethodGroup.Length);
}
[Fact]
public void PointerElementAccessSemanticModelAPIs_Fixed_Unmovable()
{
var text = @"
unsafe class C
{
struct S1
{
public fixed int f[10];
}
void M()
{
S1 p = default;
p.f[i] = 123;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression;
var accessSyntax = syntax;
var intType = compilation.GetSpecialType(SpecialType.System_Int32);
var intPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(intType));
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Field, receiverSymbol.Kind);
Assert.Equal(intPointerType.GetPublicSymbol(), ((IFieldSymbol)receiverSymbol).Type);
Assert.Equal("f", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(intPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(intPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var indexSummary = model.GetSemanticInfoSummary(indexSyntax);
var indexSymbol = indexSummary.Symbol;
Assert.Null(indexSymbol);
var accessSummary = model.GetSemanticInfoSummary(accessSyntax);
Assert.Null(accessSummary.Symbol);
Assert.Equal(CandidateReason.None, accessSummary.CandidateReason);
Assert.Equal(0, accessSummary.CandidateSymbols.Length);
Assert.Equal(intType, accessSummary.Type.GetSymbol());
Assert.Equal(intType, accessSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind);
Assert.Equal(0, accessSummary.MethodGroup.Length);
}
[Fact]
public void PointerElementAccessSemanticModelAPIs_Fixed_Movable()
{
var text = @"
unsafe class C
{
struct S1
{
public fixed int f[10];
}
S1 p = default;
void M()
{
p.f[i] = 123;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single();
Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind());
var receiverSyntax = syntax.Expression;
var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression;
var accessSyntax = syntax;
var intType = compilation.GetSpecialType(SpecialType.System_Int32);
var intPointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(intType));
var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax);
var receiverSymbol = receiverSummary.Symbol;
Assert.Equal(SymbolKind.Field, receiverSymbol.Kind);
Assert.Equal(intPointerType.GetPublicSymbol(), ((IFieldSymbol)receiverSymbol).Type);
Assert.Equal("f", receiverSymbol.Name);
Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason);
Assert.Equal(0, receiverSummary.CandidateSymbols.Length);
Assert.Equal(intPointerType, receiverSummary.Type.GetSymbol());
Assert.Equal(intPointerType, receiverSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind);
Assert.Equal(0, receiverSummary.MethodGroup.Length);
var indexSummary = model.GetSemanticInfoSummary(indexSyntax);
var indexSymbol = indexSummary.Symbol;
Assert.Null(indexSymbol);
var accessSummary = model.GetSemanticInfoSummary(accessSyntax);
Assert.Null(accessSummary.Symbol);
Assert.Equal(CandidateReason.None, accessSummary.CandidateReason);
Assert.Equal(0, accessSummary.CandidateSymbols.Length);
Assert.Equal(intType, accessSummary.Type.GetSymbol());
Assert.Equal(intType, accessSummary.ConvertedType.GetSymbol());
Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind);
Assert.Equal(0, accessSummary.MethodGroup.Length);
}
#endregion PointerElementAccess SemanticModel tests
#region Pointer conversion tests
[Fact]
public void NullLiteralConversion()
{
var text = @"
unsafe struct S
{
void M()
{
byte* b = null;
int* i = null;
S* s = null;
void* v = null;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var nullSyntax in tree.GetCompilationUnitRoot().DescendantTokens().Where(token => token.IsKind(SyntaxKind.NullKeyword)))
{
var node = (ExpressionSyntax)nullSyntax.Parent;
var typeInfo = model.GetTypeInfo(node);
var conv = model.GetConversion(node);
Assert.Null(typeInfo.Type);
Assert.Equal(TypeKind.Pointer, typeInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNullToPointer, conv.Kind);
}
}
[Fact]
public void VoidPointerConversion1()
{
var text = @"
unsafe struct S
{
void M()
{
byte* b = null;
int* i = null;
S* s = null;
void* v1 = b;
void* v2 = i;
void* v3 = s;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var declarationSyntax in tree.GetCompilationUnitRoot().DescendantTokens().OfType<VariableDeclarationSyntax>().Where(syntax => syntax.GetFirstToken().IsKind(SyntaxKind.VoidKeyword)))
{
var value = declarationSyntax.Variables.Single().Initializer.Value;
var typeInfo = model.GetTypeInfo(value);
var type = typeInfo.Type;
Assert.Equal(TypeKind.Pointer, type.TypeKind);
Assert.NotEqual(SpecialType.System_Void, ((IPointerTypeSymbol)type).PointedAtType.SpecialType);
var convertedType = typeInfo.ConvertedType;
Assert.Equal(TypeKind.Pointer, convertedType.TypeKind);
Assert.Equal(SpecialType.System_Void, ((IPointerTypeSymbol)convertedType).PointedAtType.SpecialType);
var conv = model.GetConversion(value);
Assert.Equal(ConversionKind.ImplicitPointerToVoid, conv.Kind);
}
}
[Fact]
public void VoidPointerConversion2()
{
var text = @"
unsafe struct S
{
void M()
{
void* v = null;
void* vv1 = &v;
void** vv2 = &v;
void* vv3 = vv2;
void** vv4 = vv3;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,22): error CS0266: Cannot implicitly convert type 'void*' to 'void**'. An explicit conversion exists (are you missing a cast?)
// void** vv4 = vv3;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "vv3").WithArguments("void*", "void**"));
}
[Fact]
public void ExplicitPointerConversion()
{
var text = @"
unsafe struct S
{
void M(int* i, byte* b, void* v, int** ii, byte** bb, void** vv)
{
i = (int*)b;
i = (int*)v;
i = (int*)ii;
i = (int*)bb;
i = (int*)vv;
b = (byte*)i;
b = (byte*)v;
b = (byte*)ii;
b = (byte*)bb;
b = (byte*)vv;
v = (void*)i;
v = (void*)b;
v = (void*)ii;
v = (void*)bb;
v = (void*)vv;
ii = (int**)i;
ii = (int**)b;
ii = (int**)v;
ii = (int**)bb;
ii = (int**)vv;
bb = (byte**)i;
bb = (byte**)b;
bb = (byte**)v;
bb = (byte**)ii;
bb = (byte**)vv;
vv = (void**)i;
vv = (void**)b;
vv = (void**)v;
vv = (void**)ii;
vv = (void**)bb;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ExplicitPointerNumericConversion()
{
var text = @"
unsafe struct S
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void ExplicitPointerNumericConversion_Illegal()
{
var text = @"
unsafe struct S
{
void M(int* pi, void* pv, bool b, char c, double d, decimal e, float f)
{
b = (bool)pi;
c = (char)pi;
d = (double)pi;
e = (decimal)pi;
f = (float)pi;
b = (bool)pv;
c = (char)pv;
d = (double)pv;
e = (decimal)pv;
f = (float)pv;
pi = (int*)b;
pi = (int*)c;
pi = (int*)d;
pi = (int*)d;
pi = (int*)f;
pv = (void*)b;
pv = (void*)c;
pv = (void*)d;
pv = (void*)e;
pv = (void*)f;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0030: Cannot convert type 'int*' to 'bool'
// b = (bool)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(bool)pi").WithArguments("int*", "bool"),
// (7,13): error CS0030: Cannot convert type 'int*' to 'char'
// c = (char)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(char)pi").WithArguments("int*", "char"),
// (8,13): error CS0030: Cannot convert type 'int*' to 'double'
// d = (double)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double)pi").WithArguments("int*", "double"),
// (9,13): error CS0030: Cannot convert type 'int*' to 'decimal'
// e = (decimal)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(decimal)pi").WithArguments("int*", "decimal"),
// (10,13): error CS0030: Cannot convert type 'int*' to 'float'
// f = (float)pi;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(float)pi").WithArguments("int*", "float"),
// (12,13): error CS0030: Cannot convert type 'void*' to 'bool'
// b = (bool)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(bool)pv").WithArguments("void*", "bool"),
// (13,13): error CS0030: Cannot convert type 'void*' to 'char'
// c = (char)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(char)pv").WithArguments("void*", "char"),
// (14,13): error CS0030: Cannot convert type 'void*' to 'double'
// d = (double)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double)pv").WithArguments("void*", "double"),
// (15,13): error CS0030: Cannot convert type 'void*' to 'decimal'
// e = (decimal)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(decimal)pv").WithArguments("void*", "decimal"),
// (16,13): error CS0030: Cannot convert type 'void*' to 'float'
// f = (float)pv;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(float)pv").WithArguments("void*", "float"),
// (18,14): error CS0030: Cannot convert type 'bool' to 'int*'
// pi = (int*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)b").WithArguments("bool", "int*"),
// (19,14): error CS0030: Cannot convert type 'char' to 'int*'
// pi = (int*)c;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)c").WithArguments("char", "int*"),
// (20,14): error CS0030: Cannot convert type 'double' to 'int*'
// pi = (int*)d;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)d").WithArguments("double", "int*"),
// (21,14): error CS0030: Cannot convert type 'double' to 'int*'
// pi = (int*)d;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)d").WithArguments("double", "int*"),
// (22,14): error CS0030: Cannot convert type 'float' to 'int*'
// pi = (int*)f;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)f").WithArguments("float", "int*"),
// (24,14): error CS0030: Cannot convert type 'bool' to 'void*'
// pv = (void*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)b").WithArguments("bool", "void*"),
// (25,14): error CS0030: Cannot convert type 'char' to 'void*'
// pv = (void*)c;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)c").WithArguments("char", "void*"),
// (26,14): error CS0030: Cannot convert type 'double' to 'void*'
// pv = (void*)d;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)d").WithArguments("double", "void*"),
// (27,14): error CS0030: Cannot convert type 'decimal' to 'void*'
// pv = (void*)e;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)e").WithArguments("decimal", "void*"),
// (28,14): error CS0030: Cannot convert type 'float' to 'void*'
// pv = (void*)f;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)f").WithArguments("float", "void*"));
}
[Fact]
public void ExplicitPointerNumericConversion_Nullable()
{
var text = @"
unsafe struct S
{
void M(int* pi, void* pv, sbyte? sb, byte? b, short? s, ushort? us, int? i, uint? ui, long? l, ulong? ul)
{
sb = (sbyte?)pi;
b = (byte?)pi;
s = (short?)pi;
us = (ushort?)pi;
i = (int?)pi;
ui = (uint?)pi;
l = (long?)pi;
ul = (ulong?)pi;
sb = (sbyte?)pv;
b = (byte?)pv;
s = (short?)pv;
us = (ushort?)pv;
i = (int?)pv;
ui = (uint?)pv;
l = (long?)pv;
ul = (ulong?)pv;
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (24,14): error CS0030: Cannot convert type 'sbyte?' to 'int*'
// pi = (int*)sb;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)sb").WithArguments("sbyte?", "int*"),
// (25,14): error CS0030: Cannot convert type 'byte?' to 'int*'
// pi = (int*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)b").WithArguments("byte?", "int*"),
// (26,14): error CS0030: Cannot convert type 'short?' to 'int*'
// pi = (int*)s;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)s").WithArguments("short?", "int*"),
// (27,14): error CS0030: Cannot convert type 'ushort?' to 'int*'
// pi = (int*)us;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)us").WithArguments("ushort?", "int*"),
// (28,14): error CS0030: Cannot convert type 'int?' to 'int*'
// pi = (int*)i;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)i").WithArguments("int?", "int*"),
// (29,14): error CS0030: Cannot convert type 'uint?' to 'int*'
// pi = (int*)ui;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)ui").WithArguments("uint?", "int*"),
// (30,14): error CS0030: Cannot convert type 'long?' to 'int*'
// pi = (int*)l;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)l").WithArguments("long?", "int*"),
// (31,14): error CS0030: Cannot convert type 'ulong?' to 'int*'
// pi = (int*)ul;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)ul").WithArguments("ulong?", "int*"),
// (33,14): error CS0030: Cannot convert type 'sbyte?' to 'void*'
// pv = (void*)sb;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)sb").WithArguments("sbyte?", "void*"),
// (34,14): error CS0030: Cannot convert type 'byte?' to 'void*'
// pv = (void*)b;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)b").WithArguments("byte?", "void*"),
// (35,14): error CS0030: Cannot convert type 'short?' to 'void*'
// pv = (void*)s;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)s").WithArguments("short?", "void*"),
// (36,14): error CS0030: Cannot convert type 'ushort?' to 'void*'
// pv = (void*)us;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)us").WithArguments("ushort?", "void*"),
// (37,14): error CS0030: Cannot convert type 'int?' to 'void*'
// pv = (void*)i;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)i").WithArguments("int?", "void*"),
// (38,14): error CS0030: Cannot convert type 'uint?' to 'void*'
// pv = (void*)ui;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)ui").WithArguments("uint?", "void*"),
// (39,14): error CS0030: Cannot convert type 'long?' to 'void*'
// pv = (void*)l;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)l").WithArguments("long?", "void*"),
// (40,14): error CS0030: Cannot convert type 'ulong?' to 'void*'
// pv = (void*)ul;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)ul").WithArguments("ulong?", "void*"));
}
[Fact]
public void PointerArrayConversion()
{
var text = @"
using System;
unsafe class C
{
void M(int*[] api, void*[] apv, Array a)
{
a = api;
a.GetValue(0); //runtime error
a = apv;
a.GetValue(0); //runtime error
api = a; //CS0266
apv = a; //CS0266
api = (int*[])a;
apv = (void*[])a;
apv = api; //CS0029
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (13,15): error CS0266: Cannot implicitly convert type 'System.Array' to 'int*[]'. An explicit conversion exists (are you missing a cast?)
// api = a; //CS0266
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("System.Array", "int*[]"),
// (14,15): error CS0266: Cannot implicitly convert type 'System.Array' to 'void*[]'. An explicit conversion exists (are you missing a cast?)
// apv = a; //CS0266
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("System.Array", "void*[]"),
// (19,15): error CS0029: Cannot implicitly convert type 'int*[]' to 'void*[]'
// apv = api; //CS0029
Diagnostic(ErrorCode.ERR_NoImplicitConv, "api").WithArguments("int*[]", "void*[]"));
}
[Fact]
public void PointerArrayToListConversion()
{
var text = @"
using System.Collections.Generic;
unsafe class C
{
void M(int*[] api, void*[] apv)
{
To(api);
To(apv);
api = From(api[0]);
apv = From(apv[0]);
}
void To<T>(IList<T> list)
{
}
IList<T> From<T>(T t)
{
return null;
}
}
";
// NOTE: dev10 also reports some rather silly cascading CS0266s.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,9): error CS0306: The type 'int*' may not be used as a type argument
// To(api);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "To").WithArguments("int*"),
// (9,9): error CS0306: The type 'void*' may not be used as a type argument
// To(apv);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "To").WithArguments("void*"),
// (11,15): error CS0306: The type 'int*' may not be used as a type argument
// api = From(api[0]);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "From").WithArguments("int*"),
// (12,15): error CS0306: The type 'void*' may not be used as a type argument
// apv = From(apv[0]);
Diagnostic(ErrorCode.ERR_BadTypeArgument, "From").WithArguments("void*"));
}
[Fact]
public void PointerArrayToEnumerableConversion()
{
var text = @"
using System.Collections;
unsafe class C
{
void M(int*[] api, void*[] apv)
{
IEnumerable e = api;
e = apv;
}
}
";
// NOTE: as in Dev10, there's a runtime error if you try to access an element.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
#endregion Pointer conversion tests
#region Pointer arithmetic tests
[Fact]
public void PointerArithmetic_LegalNumeric()
{
var text = @"
unsafe class C
{
void M(byte* p, int i, uint ui, long l, ulong ul)
{
p = p + i;
p = i + p;
p = p - i;
p = p + ui;
p = ui + p;
p = p - ui;
p = p + l;
p = l + p;
p = p - l;
p = p + ul;
p = ul + p;
p = p - ul;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
var methodSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M");
var pointerType = methodSymbol.Parameters[0].Type;
Assert.Equal(TypeKind.Pointer, pointerType.TypeKind);
foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>())
{
var summary = model.GetSemanticInfoSummary(binOpSyntax);
if (binOpSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression)
{
Assert.Null(summary.Symbol);
}
else
{
Assert.NotNull(summary.Symbol);
Assert.Equal(MethodKind.BuiltinOperator, ((IMethodSymbol)summary.Symbol).MethodKind);
}
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(pointerType, summary.Type.GetSymbol());
Assert.Equal(pointerType, summary.ConvertedType.GetSymbol());
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
Assert.False(summary.IsCompileTimeConstant);
Assert.False(summary.ConstantValue.HasValue);
}
}
[Fact]
public void PointerArithmetic_LegalPointer()
{
var text = @"
unsafe class C
{
void M(byte* p)
{
var diff = p - p;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>())
{
var summary = model.GetSemanticInfoSummary(binOpSyntax);
Assert.Equal("System.Int64 System.Byte*.op_Subtraction(System.Byte* left, System.Byte* right)", summary.Symbol.ToTestDisplayString());
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(SpecialType.System_Int64, summary.Type.SpecialType);
Assert.Equal(SpecialType.System_Int64, summary.ConvertedType.SpecialType);
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
Assert.False(summary.IsCompileTimeConstant);
Assert.False(summary.ConstantValue.HasValue);
}
}
[Fact]
public void PointerArithmetic_IllegalNumericSubtraction()
{
var text = @"
unsafe class C
{
void M(byte* p, int i, uint ui, long l, ulong ul)
{
p = i - p;
p = ui - p;
p = l - p;
p = ul - p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'byte*'
// p = i - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - p").WithArguments("-", "int", "byte*"),
// (7,13): error CS0019: Operator '-' cannot be applied to operands of type 'uint' and 'byte*'
// p = ui - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ui - p").WithArguments("-", "uint", "byte*"),
// (8,13): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'byte*'
// p = l - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "l - p").WithArguments("-", "long", "byte*"),
// (9,13): error CS0019: Operator '-' cannot be applied to operands of type 'ulong' and 'byte*'
// p = ul - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ul - p").WithArguments("-", "ulong", "byte*"));
}
[Fact]
public void PointerArithmetic_IllegalPointerSubtraction()
{
var text = @"
unsafe class C
{
void M(byte* b, int* i, byte** bb, int** ii)
{
long l;
l = b - i;
l = b - bb;
l = b - ii;
l = i - b;
l = i - bb;
l = i - ii;
l = bb - b;
l = bb - i;
l = bb - ii;
l = ii - b;
l = ii - i;
l = ii - bb;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'int*'
// l = b - i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - i").WithArguments("-", "byte*", "int*"),
// (9,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'byte**'
// l = b - bb;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - bb").WithArguments("-", "byte*", "byte**"),
// (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'int**'
// l = b - ii;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - ii").WithArguments("-", "byte*", "int**"),
// (12,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'byte*'
// l = i - b;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - b").WithArguments("-", "int*", "byte*"),
// (13,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'byte**'
// l = i - bb;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - bb").WithArguments("-", "int*", "byte**"),
// (14,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'int**'
// l = i - ii;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - ii").WithArguments("-", "int*", "int**"),
// (16,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'byte*'
// l = bb - b;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - b").WithArguments("-", "byte**", "byte*"),
// (17,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'int*'
// l = bb - i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - i").WithArguments("-", "byte**", "int*"),
// (18,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'int**'
// l = bb - ii;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - ii").WithArguments("-", "byte**", "int**"),
// (20,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'byte*'
// l = ii - b;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - b").WithArguments("-", "int**", "byte*"),
// (21,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'int*'
// l = ii - i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - i").WithArguments("-", "int**", "int*"),
// (22,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'byte**'
// l = ii - bb;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - bb").WithArguments("-", "int**", "byte**"));
}
[Fact]
public void PointerArithmetic_OtherOperators()
{
var text = @"
unsafe class C
{
void M(byte* p, int i)
{
var r01 = p * i;
var r02 = i * p;
var r03 = p / i;
var r04 = i / p;
var r05 = p % i;
var r06 = i % p;
var r07 = p << i;
var r08 = i << p;
var r09 = p >> i;
var r10 = i >> p;
var r11 = p & i;
var r12 = i & p;
var r13 = p | i;
var r14 = i | p;
var r15 = p ^ i;
var r16 = i ^ p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,19): error CS0019: Operator '*' cannot be applied to operands of type 'byte*' and 'int'
// var r01 = p * i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p * i").WithArguments("*", "byte*", "int"),
// (7,19): error CS0019: Operator '*' cannot be applied to operands of type 'int' and 'byte*'
// var r02 = i * p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i * p").WithArguments("*", "int", "byte*"),
// (8,19): error CS0019: Operator '/' cannot be applied to operands of type 'byte*' and 'int'
// var r03 = p / i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p / i").WithArguments("/", "byte*", "int"),
// (9,19): error CS0019: Operator '/' cannot be applied to operands of type 'int' and 'byte*'
// var r04 = i / p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i / p").WithArguments("/", "int", "byte*"),
// (10,19): error CS0019: Operator '%' cannot be applied to operands of type 'byte*' and 'int'
// var r05 = p % i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p % i").WithArguments("%", "byte*", "int"),
// (11,19): error CS0019: Operator '%' cannot be applied to operands of type 'int' and 'byte*'
// var r06 = i % p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i % p").WithArguments("%", "int", "byte*"),
// (12,19): error CS0019: Operator '<<' cannot be applied to operands of type 'byte*' and 'int'
// var r07 = p << i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p << i").WithArguments("<<", "byte*", "int"),
// (13,19): error CS0019: Operator '<<' cannot be applied to operands of type 'int' and 'byte*'
// var r08 = i << p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i << p").WithArguments("<<", "int", "byte*"),
// (14,19): error CS0019: Operator '>>' cannot be applied to operands of type 'byte*' and 'int'
// var r09 = p >> i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >> i").WithArguments(">>", "byte*", "int"),
// (15,19): error CS0019: Operator '>>' cannot be applied to operands of type 'int' and 'byte*'
// var r10 = i >> p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i >> p").WithArguments(">>", "int", "byte*"),
// (16,19): error CS0019: Operator '&' cannot be applied to operands of type 'byte*' and 'int'
// var r11 = p & i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p & i").WithArguments("&", "byte*", "int"),
// (17,19): error CS0019: Operator '&' cannot be applied to operands of type 'int' and 'byte*'
// var r12 = i & p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i & p").WithArguments("&", "int", "byte*"),
// (18,19): error CS0019: Operator '|' cannot be applied to operands of type 'byte*' and 'int'
// var r13 = p | i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p | i").WithArguments("|", "byte*", "int"),
// (19,19): error CS0019: Operator '|' cannot be applied to operands of type 'int' and 'byte*'
// var r14 = i | p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i | p").WithArguments("|", "int", "byte*"),
// (20,19): error CS0019: Operator '^' cannot be applied to operands of type 'byte*' and 'int'
// var r15 = p ^ i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p ^ i").WithArguments("^", "byte*", "int"),
// (21,19): error CS0019: Operator '^' cannot be applied to operands of type 'int' and 'byte*'
// var r16 = i ^ p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i ^ p").WithArguments("^", "int", "byte*"));
}
[Fact]
public void PointerArithmetic_NumericWidening()
{
var text = @"
unsafe class C
{
void M(int* p, sbyte sb, byte b, short s, ushort us)
{
p = p + sb;
p = p + b;
p = p + s;
p = p + us;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerArithmetic_NumericUDC()
{
var text = @"
unsafe class C
{
void M(int* p)
{
p = p + this;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerArithmetic_Nullable()
{
var text = @"
unsafe class C
{
void M(int* p, int? i)
{
p = p + i;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,13): error CS0019: Operator '+' cannot be applied to operands of type 'int*' and 'int?'
// p = p + i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p + i").WithArguments("+", "int*", "int?"));
}
[Fact]
public void PointerArithmetic_Compound()
{
var text = @"
unsafe class C
{
void M(int* p, int i)
{
p++;
++p;
p--;
--p;
p += i;
p -= i;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerArithmetic_VoidPointer()
{
var text = @"
unsafe class C
{
void M(void* p)
{
var diff = p - p;
p = p + 1;
p = p - 1;
p = 1 + p;
p = 1 - p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,20): error CS0242: The operation in question is undefined on void pointers
// var diff = p - p;
Diagnostic(ErrorCode.ERR_VoidError, "p - p"),
// (7,13): error CS0242: The operation in question is undefined on void pointers
// p = p + 1;
Diagnostic(ErrorCode.ERR_VoidError, "p + 1"),
// (8,13): error CS0242: The operation in question is undefined on void pointers
// p = p - 1;
Diagnostic(ErrorCode.ERR_VoidError, "p - 1"),
// (9,13): error CS0242: The operation in question is undefined on void pointers
// p = 1 + p;
Diagnostic(ErrorCode.ERR_VoidError, "1 + p"),
// (10,13): error CS0242: The operation in question is undefined on void pointers
// p = 1 - p;
Diagnostic(ErrorCode.ERR_VoidError, "1 - p"),
// (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'void*'
// p = 1 - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - p").WithArguments("-", "int", "void*"));
}
[Fact]
public void PointerArithmetic_VoidPointerPointer()
{
var text = @"
unsafe class C
{
void M(void** p) //void** is not a void pointer
{
var diff = p - p;
p = p + 1;
p = p - 1;
p = 1 + p;
p = 1 - p;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'void**'
// p = 1 - p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - p").WithArguments("-", "int", "void**"));
}
#endregion Pointer arithmetic tests
#region Pointer comparison tests
[WorkItem(546712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546712")]
[Fact]
public void PointerComparison_Null()
{
// We had a bug whereby overload resolution was failing if the null
// was on the left. This test regresses the bug.
var text = @"
unsafe struct S
{
bool M(byte* pb, S* ps)
{
return null != pb && null == ps;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerComparison_Pointer()
{
var text = @"
unsafe class C
{
void M(byte* b, int* i, void* v)
{
bool result;
byte* b2 = b;
int* i2 = i;
void* v2 = v;
result = b == b2;
result = b == i2;
result = b == v2;
result = i != i2;
result = i != v2;
result = i != b2;
result = v <= v2;
result = v <= b2;
result = v <= i2;
result = b >= b2;
result = b >= i2;
result = b >= v2;
result = i < i2;
result = i < v2;
result = i < b2;
result = v > v2;
result = v > b2;
result = v > i2;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
compilation.VerifyDiagnostics();
foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>())
{
var summary = model.GetSemanticInfoSummary(binOpSyntax);
if (binOpSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression)
{
Assert.Null(summary.Symbol);
}
else
{
Assert.NotNull(summary.Symbol);
Assert.Equal(MethodKind.BuiltinOperator, ((IMethodSymbol)summary.Symbol).MethodKind);
}
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(SpecialType.System_Boolean, summary.Type.SpecialType);
Assert.Equal(SpecialType.System_Boolean, summary.ConvertedType.SpecialType);
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
Assert.False(summary.IsCompileTimeConstant);
Assert.False(summary.ConstantValue.HasValue);
}
}
[Fact]
public void PointerComparison_PointerPointer()
{
var text = @"
unsafe class C
{
void M(byte* b, byte** bb)
{
bool result;
result = b == bb;
result = b != bb;
result = b <= bb;
result = b >= bb;
result = b < bb;
result = b > bb;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void PointerComparison_Numeric()
{
var text = @"
unsafe class C
{
void M(char* p, int i, uint ui, long l, ulong ul)
{
bool result;
result = p == i;
result = p != i;
result = p <= i;
result = p >= i;
result = p < i;
result = p > i;
result = p == ui;
result = p != ui;
result = p <= ui;
result = p >= ui;
result = p < ui;
result = p > ui;
result = p == l;
result = p != l;
result = p <= l;
result = p >= l;
result = p < l;
result = p > l;
result = p == ul;
result = p != ul;
result = p <= ul;
result = p >= ul;
result = p < ul;
result = p > ul;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'int'
// result = p == i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == i").WithArguments("==", "char*", "int"),
// (9,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'int'
// result = p != i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != i").WithArguments("!=", "char*", "int"),
// (10,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'int'
// result = p <= i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= i").WithArguments("<=", "char*", "int"),
// (11,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'int'
// result = p >= i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= i").WithArguments(">=", "char*", "int"),
// (12,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'int'
// result = p < i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < i").WithArguments("<", "char*", "int"),
// (13,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'int'
// result = p > i;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > i").WithArguments(">", "char*", "int"),
// (15,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'uint'
// result = p == ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == ui").WithArguments("==", "char*", "uint"),
// (16,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'uint'
// result = p != ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != ui").WithArguments("!=", "char*", "uint"),
// (17,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'uint'
// result = p <= ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= ui").WithArguments("<=", "char*", "uint"),
// (18,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'uint'
// result = p >= ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= ui").WithArguments(">=", "char*", "uint"),
// (19,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'uint'
// result = p < ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < ui").WithArguments("<", "char*", "uint"),
// (20,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'uint'
// result = p > ui;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > ui").WithArguments(">", "char*", "uint"),
// (22,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'long'
// result = p == l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == l").WithArguments("==", "char*", "long"),
// (23,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'long'
// result = p != l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != l").WithArguments("!=", "char*", "long"),
// (24,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'long'
// result = p <= l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= l").WithArguments("<=", "char*", "long"),
// (25,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'long'
// result = p >= l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= l").WithArguments(">=", "char*", "long"),
// (26,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'long'
// result = p < l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < l").WithArguments("<", "char*", "long"),
// (27,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'long'
// result = p > l;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > l").WithArguments(">", "char*", "long"),
// (29,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'ulong'
// result = p == ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == ul").WithArguments("==", "char*", "ulong"),
// (30,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'ulong'
// result = p != ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != ul").WithArguments("!=", "char*", "ulong"),
// (31,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'ulong'
// result = p <= ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= ul").WithArguments("<=", "char*", "ulong"),
// (32,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'ulong'
// result = p >= ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= ul").WithArguments(">=", "char*", "ulong"),
// (33,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'ulong'
// result = p < ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < ul").WithArguments("<", "char*", "ulong"),
// (34,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'ulong'
// result = p > ul;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > ul").WithArguments(">", "char*", "ulong"));
}
#endregion Pointer comparison tests
#region Fixed statement diagnostics
[Fact]
public void ERR_BadFixedInitType()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (int p = &x) //not a pointer
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int p = &x) //not a pointer
Diagnostic(ErrorCode.ERR_BadFixedInitType, "p = &x"));
}
[Fact]
public void ERR_FixedMustInit()
{
var text = @"
unsafe class C
{
void M()
{
fixed (int* p) //missing initializer
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,21): error CS0210: You must provide an initializer in a fixed or using statement declaration
// fixed (int* p) //missing initializer
Diagnostic(ErrorCode.ERR_FixedMustInit, "p"));
}
[Fact]
public void ERR_ImplicitlyTypedLocalCannotBeFixed1()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (var p = &x) //implicitly typed
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,20): error CS0821: Implicitly-typed local variables cannot be fixed
// fixed (var p = &x) //implicitly typed
Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "p = &x"));
}
[Fact]
public void ERR_ImplicitlyTypedLocalCannotBeFixed2()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (var p = &x) //not implicitly typed
{
}
}
}
class var
{
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (var p = &x) //not implicitly typed
Diagnostic(ErrorCode.ERR_BadFixedInitType, "p = &x"));
}
[Fact]
public void ERR_MultiTypeInDeclaration()
{
var text = @"
unsafe class C
{
int x;
void M()
{
fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,29): error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_MultiTypeInDeclaration, "var"),
// (8,33): error CS1026: ) expected
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_CloseParenExpected, "q"),
// (8,38): error CS1002: ; expected
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"),
// (8,38): error CS1513: } expected
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_RbraceExpected, ")"),
// (8,29): error CS0210: You must provide an initializer in a fixed or using statement declaration
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_FixedMustInit, "var"),
// (8,33): error CS0103: The name 'q' does not exist in the current context
// fixed (int* p = &x, var q = p) //multiple declarations (vs declarators)
Diagnostic(ErrorCode.ERR_NameNotInContext, "q").WithArguments("q"));
}
[Fact]
public void ERR_BadCastInFixed_String()
{
var text = @"
unsafe class C
{
public NotString n;
void M()
{
fixed (char* p = (string)""hello"")
{
}
fixed (char* p = (string)n)
{
}
}
}
class NotString
{
unsafe public static implicit operator string(NotString n)
{
return null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,22): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null
// public NotString n;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null"));
}
[Fact]
public void ERR_BadCastInFixed_Array()
{
var text = @"
unsafe class C
{
public NotArray n;
void M()
{
fixed (byte* p = (byte[])new byte[0])
{
}
fixed (int* p = (int[])n)
{
}
}
}
class NotArray
{
unsafe public static implicit operator int[](NotArray n)
{
return null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,21): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null
// public NotArray n;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null"));
}
[Fact]
public void ERR_BadCastInFixed_Pointer()
{
var text = @"
unsafe class C
{
public byte x;
public NotPointer n;
void M()
{
fixed (byte* p = (byte*)&x)
{
}
fixed (int* p = n) //CS0213 (confusing, but matches dev10)
{
}
fixed (int* p = (int*)n)
{
}
}
}
class NotPointer
{
unsafe public static implicit operator int*(NotPointer n)
{
return null;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (byte* p = (byte*)&x)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(byte*)&x").WithLocation(9, 26),
// (13,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = n) //CS0213 (confusing, but matches dev10)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "n").WithLocation(13, 25),
// (17,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (int*)n)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(int*)n").WithLocation(17, 25),
// (5,23): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null
// public NotPointer n;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null").WithLocation(5, 23)
);
}
[Fact]
public void ERR_FixedLocalInLambda()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
System.Action a;
a = () => Console.WriteLine(*p);
a = () => Console.WriteLine(*q);
a = () => Console.WriteLine(*r);
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (15,42): error CS1764: Cannot use fixed local 'p' inside an anonymous method, lambda expression, or query expression
// a = () => Console.WriteLine(*p);
Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "p").WithArguments("p"),
// (16,42): error CS1764: Cannot use fixed local 'q' inside an anonymous method, lambda expression, or query expression
// a = () => Console.WriteLine(*q);
Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "q").WithArguments("q"),
// (17,42): error CS1764: Cannot use fixed local 'r' inside an anonymous method, lambda expression, or query expression
// a = () => Console.WriteLine(*r);
Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "r").WithArguments("r"));
}
[Fact]
public void NormalAddressOfInFixedStatement()
{
var text = @"
class Program
{
int x;
int[] a;
unsafe static void Main()
{
Program p = new Program();
int q;
fixed (int* px = (&(p.a[*(&q)]))) //fine
{
}
fixed (int* px = &(p.a[*(&p.x)])) //CS0212
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (15,34): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// fixed (int* px = &(p.a[*(&p.x)])) //CS0212
Diagnostic(ErrorCode.ERR_FixedNeeded, "&p.x"),
// (5,11): warning CS0649: Field 'Program.a' is never assigned to, and will always have its default value null
// int[] a;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("Program.a", "null"));
}
[Fact]
public void StackAllocInFixedStatement()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = stackalloc int[2]) //CS0213 - already fixed
{
}
}
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = stackalloc int[2]) //CS0213 - already fixed
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int[2]").WithLocation(6, 25));
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = stackalloc int[2]) //CS0213 - already fixed
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int[2]").WithLocation(6, 25));
}
[Fact]
public void FixedInitializerRefersToPreviousVariable()
{
var text = @"
unsafe class C
{
int f;
int[] a;
void Goo()
{
fixed (int* q = &f, r = &q[1]) //CS0213
{
}
fixed (int* q = &f, r = &a[*q]) //fine
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,33): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* q = &f, r = &q[1]) //CS0213
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&q[1]"),
// (5,11): warning CS0649: Field 'C.a' is never assigned to, and will always have its default value null
// int[] a;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("C.a", "null"));
}
[Fact]
public void NormalInitializerType_Null()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = null)
{
}
fixed (int* p = &null)
{
}
fixed (int* p = _)
{
}
fixed (int* p = &_)
{
}
fixed (int* p = ()=>throw null)
{
}
fixed (int* p = &(()=>throw null))
{
}
}
}
";
// Confusing, but matches Dev10.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = null)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "null").WithLocation(6, 25),
// (10,26): error CS0211: Cannot take the address of the given expression
// fixed (int* p = &null)
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "null").WithLocation(10, 26),
// (14,25): error CS0103: The name '_' does not exist in the current context
// fixed (int* p = _)
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 25),
// (18,26): error CS0103: The name '_' does not exist in the current context
// fixed (int* p = &_)
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(18, 26),
// (22,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = ()=>throw null)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "()=>throw null").WithLocation(22, 25),
// (26,27): error CS0211: Cannot take the address of the given expression
// fixed (int* p = &(()=>throw null))
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "()=>throw null").WithLocation(26, 27)
);
}
[Fact]
public void NormalInitializerType_Lambda()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = (x => x))
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (x => x))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "x => x").WithLocation(6, 26));
}
[Fact]
public void NormalInitializerType_MethodGroup()
{
var text = @"
class Program
{
unsafe static void Main()
{
fixed (int* p = Main)
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = Main)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "Main").WithLocation(6, 25));
}
[Fact]
public void NormalInitializerType_String()
{
var text = @"
class Program
{
unsafe static void Main()
{
string s = ""hello"";
fixed (char* p = s) //fine
{
}
fixed (void* p = s) //fine
{
}
fixed (int* p = s) //can't convert char* to int*
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?)
// fixed (int* p = s) //can't convert char* to int*
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("char*", "int*"));
}
[Fact]
public void NormalInitializerType_ArrayOfManaged()
{
var text = @"
class Program
{
unsafe static void Main()
{
string[] a = new string[2];
fixed (void* p = a) //string* is not a valid type
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// fixed (void* p = a)
Diagnostic(ErrorCode.ERR_ManagedAddr, "a").WithArguments("string"));
}
[Fact]
public void NormalInitializerType_ArrayOfGenericStruct()
{
var text = @"
public struct MyStruct<T>
{
public T field;
}
class Program
{
unsafe static void Main()
{
var a = new MyStruct<int>[2];
a[0].field = 42;
fixed (MyStruct<int>* p = a)
{
System.Console.Write(p->field);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42");
}
[Fact]
public void NormalInitializerType_ArrayOfGenericStruct_RequiresCSharp8()
{
var text = @"
public struct MyStruct<T>
{
public T field;
}
class Program
{
unsafe static void Main()
{
var a = new MyStruct<int>[2];
fixed (void* p = a)
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (13,26): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater.
// fixed (void* p = a)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "a").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 26));
}
[Fact]
public void NormalInitializerType_Array()
{
var text = @"
class Program
{
unsafe static void Main()
{
char[] a = new char[2];
fixed (char* p = a) //fine
{
}
fixed (void* p = a) //fine
{
}
fixed (int* p = a) //can't convert char* to int*
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?)
// fixed (int* p = a) //can't convert char* to int*
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("char*", "int*"));
}
[Fact]
public void NormalInitializerType_MultiDimensionalArray()
{
var text = @"
class Program
{
unsafe static void Main()
{
char[,] a = new char[2,2];
fixed (char* p = a) //fine
{
}
fixed (void* p = a) //fine
{
}
fixed (int* p = a) //can't convert char* to int*
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?)
// fixed (int* p = a) //can't convert char* to int*
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("char*", "int*"));
}
[Fact]
public void NormalInitializerType_JaggedArray()
{
var text = @"
class Program
{
unsafe static void Main()
{
char[][] a = new char[2][];
fixed (void* p = a) //char[]* is not a valid type
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (8,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('char[]')
// fixed (void* p = a) //char[]* is not a valid type
Diagnostic(ErrorCode.ERR_ManagedAddr, "a").WithArguments("char[]"));
}
#endregion Fixed statement diagnostics
#region Fixed statement semantic model tests
[Fact]
public void FixedSemanticModelDeclaredSymbols()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(3).Reverse().ToArray();
var declaredSymbols = declarators.Select(syntax => (ILocalSymbol)model.GetDeclaredSymbol(syntax)).ToArray();
foreach (var symbol in declaredSymbols)
{
Assert.NotNull(symbol);
Assert.Equal(LocalDeclarationKind.FixedVariable, symbol.GetSymbol().DeclarationKind);
Assert.True(((ILocalSymbol)symbol).IsFixed);
ITypeSymbol type = symbol.Type;
Assert.Equal(TypeKind.Pointer, type.TypeKind);
Assert.Equal(SpecialType.System_Char, ((IPointerTypeSymbol)type).PointedAtType.SpecialType);
}
}
[Fact]
public void FixedSemanticModelSymbolInfo()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.WriteLine(*p);
Console.WriteLine(*q);
Console.WriteLine(*r);
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var stringSymbol = compilation.GetSpecialType(SpecialType.System_String);
var charSymbol = compilation.GetSpecialType(SpecialType.System_Char);
var charPointerSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(charSymbol));
const int numSymbols = 3;
var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(numSymbols).Reverse().ToArray();
var dereferences = tree.GetCompilationUnitRoot().DescendantNodes().Where(syntax => syntax.IsKind(SyntaxKind.PointerIndirectionExpression)).ToArray();
Assert.Equal(numSymbols, dereferences.Length);
var declaredSymbols = declarators.Select(syntax => (ILocalSymbol)model.GetDeclaredSymbol(syntax)).ToArray();
var initializerSummaries = declarators.Select(syntax => model.GetSemanticInfoSummary(syntax.Initializer.Value)).ToArray();
for (int i = 0; i < numSymbols; i++)
{
var summary = initializerSummaries[i];
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(charPointerSymbol, summary.ConvertedType.GetSymbol());
Assert.Equal(Conversion.Identity, summary.ImplicitConversion);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
}
var summary0 = initializerSummaries[0];
Assert.Null(summary0.Symbol);
Assert.Equal(charPointerSymbol, summary0.Type.GetSymbol());
var summary1 = initializerSummaries[1];
var arraySymbol = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
Assert.Equal(arraySymbol, summary1.Symbol.GetSymbol());
Assert.Equal(arraySymbol.Type, summary1.Type.GetSymbol());
var summary2 = initializerSummaries[2];
Assert.Null(summary2.Symbol);
Assert.Equal(stringSymbol, summary2.Type.GetSymbol());
var accessSymbolInfos = dereferences.Select(syntax => model.GetSymbolInfo(((PrefixUnaryExpressionSyntax)syntax).Operand)).ToArray();
for (int i = 0; i < numSymbols; i++)
{
SymbolInfo info = accessSymbolInfos[i];
Assert.Equal(declaredSymbols[i], info.Symbol);
Assert.Equal(0, info.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, info.CandidateReason);
}
}
[Fact]
public void FixedSemanticModelSymbolInfoConversions()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (void* p = &c.c, q = c.a, r = ""hello"")
{
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var stringSymbol = compilation.GetSpecialType(SpecialType.System_String);
var charSymbol = compilation.GetSpecialType(SpecialType.System_Char);
var charPointerSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(charSymbol));
var voidSymbol = compilation.GetSpecialType(SpecialType.System_Void);
var voidPointerSymbol = new PointerTypeSymbol(TypeWithAnnotations.Create(voidSymbol));
const int numSymbols = 3;
var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(numSymbols).Reverse().ToArray();
var initializerSummaries = declarators.Select(syntax => model.GetSemanticInfoSummary(syntax.Initializer.Value)).ToArray();
for (int i = 0; i < numSymbols; i++)
{
var summary = initializerSummaries[i];
Assert.Equal(0, summary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, summary.CandidateReason);
Assert.Equal(0, summary.MethodGroup.Length);
Assert.Null(summary.Alias);
}
var summary0 = initializerSummaries[0];
Assert.Null(summary0.Symbol);
Assert.Equal(charPointerSymbol, summary0.Type.GetSymbol());
Assert.Equal(voidPointerSymbol, summary0.ConvertedType.GetSymbol());
Assert.Equal(Conversion.PointerToVoid, summary0.ImplicitConversion);
var summary1 = initializerSummaries[1];
var arraySymbol = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
Assert.Equal(arraySymbol, summary1.Symbol.GetSymbol());
Assert.Equal(arraySymbol.Type, summary1.Type.GetSymbol());
Assert.Equal(voidPointerSymbol, summary1.ConvertedType.GetSymbol());
Assert.Equal(Conversion.PointerToVoid, summary1.ImplicitConversion);
var summary2 = initializerSummaries[2];
Assert.Null(summary2.Symbol);
Assert.Equal(stringSymbol, summary2.Type.GetSymbol());
Assert.Equal(voidPointerSymbol, summary2.ConvertedType.GetSymbol());
Assert.Equal(Conversion.PointerToVoid, summary2.ImplicitConversion);
}
#endregion Fixed statement semantic model tests
#region sizeof diagnostic tests
[Fact]
public void SizeOfManaged()
{
var text = @"
unsafe class C
{
void M<T>(T t)
{
int x;
x = sizeof(T); //CS0208
x = sizeof(C); //CS0208
x = sizeof(S); //CS0208
}
}
public struct S
{
public string s;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
// x = sizeof(T); //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(T)").WithArguments("T"),
// (8,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C')
// x = sizeof(C); //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(C)").WithArguments("C"),
// (9,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S')
// x = sizeof(S); //CS0208
Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(S)").WithArguments("S"));
}
[Fact]
public void SizeOfUnsafe1()
{
var template = @"
{0} struct S
{{
{1} void M()
{{
int x;
x = sizeof(S); // Type isn't unsafe, but expression is.
}}
}}
";
CompareUnsafeDiagnostics(template,
// (7,13): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(S);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(S)").WithArguments("S"));
}
[Fact]
public void SizeOfUnsafe2()
{
var template = @"
{0} class C
{{
{1} void M()
{{
int x;
x = sizeof(int*);
x = sizeof(int**);
x = sizeof(void*);
x = sizeof(void**);
}}
}}
";
// CONSIDER: Dev10 reports ERR_SizeofUnsafe for each sizeof, but that seems redundant.
CompareUnsafeDiagnostics(template,
// (7,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(int*);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (7,13): error CS0233: 'int*' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(int*);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(int*)").WithArguments("int*"),
// (8,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(int**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (8,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(int**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int**"),
// (8,13): error CS0233: 'int**' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(int**);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(int**)").WithArguments("int**"),
// (9,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(void*);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"),
// (9,13): error CS0233: 'void*' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(void*);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(void*)").WithArguments("void*"),
// (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(void**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"),
// (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// x = sizeof(void**);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void**"),
// (10,13): error CS0233: 'void**' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// x = sizeof(void**);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(void**)").WithArguments("void**")
);
}
[Fact]
public void SizeOfUnsafeInIterator()
{
var text = @"
struct S
{
System.Collections.Generic.IEnumerable<int> M()
{
yield return sizeof(S);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,22): error CS1629: Unsafe code may not appear in iterators
// yield return sizeof(S);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "sizeof(S)"));
}
[Fact]
public void SizeOfNonType1()
{
var text = @"
unsafe struct S
{
void M()
{
S s = new S();
int i = 0;
i = sizeof(s);
i = sizeof(i);
i = sizeof(M);
}
}
";
// Not identical to Dev10, but same meaning.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,20): error CS0118: 's' is a variable but is used like a type
// i = sizeof(s);
Diagnostic(ErrorCode.ERR_BadSKknown, "s").WithArguments("s", "variable", "type"),
// (10,20): error CS0118: 'i' is a variable but is used like a type
// i = sizeof(i);
Diagnostic(ErrorCode.ERR_BadSKknown, "i").WithArguments("i", "variable", "type"),
// (11,20): error CS0246: The type or namespace name 'M' could not be found (are you missing a using directive or an assembly reference?)
// i = sizeof(M);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M").WithArguments("M"),
// (6,11): warning CS0219: The variable 's' is assigned but its value is never used
// S s = new S();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s"));
}
[Fact]
public void SizeOfNonType2()
{
var text = @"
unsafe struct S
{
void M()
{
int i;
i = sizeof(void);
i = sizeof(this); //parser error
i = sizeof(x => x); //parser error
}
}
";
// Not identical to Dev10, but same meaning.
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,20): error CS1547: Keyword 'void' cannot be used in this context
// i = sizeof(void);
Diagnostic(ErrorCode.ERR_NoVoidHere, "void"),
// (8,20): error CS1031: Type expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_TypeExpected, "this"),
// (8,20): error CS1026: ) expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_CloseParenExpected, "this"),
// (8,20): error CS1002: ; expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "this"),
// (8,24): error CS1002: ; expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"),
// (8,24): error CS1513: } expected
// i = sizeof(this); //parser error
Diagnostic(ErrorCode.ERR_RbraceExpected, ")"),
// (9,22): error CS1026: ) expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_CloseParenExpected, "=>"),
// (9,22): error CS1002: ; expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=>"),
// (9,22): error CS1513: } expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>"),
// (9,26): error CS1002: ; expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"),
// (9,26): error CS1513: } expected
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_RbraceExpected, ")"),
// (9,20): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x"),
// (9,25): error CS0103: The name 'x' does not exist in the current context
// i = sizeof(x => x); //parser error
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"));
}
[Fact, WorkItem(529318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529318")]
public void SizeOfNull()
{
string text = @"
class Program
{
int F1 = sizeof(null);
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,21): error CS1031: Type expected
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_TypeExpected, "null"),
// (4,21): error CS1026: ) expected
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "null"),
// (4,21): error CS1003: Syntax error, ',' expected
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_SyntaxError, "null").WithArguments(",", "null"),
// (4,14): error CS0233: '?' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
// int F1 = sizeof(null);
Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(").WithArguments("?"));
}
#endregion sizeof diagnostic tests
#region sizeof semantic model tests
private static readonly Dictionary<SpecialType, int> s_specialTypeSizeOfMap = new Dictionary<SpecialType, int>
{
{ SpecialType.System_SByte, 1 },
{ SpecialType.System_Byte, 1 },
{ SpecialType.System_Int16, 2 },
{ SpecialType.System_UInt16, 2 },
{ SpecialType.System_Int32, 4 },
{ SpecialType.System_UInt32, 4 },
{ SpecialType.System_Int64, 8 },
{ SpecialType.System_UInt64, 8 },
{ SpecialType.System_Char, 2 },
{ SpecialType.System_Single, 4 },
{ SpecialType.System_Double, 8 },
{ SpecialType.System_Boolean, 1 },
{ SpecialType.System_Decimal, 16 },
};
[Fact]
public void SizeOfSemanticModelSafe()
{
var text = @"
class Program
{
static void Main()
{
int x;
x = sizeof(sbyte);
x = sizeof(byte);
x = sizeof(short);
x = sizeof(ushort);
x = sizeof(int);
x = sizeof(uint);
x = sizeof(long);
x = sizeof(ulong);
x = sizeof(char);
x = sizeof(float);
x = sizeof(double);
x = sizeof(bool);
x = sizeof(decimal); //Supported by dev10, but not spec.
}
}
";
// NB: not unsafe
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>();
foreach (var syntax in syntaxes)
{
var typeSummary = model.GetSemanticInfoSummary(syntax.Type);
var type = typeSummary.Symbol as ITypeSymbol;
Assert.NotNull(type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.NotEqual(SpecialType.None, type.SpecialType);
Assert.Equal(type, typeSummary.Type);
Assert.Equal(type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var sizeOfSummary = model.GetSemanticInfoSummary(syntax);
Assert.Null(sizeOfSummary.Symbol);
Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason);
Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType);
Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType);
Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion);
Assert.Equal(0, sizeOfSummary.MethodGroup.Length);
Assert.Null(sizeOfSummary.Alias);
Assert.True(sizeOfSummary.IsCompileTimeConstant);
Assert.Equal(s_specialTypeSizeOfMap[type.SpecialType], sizeOfSummary.ConstantValue);
}
}
[Fact]
public void SizeOfSemanticModelEnum()
{
var text = @"
class Program
{
static void Main()
{
int x;
x = sizeof(E1);
x = sizeof(E2);
}
}
enum E1 : short
{
A
}
enum E2 : long
{
A
}
";
// NB: not unsafe
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>();
foreach (var syntax in syntaxes)
{
var typeSummary = model.GetSemanticInfoSummary(syntax.Type);
var type = typeSummary.Symbol as ITypeSymbol;
Assert.NotNull(type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.Equal(TypeKind.Enum, type.TypeKind);
Assert.Equal(type, typeSummary.Type);
Assert.Equal(type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var sizeOfSummary = model.GetSemanticInfoSummary(syntax);
Assert.Null(sizeOfSummary.Symbol);
Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason);
Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType);
Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType);
Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion);
Assert.Equal(0, sizeOfSummary.MethodGroup.Length);
Assert.Null(sizeOfSummary.Alias);
Assert.True(sizeOfSummary.IsCompileTimeConstant);
Assert.Equal(s_specialTypeSizeOfMap[type.GetEnumUnderlyingType().SpecialType], sizeOfSummary.ConstantValue);
}
}
[Fact]
public void SizeOfSemanticModelUnsafe()
{
var text = @"
struct Outer
{
unsafe static void Main()
{
int x;
x = sizeof(Outer);
x = sizeof(Inner);
x = sizeof(Outer*);
x = sizeof(Inner*);
x = sizeof(Outer**);
x = sizeof(Inner**);
}
struct Inner
{
}
}
";
// NB: not unsafe
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>();
foreach (var syntax in syntaxes)
{
var typeSummary = model.GetSemanticInfoSummary(syntax.Type);
var type = typeSummary.Symbol as ITypeSymbol;
Assert.NotNull(type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.Equal(SpecialType.None, type.SpecialType);
Assert.Equal(type, typeSummary.Type);
Assert.Equal(type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var sizeOfSummary = model.GetSemanticInfoSummary(syntax);
Assert.Null(sizeOfSummary.Symbol);
Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason);
Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType);
Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType);
Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion);
Assert.Equal(0, sizeOfSummary.MethodGroup.Length);
Assert.Null(sizeOfSummary.Alias);
Assert.False(sizeOfSummary.IsCompileTimeConstant);
Assert.False(sizeOfSummary.ConstantValue.HasValue);
}
}
#endregion sizeof semantic model tests
#region stackalloc diagnostic tests
[Fact]
public void StackAllocUnsafe()
{
var template = @"
{0} struct S
{{
{1} void M()
{{
int* p = stackalloc int[1];
}}
}}
";
CompareUnsafeDiagnostics(template,
// (6,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1]")
);
}
[Fact]
public void StackAllocUnsafeInIterator()
{
var text = @"
struct S
{
System.Collections.Generic.IEnumerable<int> M()
{
var p = stackalloc int[1];
yield return 1;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,17): error CS1629: Unsafe code may not appear in iterators
// var p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "stackalloc int[1]"));
}
[Fact]
public void ERR_NegativeStackAllocSize()
{
var text = @"
unsafe struct S
{
void M()
{
int* p = stackalloc int[-1];
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,33): error CS0247: Cannot use a negative size with stackalloc
// int* p = stackalloc int[-1];
Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, "-1"));
}
[Fact]
public void ERR_StackallocInCatchFinally_Catch()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
catch
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
});
static int M(System.Action action)
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
catch
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
catch
{
int* q = stackalloc int[1]; //CS0255
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (17,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (23,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (32,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (51,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (57,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (66,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"));
}
[Fact]
public void ERR_StackallocInCatchFinally_Finally()
{
var text = @"
unsafe class C
{
int x = M(() =>
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
finally
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
});
static int M(System.Action action)
{
try
{
int* p = stackalloc int[1]; //fine
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
finally
{
int* p = stackalloc int[1]; //CS0255
System.Action a = () =>
{
try
{
int* q = stackalloc int[1]; //fine
}
finally
{
int* q = stackalloc int[1]; //CS0255
}
};
}
return 0;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (17,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (23,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (32,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (51,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (57,22): error CS0255: stackalloc may not be used in a catch or finally block
// int* p = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"),
// (66,30): error CS0255: stackalloc may not be used in a catch or finally block
// int* q = stackalloc int[1]; //CS0255
Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"));
}
[Fact]
public void ERR_BadStackAllocExpr()
{
var text = @"
unsafe class C
{
static void Main()
{
int* p = stackalloc int;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,29): error CS1575: A stackalloc expression requires [] after type
// int* p = stackalloc int;
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int"));
}
[Fact]
public void StackAllocCountType()
{
var text = @"
unsafe class C
{
static void Main()
{
{ int* p = stackalloc int[1]; } //fine
{ int* p = stackalloc int[1L]; } //CS0266 (could cast), even though constant value is fine
{ int* p = stackalloc int['c']; } //fine
{ int* p = stackalloc int[""hello""]; } // CS0029 (no conversion)
{ int* p = stackalloc int[Main]; } //CS0428 (method group conversion)
{ int* p = stackalloc int[x => x]; } //CS1660 (lambda conversion)
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,35): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
// { int* p = stackalloc int[1L]; } //CS0266 (could cast), even though constant value is fine
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int"),
// (9,35): error CS0029: Cannot implicitly convert type 'string' to 'int'
// { int* p = stackalloc int["hello"]; } // CS0029 (no conversion)
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int"),
// (10,35): error CS0428: Cannot convert method group 'Main' to non-delegate type 'int'. Did you intend to invoke the method?
// { int* p = stackalloc int[Main]; } //CS0428 (method group conversion)
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "int"),
// (11,35): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type
// { int* p = stackalloc int[x => x]; } //CS1660 (lambda conversion)
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "int"));
}
[Fact]
public void StackAllocCountQuantity()
{
// These all give unhelpful parser errors in Dev10. Let's see if we can do better.
var text = @"
unsafe class C
{
static void Main()
{
{ int* p = stackalloc int[]; }
{ int* p = stackalloc int[1, 1]; }
{ int* p = stackalloc int[][]; }
{ int* p = stackalloc int[][1]; }
{ int* p = stackalloc int[1][]; }
{ int* p = stackalloc int[1][1]; }
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,34): error CS1586: Array creation must have array size or array initializer
// { int* p = stackalloc int[]; }
Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34),
// (7,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[1, 1]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1, 1]").WithLocation(7, 31),
// (8,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[][]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(8, 31),
// (8,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[][]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(8, 31),
// (9,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[][1]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(9, 31),
// (9,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[][1]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][1]").WithLocation(9, 31),
// (10,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[1][]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(10, 31),
// (10,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[1][]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1][]").WithLocation(10, 31),
// (11,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]')
// { int* p = stackalloc int[1][1]; }
Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(11, 31),
// (11,31): error CS1575: A stackalloc expression requires [] after type
// { int* p = stackalloc int[1][1]; }
Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1][1]").WithLocation(11, 31)
);
}
[Fact]
public void StackAllocExplicitConversion()
{
var text = @"
unsafe class C
{
static void Main()
{
{ var p = (int*)stackalloc int[1]; }
{ var p = (void*)stackalloc int[1]; }
{ var p = (C)stackalloc int[1]; }
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (6,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// { var p = (int*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(int*)stackalloc int[1]").WithArguments("int", "int*").WithLocation(6, 19),
// (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'void*' is not possible.
// { var p = (void*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(void*)stackalloc int[1]").WithArguments("int", "void*").WithLocation(7, 19),
// (8,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'C' is not possible.
// { var p = (C)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(C)stackalloc int[1]").WithArguments("int", "C").WithLocation(8, 19));
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (6,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// { var p = (int*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(int*)stackalloc int[1]").WithArguments("int", "int*").WithLocation(6, 19),
// (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'void*' is not possible.
// { var p = (void*)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(void*)stackalloc int[1]").WithArguments("int", "void*").WithLocation(7, 19),
// (8,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'C' is not possible.
// { var p = (C)stackalloc int[1]; }
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(C)stackalloc int[1]").WithArguments("int", "C").WithLocation(8, 19));
}
[Fact]
public void StackAllocNotExpression_FieldInitializer()
{
var text = @"
unsafe class C
{
int* p = stackalloc int[1];
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (4,14): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater.
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(4, 14)
);
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (4,14): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "int*").WithLocation(4, 14)
);
}
[Fact]
public void StackAllocNotExpression_DefaultParameterValue()
{
var text = @"
unsafe class C
{
void M(int* p = stackalloc int[1])
{
}
}
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,21): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void M(int* p = stackalloc int[1])
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "stackalloc int[1]").WithArguments("p").WithLocation(4, 21)
);
}
[Fact]
public void StackAllocNotExpression_ForLoop()
{
var text = @"
unsafe class C
{
void M()
{
for (int* p = stackalloc int[1]; p != null; p++) //fine
{
}
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void StackAllocNotExpression_GlobalDeclaration_01()
{
var text = @"
unsafe int* p = stackalloc int[1];
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (2,17): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible.
// unsafe int* p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[1]").WithArguments("int", "int*").WithLocation(2, 17)
);
}
[Fact]
public void StackAllocNotExpression_GlobalDeclaration_02()
{
var text = @"
using System;
Span<int> p = stackalloc int[1];
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (3,1): error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct.
// Span<int> p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "Span<int>").WithArguments("System.Span<int>").WithLocation(3, 1)
);
}
[Fact]
public void StackAllocNotExpression_GlobalDeclaration_03()
{
var text = @"
var p = stackalloc int[1];
";
CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (2,1): error CS8345: Field or auto-implemented property cannot be of type 'Span<int>' unless it is an instance member of a ref struct.
// var p = stackalloc int[1];
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "var").WithArguments("System.Span<int>").WithLocation(2, 1)
);
}
#endregion stackalloc diagnostic tests
#region stackalloc semantic model tests
[Fact]
public void StackAllocSemanticModel()
{
var text = @"
class C
{
unsafe static void Main()
{
const short count = 20;
void* p = stackalloc char[count];
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var stackAllocSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().Single();
var arrayTypeSyntax = (ArrayTypeSyntax)stackAllocSyntax.Type;
var typeSyntax = arrayTypeSyntax.ElementType;
var countSyntax = arrayTypeSyntax.RankSpecifiers.Single().Sizes.Single();
var stackAllocSummary = model.GetSemanticInfoSummary(stackAllocSyntax);
Assert.Equal(SpecialType.System_Char, ((IPointerTypeSymbol)stackAllocSummary.Type).PointedAtType.SpecialType);
Assert.Equal(SpecialType.System_Void, ((IPointerTypeSymbol)stackAllocSummary.ConvertedType).PointedAtType.SpecialType);
Assert.Equal(Conversion.PointerToVoid, stackAllocSummary.ImplicitConversion);
Assert.Null(stackAllocSummary.Symbol);
Assert.Equal(0, stackAllocSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, stackAllocSummary.CandidateReason);
Assert.Equal(0, stackAllocSummary.MethodGroup.Length);
Assert.Null(stackAllocSummary.Alias);
Assert.False(stackAllocSummary.IsCompileTimeConstant);
Assert.False(stackAllocSummary.ConstantValue.HasValue);
var typeSummary = model.GetSemanticInfoSummary(typeSyntax);
Assert.Equal(SpecialType.System_Char, typeSummary.Type.SpecialType);
Assert.Equal(typeSummary.Type, typeSummary.ConvertedType);
Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion);
Assert.Equal(typeSummary.Symbol, typeSummary.Type);
Assert.Equal(0, typeSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, typeSummary.CandidateReason);
Assert.Equal(0, typeSummary.MethodGroup.Length);
Assert.Null(typeSummary.Alias);
Assert.False(typeSummary.IsCompileTimeConstant);
Assert.False(typeSummary.ConstantValue.HasValue);
var countSummary = model.GetSemanticInfoSummary(countSyntax);
Assert.Equal(SpecialType.System_Int16, countSummary.Type.SpecialType);
Assert.Equal(SpecialType.System_Int32, countSummary.ConvertedType.SpecialType);
Assert.Equal(Conversion.ImplicitNumeric, countSummary.ImplicitConversion);
var countSymbol = (ILocalSymbol)countSummary.Symbol;
Assert.Equal(countSummary.Type, countSymbol.Type);
Assert.Equal("count", countSymbol.Name);
Assert.Equal(0, countSummary.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, countSummary.CandidateReason);
Assert.Equal(0, countSummary.MethodGroup.Length);
Assert.Null(countSummary.Alias);
Assert.True(countSummary.IsCompileTimeConstant);
Assert.True(countSummary.ConstantValue.HasValue);
Assert.Equal((short)20, countSummary.ConstantValue.Value);
}
#endregion stackalloc semantic model tests
#region PointerTypes tests
[WorkItem(5712, "https://github.com/dotnet/roslyn/issues/5712")]
[Fact]
public void PathologicalRefStructPtrMultiDimensionalArray()
{
var text = @"
class C
{
class Goo3 {
internal struct Struct1<U> {}
}
unsafe void NMethodCecilNameHelper_Parameter_AllTogether<U>(ref Goo3.Struct1<int>**[][,,] ppi) { }
}
";
CreateCompilation(text, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics();
}
[WorkItem(543990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543990")]
[Fact]
public void PointerTypeInVolatileField()
{
string text = @"
unsafe class Test
{
static volatile int *px;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,23): warning CS0169: The field 'Test.px' is never used
// static volatile int *px;
Diagnostic(ErrorCode.WRN_UnreferencedField, "px").WithArguments("Test.px"));
}
[WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")]
[Fact]
public void PointerTypesAsTypeArgs()
{
string text = @"
class A
{
public class B{}
}
class C<T> : A
{
private static C<T*[]>.B b;
}
";
var expected = new[]
{
// (8,30): warning CS0169: The field 'C<T>.b' is never used
// private static C<T*[]>.B b;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b")
};
CreateCompilation(text).VerifyDiagnostics(expected);
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected);
}
[WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")]
[WorkItem(544232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544232")]
[Fact]
public void PointerTypesAsTypeArgs2()
{
string text = @"
class A
{
public class B{}
}
class C<T> : A
{
// Dev10 and Roslyn both do not report an error here because they don't look for ERR_ManagedAddr until
// late in the binding process - at which point the type has been resolved to A.B.
private static C<T*[]>.B b;
// Workarounds
private static B b1;
private static A.B b2;
// Dev10 and Roslyn produce the same diagnostic here.
private static C<T*[]> c;
}
";
var expected = new[]
{
// (17,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
// private static C<T*[]> c;
Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("T"),
// (10,30): warning CS0169: The field 'C<T>.b' is never used
// private static C<T*[]>.B b;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b"),
// (13,22): warning CS0169: The field 'C<T>.b1' is never used
// private static B b1;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b1").WithArguments("C<T>.b1"),
// (14,24): warning CS0169: The field 'C<T>.b2' is never used
// private static A.B b2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b2").WithArguments("C<T>.b2"),
// (17,28): warning CS0169: The field 'C<T>.c' is never used
// private static C<T*[]> c;
Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c")
};
CreateCompilation(text).VerifyDiagnostics(expected);
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected);
}
[WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")]
[WorkItem(544232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544232")]
[Fact]
public void PointerTypesAsTypeArgs3()
{
string text = @"
class A
{
public class B{}
}
class C<T> : A
{
// Dev10 and Roslyn both do not report an error here because they don't look for ERR_ManagedAddr until
// late in the binding process - at which point the type has been resolved to A.B.
private static C<string*[]>.B b;
// Dev10 and Roslyn produce the same diagnostic here.
private static C<string*[]> c;
}
";
var expected = new[]
{
// (15,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
// private static C<T*[]> c;
Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("string"),
// (10,30): warning CS0169: The field 'C<T>.b' is never used
// private static C<T*[]>.B b;
Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b"),
// (15,28): warning CS0169: The field 'C<T>.c' is never used
// private static C<T*[]> c;
Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c")
};
CreateCompilation(text).VerifyDiagnostics(expected);
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected);
}
[Fact]
[WorkItem(37051, "https://github.com/dotnet/roslyn/issues/37051")]
public void GenericPointer_Override()
{
var csharp = @"
public unsafe class A
{
public virtual T* M<T>() where T : unmanaged => throw null!;
}
public unsafe class B : A
{
public override T* M<T>() => throw null!;
}
";
var comp = CreateCompilation(csharp, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics();
}
#endregion PointerTypes tests
#region misc unsafe tests
[Fact, WorkItem(543988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543988")]
public void UnsafeFieldInitializerInStruct()
{
string sourceCode = @"
public struct Test
{
static unsafe int*[] myArray = new int*[100];
}
";
var tree = Parse(sourceCode);
var comp = CreateCompilation(tree, options: TestOptions.UnsafeReleaseDll);
var model = comp.GetSemanticModel(tree);
model.GetDiagnostics().Verify();
}
[Fact, WorkItem(544143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544143")]
public void ConvertFromPointerToSelf()
{
string text = @"
struct C
{
unsafe static public implicit operator long*(C* i)
{
return null;
}
unsafe static void Main()
{
C c = new C();
}
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (4,44): error CS0556: User-defined conversion must convert to or from the enclosing type
// unsafe static public implicit operator long*(C* i)
Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "long*"),
// (10,11): warning CS0219: The variable 'c' is assigned but its value is never used
// C c = new C();
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c"));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
var info = model.GetSemanticInfoSummary(parameterSyntax.Type);
}
[Fact]
public void PointerVolatileField()
{
string text = @"
unsafe class C
{
volatile int* p; //Spec section 18.2 specifically allows this.
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (4,19): warning CS0169: The field 'C.p' is never used
// volatile int* p; //Spec section 18.2 specifically allows this.
Diagnostic(ErrorCode.WRN_UnreferencedField, "p").WithArguments("C.p"));
}
[Fact]
public void SemanticModelPointerArrayForeachInfo()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
foreach(int* element in new int*[3])
{
}
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var foreachSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single();
// Reports members of non-generic interfaces (pointers can't be type arguments).
var info = model.GetForEachStatementInfo(foreachSyntax);
Assert.Equal(default(ForEachStatementInfo), info);
}
[Fact, WorkItem(544336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544336")]
public void PointerTypeAsDelegateParamInAnonMethod()
{
// It is legal to use a delegate with pointer types in a "safe" context
// provided that you do not actually make a parameter of unsafe type!
string sourceCode = @"
unsafe delegate int D(int* p);
class C
{
static void Main()
{
D d = delegate { return 1;};
}
}
";
var tree = Parse(sourceCode);
var comp = CreateCompilation(tree, options: TestOptions.UnsafeReleaseDll);
var model = comp.GetSemanticModel(tree);
model.GetDiagnostics().Verify();
}
[Fact(Skip = "529402"), WorkItem(529402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529402")]
public void DotOperatorOnPointerTypes()
{
string text = @"
unsafe class Program
{
static void Main(string[] args)
{
int* i1 = null;
i1.ToString();
}
}
";
var comp = CreateCompilation(text, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (7,9): error CS0023: Operator '.' cannot be applied to operand of type 'int*'
// i1.ToString();
Diagnostic(ErrorCode.ERR_BadUnaryOp, "i1.ToString").WithArguments(".", "int*"));
}
[Fact, WorkItem(545028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545028")]
public void PointerToEnumInGeneric()
{
string text = @"
class C<T>
{
enum E { }
unsafe E* ptr;
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (5,15): warning CS0169: The field 'C<T>.ptr' is never used
// unsafe E* ptr;
Diagnostic(ErrorCode.WRN_UnreferencedField, "ptr").WithArguments("C<T>.ptr"));
}
[Fact]
public void InvalidAsConversions()
{
string text = @"
using System;
public class Test
{
unsafe void M<T>(T t)
{
int* p = null;
Console.WriteLine(t as int*); // CS0244
Console.WriteLine(p as T); // Dev10 reports CS0244 here as well, but CS0413 seems reasonable
Console.WriteLine(null as int*); // CS0244
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (9,27): error CS0244: Neither 'is' nor 'as' is valid on pointer types
// Console.WriteLine(t as int*); // pointer
Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "t as int*"),
// (10,27): error CS0413: The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint
// Console.WriteLine(p as T); // pointer
Diagnostic(ErrorCode.ERR_AsWithTypeVar, "p as T").WithArguments("T"),
// (11,27): error CS0244: Neither 'is' nor 'as' is valid on pointer types
// Console.WriteLine(null as int*); // pointer
Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "null as int*"));
}
[Fact]
public void UnsafeConstructorInitializer()
{
string template = @"
{0} class A
{{
{1} public A(params int*[] x) {{ }}
}}
{0} class B : A
{{
{1} B(int x) {{ }}
{1} B(double x) : base() {{ }}
}}
";
CompareUnsafeDiagnostics(template,
// (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// public A(params int*[] x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"),
// (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// B(int x) { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "B"),
// (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// B(double x) : base() { }
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "base"));
}
[WorkItem(545985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545985")]
[Fact]
public void UnboxPointer()
{
var text = @"
class C
{
unsafe void Goo(object obj)
{
var x = (int*)obj;
}
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,17): error CS0030: Cannot convert type 'object' to 'int*'
// var x = (int*)obj;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)obj").WithArguments("object", "int*"));
}
[Fact]
public void FixedBuffersNoDefiniteAssignmentCheck()
{
var text = @"
unsafe struct struct_ForTestingDefiniteAssignmentChecking
{
//Definite Assignment Checking
public fixed int FixedbuffInt[1024];
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void FixedBuffersNoErrorsOnValidTypes()
{
var text = @"
unsafe struct struct_ForTestingDefiniteAssignmentChecking
{
public fixed bool _Type1[10];
public fixed byte _Type12[10];
public fixed int _Type2[10];
public fixed short _Type3[10];
public fixed long _Type4[10];
public fixed char _Type5[10];
public fixed sbyte _Type6[10];
public fixed ushort _Type7[10];
public fixed uint _Type8[10];
public fixed ulong _Type9[10];
public fixed float _Type10[10];
public fixed double _Type11[10];
}
";
CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact()]
[WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")]
public void FixedBuffersUsageScenarioInRange()
{
var text = @"
using System;
unsafe struct s
{
public fixed bool _buffer[5]; // This is a fixed buffer.
}
class Program
{
static s _fixedBufferExample = new s();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[1] = false;
buffer[2] = true;
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[1]);
Console.Write(buffer[2]);
}
}
}
";
var compilation = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compilation.VerifyIL("Program.Store", @"
{
// Code size 34 (0x22)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: stind.i1
IL_0015: dup
IL_0016: ldc.i4.1
IL_0017: add
IL_0018: ldc.i4.0
IL_0019: stind.i1
IL_001a: ldc.i4.2
IL_001b: add
IL_001c: ldc.i4.1
IL_001d: stind.i1
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.0
IL_0021: ret
}
");
compilation.VerifyIL("Program.Load", @"
{
// Code size 46 (0x2e)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldind.u1
IL_0014: call ""void System.Console.Write(bool)""
IL_0019: dup
IL_001a: ldc.i4.1
IL_001b: add
IL_001c: ldind.u1
IL_001d: call ""void System.Console.Write(bool)""
IL_0022: ldc.i4.2
IL_0023: add
IL_0024: ldind.u1
IL_0025: call ""void System.Console.Write(bool)""
IL_002a: ldc.i4.0
IL_002b: conv.u
IL_002c: stloc.0
IL_002d: ret
}
");
}
[Fact()]
[WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")]
public void FixedBuffersUsagescenarioOutOfRange()
{
// This should work as no range checking for unsafe code.
//however the fact that we are writing bad unsafe code has potential for encountering problems
var text = @"
using System;
unsafe struct s
{
public fixed bool _buffer[5]; // This is a fixed buffer.
}
class Program
{
static s _fixedBufferExample = new s();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[8] = false;
buffer[10] = true;
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[8]);
Console.Write(buffer[10]);
}
}
}
";
//IL Baseline rather than execute because I'm intentionally writing outside of bounds of buffer
// This will compile without warning but runtime behavior is unpredictable.
var compilation = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compilation.VerifyIL("Program.Load", @"
{
// Code size 47 (0x2f)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldind.u1
IL_0014: call ""void System.Console.Write(bool)""
IL_0019: dup
IL_001a: ldc.i4.8
IL_001b: add
IL_001c: ldind.u1
IL_001d: call ""void System.Console.Write(bool)""
IL_0022: ldc.i4.s 10
IL_0024: add
IL_0025: ldind.u1
IL_0026: call ""void System.Console.Write(bool)""
IL_002b: ldc.i4.0
IL_002c: conv.u
IL_002d: stloc.0
IL_002e: ret
}");
compilation.VerifyIL("Program.Store", @"
{
// Code size 35 (0x23)
.maxstack 3
.locals init (pinned bool& V_0)
IL_0000: ldsflda ""s Program._fixedBufferExample""
IL_0005: ldflda ""bool* s._buffer""
IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: stind.i1
IL_0015: dup
IL_0016: ldc.i4.8
IL_0017: add
IL_0018: ldc.i4.0
IL_0019: stind.i1
IL_001a: ldc.i4.s 10
IL_001c: add
IL_001d: ldc.i4.1
IL_001e: stind.i1
IL_001f: ldc.i4.0
IL_0020: conv.u
IL_0021: stloc.0
IL_0022: ret
}");
}
[Fact]
public void FixedBufferUsageWith_this()
{
var text = @"
using System;
unsafe struct s
{
private fixed ushort _e_res[4];
void Error_UsingFixedBuffersWithThis()
{
fixed (ushort* abc = this._e_res)
{
abc[2] = 1;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
}
[Fact]
[WorkItem(547074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547074")]
public void FixedBufferWithNoSize()
{
var text = @"
unsafe struct S
{
fixed[
}
";
var s = CreateCompilation(text).GlobalNamespace.GetMember<TypeSymbol>("S");
foreach (var member in s.GetMembers())
{
var field = member as FieldSymbol;
if (field != null)
{
Assert.Equal(0, field.FixedSize);
Assert.True(field.Type.IsPointerType());
Assert.True(field.HasPointerType);
}
}
}
[Fact()]
[WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")]
public void FixedBufferUsageDifferentAssemblies()
{
// Ensure fixed buffers work as expected when fixed buffer is created in different assembly to where it is consumed.
var s1 =
@"using System;
namespace ClassLibrary1
{
public unsafe struct FixedBufferExampleForSizes
{
public fixed bool _buffer[5]; // This is a fixed buffer.
}
}";
var s2 =
@"using System; using ClassLibrary1;
namespace ConsoleApplication30
{
class Program
{
static FixedBufferExampleForSizes _fixedBufferExample = new FixedBufferExampleForSizes();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[10] = false;
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[10]);
}
}
}
}";
var comp1 = CompileAndVerify(s1, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).Compilation;
var comp2 = CompileAndVerify(s2,
options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails,
references: new MetadataReference[] { MetadataReference.CreateFromImage(comp1.EmitToArray()) },
expectedOutput: "TrueFalse").Compilation;
var s3 =
@"using System; using ClassLibrary1;
namespace ConsoleApplication30
{
class Program
{
static FixedBufferExampleForSizes _fixedBufferExample = new FixedBufferExampleForSizes();
static void Main()
{
// Store values in the fixed buffer.
// ... The load the values from the fixed buffer.
Store();
Load();
}
unsafe static void Store()
{
// Put the fixed buffer in unmovable memory.
// ... Then assign some elements.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
buffer[0] = true;
buffer[10] = false;
buffer[1024] = true; //Intentionally outside range
}
}
unsafe static void Load()
{
// Put in unmovable memory.
// ... Then load some values from the memory.
fixed (bool* buffer = _fixedBufferExample._buffer)
{
Console.Write(buffer[0]);
Console.Write(buffer[10]);
Console.Write(buffer[1024]);
}
}
}
}";
// Only compile this as its intentionally writing outside of fixed buffer boundaries and
// this doesn't warn but causes flakiness when executed.
var comp3 = CompileAndVerify(s3,
options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails,
references: new MetadataReference[] { MetadataReference.CreateFromImage(comp1.EmitToArray()) }).Compilation;
}
[Fact]
public void FixedBufferUsageSizeCheckChar()
{
//Determine the Correct size based upon expansion for different no of elements
var text = @"using System;
unsafe struct FixedBufferExampleForSizes1
{
public fixed char _buffer[1]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes2
{
public fixed char _buffer[2]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes3
{
public fixed char _buffer[3]; // This is a fixed buffer.
}
class Program
{
// Reference to struct containing a fixed buffer
static FixedBufferExampleForSizes1 _fixedBufferExample1 = new FixedBufferExampleForSizes1();
static FixedBufferExampleForSizes2 _fixedBufferExample2 = new FixedBufferExampleForSizes2();
static FixedBufferExampleForSizes3 _fixedBufferExample3 = new FixedBufferExampleForSizes3();
static unsafe void Main()
{
int x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample1);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample2);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample3);
Console.Write(x.ToString());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"246");
}
[Fact]
public void FixedBufferUsageSizeCheckInt()
{
//Determine the Correct size based upon expansion for different no of elements
var text = @"using System;
unsafe struct FixedBufferExampleForSizes1
{
public fixed int _buffer[1]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes2
{
public fixed int _buffer[2]; // This is a fixed buffer.
}
unsafe struct FixedBufferExampleForSizes3
{
public fixed int _buffer[3]; // This is a fixed buffer.
}
class Program
{
// Reference to struct containing a fixed buffer
static FixedBufferExampleForSizes1 _fixedBufferExample1 = new FixedBufferExampleForSizes1();
static FixedBufferExampleForSizes2 _fixedBufferExample2 = new FixedBufferExampleForSizes2();
static FixedBufferExampleForSizes3 _fixedBufferExample3 = new FixedBufferExampleForSizes3();
static unsafe void Main()
{
int x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample1);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample2);
Console.Write(x.ToString());
x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample3);
Console.Write(x.ToString());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"4812");
}
[Fact]
public void CannotTakeAddressOfRefReadOnlyParameter()
{
CreateCompilation(@"
public class Test
{
unsafe void M(in int p)
{
int* pointer = &p;
}
}", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (6,24): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// int* pointer = &p;
Diagnostic(ErrorCode.ERR_FixedNeeded, "&p").WithLocation(6, 24)
);
}
#endregion
[Fact]
public void AddressOfFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
fixed (int* a = &s.Buf) {}
fixed (int* b = &s_f.Buf) {}
int* c = &s.Buf;
int* d = &s_f.Buf;
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (12,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* a = &s.Buf) {}
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&s.Buf").WithLocation(12, 25),
// (13,26): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// fixed (int* b = &s_f.Buf) {}
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(13, 26),
// (14,18): error CS0266: Cannot implicitly convert type 'int**' to 'int*'. An explicit conversion exists (are you missing a cast?)
// int* c = &s.Buf;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "&s.Buf").WithArguments("int**", "int*").WithLocation(14, 18),
// (15,19): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// int* d = &s_f.Buf;
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(15, 19));
}
[Fact]
public void FixedFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
fixed (int* a = s.Buf) {}
fixed (int* b = s_f.Buf) {}
int* c = s.Buf;
int* d = s_f.Buf;
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (12,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* a = s.Buf) {}
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "s.Buf").WithLocation(12, 25),
// (15,18): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// int* d = s_f.Buf;
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(15, 18));
}
[Fact]
public void NoPointerDerefMoveableFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
int x = *s.Buf;
int y = *s_f.Buf;
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (13,18): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.
// int y = *s_f.Buf;
Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "s_f.Buf").WithLocation(13, 18));
}
[Fact]
public void AddressOfElementAccessFixedSizeBuffer()
{
CreateCompilation(@"
unsafe struct S
{
public fixed int Buf[1];
}
unsafe class C
{
static S s_f;
void M(S s)
{
fixed (int* a = &s.Buf[0]) { }
fixed (int* b = &s_f.Buf[0]) { }
int* c = &s.Buf[0];
int* d = &s_f.Buf[0];
int* e = &(s.Buf[0]);
int* f = &(s_f.Buf[0]);
}
}", options: TestOptions.UnsafeDebugDll).VerifyDiagnostics(
// (12,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression
// fixed (int* a = &s.Buf[0]) { }
Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&s.Buf[0]").WithLocation(12, 25),
// (15,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// int* d = &s_f.Buf[0];
Diagnostic(ErrorCode.ERR_FixedNeeded, "&s_f.Buf[0]").WithLocation(15, 18),
// (17,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer
// int* f = &(s_f.Buf[0]);
Diagnostic(ErrorCode.ERR_FixedNeeded, "&(s_f.Buf[0])").WithLocation(17, 18));
}
[Fact, WorkItem(34693, "https://github.com/dotnet/roslyn/issues/34693")]
public void Repro_34693()
{
var csharp = @"
namespace Interop
{
public unsafe struct PROPVARIANT
{
public CAPROPVARIANT ca;
}
public unsafe struct CAPROPVARIANT
{
public uint cElems;
public PROPVARIANT* pElems;
}
}";
var comp = CreateCompilation(csharp, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics();
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/PkgCmdID.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.VisualStudio.DiagnosticsWindow
{
internal static class PkgCmdIDList
{
public const uint CmdIDRoslynDiagnosticWindow = 0x101;
};
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.VisualStudio.DiagnosticsWindow
{
internal static class PkgCmdIDList
{
public const uint CmdIDRoslynDiagnosticWindow = 0x101;
};
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/EditorFeatures/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Wrapping;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping
{
public class BinaryExpressionWrappingTests : AbstractWrappingTests
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpWrappingCodeRefactoringProvider();
private OptionsCollection EndOfLine => Option(
CodeStyleOptions2.OperatorPlacementWhenWrapping,
OperatorPlacementWhenWrappingPreference.EndOfLine);
private OptionsCollection BeginningOfLine => Option(
CodeStyleOptions2.OperatorPlacementWhenWrapping,
OperatorPlacementWhenWrappingPreference.BeginningOfLine);
private Task TestEndOfLine(string markup, string expected)
=> TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters(
options: EndOfLine));
private Task TestBeginningOfLine(string markup, string expected)
=> TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters(
options: BeginningOfLine));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSyntaxError()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i && (j && )
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSelection()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([|i|] && j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingBeforeExpr()
{
await TestMissingAsync(
@"class C {
void Bar() {
[||]if (i && j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSingleExpr()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithMultiLineExpression()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i && (j +
k)) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithMultiLineExpr2()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i && @""
"") {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf()
{
await TestEndOfLine(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf_IncludingOp()
{
await TestBeginningOfLine(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
@"class C {
void Bar() {
if (i
&& j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf2()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i[||] && j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf3()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i [||]&& j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf4()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i &&[||] j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf5()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i && [||]j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestTwoExprWrappingCases_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestTwoExprWrappingCases_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (i
&& j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestThreeExprWrappingCases_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j || k) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (i &&
j ||
k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestThreeExprWrappingCases_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j || k) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (i
&& j
|| k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_AllOptions_NoInitialMatches_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if (
[||]i &&
j
|| k) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (
i &&
j ||
k) {
}
}
}",
@"class C {
void Bar() {
if (
i && j || k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_AllOptions_NoInitialMatches_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if (
[||]i &&
j
|| k) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (
i
&& j
|| k) {
}
}
}",
@"class C {
void Bar() {
if (
i && j || k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption1()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]a &&
b) {
}
}
}",
@"class C {
void Bar() {
if (a
&& b) {
}
}
}",
@"class C {
void Bar() {
if (a && b) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption2_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]a
&& b) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (a &&
b) {
}
}
}",
@"class C {
void Bar() {
if (a && b) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption2_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]a
&& b) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (a && b) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInLocalInitializer_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo() {
var v = [||]a && b && c;
}
}",
BeginningOfLine,
@"class C {
void Goo() {
var v = a
&& b
&& c;
}
}",
@"class C {
void Goo() {
var v = a
&& b
&& c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInLocalInitializer_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo() {
var v = [||]a && b && c;
}
}",
EndOfLine,
@"class C {
void Goo() {
var v = a &&
b &&
c;
}
}",
@"class C {
void Goo() {
var v = a &&
b &&
c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v = [||]a && b && c;
}",
BeginningOfLine,
@"class C {
bool v = a
&& b
&& c;
}",
@"class C {
bool v = a
&& b
&& c;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_End()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v = [||]a && b && c;
}",
EndOfLine,
@"class C {
bool v = a &&
b &&
c;
}",
@"class C {
bool v = a &&
b &&
c;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestAddition_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
var goo = [||]""now"" + ""is"" + ""the"" + ""time"";
}
}",
EndOfLine,
@"class C {
void Bar() {
var goo = ""now"" +
""is"" +
""the"" +
""time"";
}
}",
@"class C {
void Bar() {
var goo = ""now"" +
""is"" +
""the"" +
""time"";
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestAddition_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
var goo = [||]""now"" + ""is"" + ""the"" + ""time"";
}
}",
BeginningOfLine,
@"class C {
void Bar() {
var goo = ""now""
+ ""is""
+ ""the""
+ ""time"";
}
}",
@"class C {
void Bar() {
var goo = ""now""
+ ""is""
+ ""the""
+ ""time"";
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestUnderscoreName_End()
{
await TestEndOfLine(
@"class C {
void Bar() {
if ([||]i is var _ && _ != null) {
}
}
}",
@"class C {
void Bar() {
if (i is var _ &&
_ != null) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestUnderscoreName_Beginning()
{
await TestBeginningOfLine(
@"class C {
void Bar() {
if ([||]i is var _ && _ != null) {
}
}
}",
@"class C {
void Bar() {
if (i is var _
&& _ != null) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_Already_Wrapped_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v =
[||]a && b && c;
}",
BeginningOfLine,
@"class C {
bool v =
a
&& b
&& c;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_Already_Wrapped_End()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v =
[||]a && b && c;
}",
EndOfLine,
@"class C {
bool v =
a &&
b &&
c;
}");
}
[WorkItem(34127, "https://github.com/dotnet/roslyn/issues/34127")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestWrapLowerPrecedenceInLargeBinary()
{
await TestAllWrappingCasesAsync(
@"class C
{
bool v = [||]a + b + c + d == x * y * z;
}",
EndOfLine,
@"class C
{
bool v = a + b + c + d ==
x * y * z;
}",
@"class C
{
bool v = a + b + c + d ==
x * y * z;
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Wrapping;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping
{
public class BinaryExpressionWrappingTests : AbstractWrappingTests
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpWrappingCodeRefactoringProvider();
private OptionsCollection EndOfLine => Option(
CodeStyleOptions2.OperatorPlacementWhenWrapping,
OperatorPlacementWhenWrappingPreference.EndOfLine);
private OptionsCollection BeginningOfLine => Option(
CodeStyleOptions2.OperatorPlacementWhenWrapping,
OperatorPlacementWhenWrappingPreference.BeginningOfLine);
private Task TestEndOfLine(string markup, string expected)
=> TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters(
options: EndOfLine));
private Task TestBeginningOfLine(string markup, string expected)
=> TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters(
options: BeginningOfLine));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSyntaxError()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i && (j && )
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSelection()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([|i|] && j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingBeforeExpr()
{
await TestMissingAsync(
@"class C {
void Bar() {
[||]if (i && j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSingleExpr()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithMultiLineExpression()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i && (j +
k)) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithMultiLineExpr2()
{
await TestMissingAsync(
@"class C {
void Bar() {
if ([||]i && @""
"") {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf()
{
await TestEndOfLine(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf_IncludingOp()
{
await TestBeginningOfLine(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
@"class C {
void Bar() {
if (i
&& j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf2()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i[||] && j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf3()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i [||]&& j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf4()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i &&[||] j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIf5()
{
await TestEndOfLine(
@"class C {
void Bar() {
if (i && [||]j) {
}
}
}",
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestTwoExprWrappingCases_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (i &&
j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestTwoExprWrappingCases_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (i
&& j) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestThreeExprWrappingCases_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j || k) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (i &&
j ||
k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestThreeExprWrappingCases_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]i && j || k) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (i
&& j
|| k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_AllOptions_NoInitialMatches_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if (
[||]i &&
j
|| k) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (
i &&
j ||
k) {
}
}
}",
@"class C {
void Bar() {
if (
i && j || k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_AllOptions_NoInitialMatches_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if (
[||]i &&
j
|| k) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (
i
&& j
|| k) {
}
}
}",
@"class C {
void Bar() {
if (
i && j || k) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption1()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]a &&
b) {
}
}
}",
@"class C {
void Bar() {
if (a
&& b) {
}
}
}",
@"class C {
void Bar() {
if (a && b) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption2_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]a
&& b) {
}
}
}",
EndOfLine,
@"class C {
void Bar() {
if (a &&
b) {
}
}
}",
@"class C {
void Bar() {
if (a && b) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption2_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
if ([||]a
&& b) {
}
}
}",
BeginningOfLine,
@"class C {
void Bar() {
if (a && b) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInLocalInitializer_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo() {
var v = [||]a && b && c;
}
}",
BeginningOfLine,
@"class C {
void Goo() {
var v = a
&& b
&& c;
}
}",
@"class C {
void Goo() {
var v = a
&& b
&& c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInLocalInitializer_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo() {
var v = [||]a && b && c;
}
}",
EndOfLine,
@"class C {
void Goo() {
var v = a &&
b &&
c;
}
}",
@"class C {
void Goo() {
var v = a &&
b &&
c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v = [||]a && b && c;
}",
BeginningOfLine,
@"class C {
bool v = a
&& b
&& c;
}",
@"class C {
bool v = a
&& b
&& c;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_End()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v = [||]a && b && c;
}",
EndOfLine,
@"class C {
bool v = a &&
b &&
c;
}",
@"class C {
bool v = a &&
b &&
c;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestAddition_End()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
var goo = [||]""now"" + ""is"" + ""the"" + ""time"";
}
}",
EndOfLine,
@"class C {
void Bar() {
var goo = ""now"" +
""is"" +
""the"" +
""time"";
}
}",
@"class C {
void Bar() {
var goo = ""now"" +
""is"" +
""the"" +
""time"";
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestAddition_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
void Bar() {
var goo = [||]""now"" + ""is"" + ""the"" + ""time"";
}
}",
BeginningOfLine,
@"class C {
void Bar() {
var goo = ""now""
+ ""is""
+ ""the""
+ ""time"";
}
}",
@"class C {
void Bar() {
var goo = ""now""
+ ""is""
+ ""the""
+ ""time"";
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestUnderscoreName_End()
{
await TestEndOfLine(
@"class C {
void Bar() {
if ([||]i is var _ && _ != null) {
}
}
}",
@"class C {
void Bar() {
if (i is var _ &&
_ != null) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestUnderscoreName_Beginning()
{
await TestBeginningOfLine(
@"class C {
void Bar() {
if ([||]i is var _ && _ != null) {
}
}
}",
@"class C {
void Bar() {
if (i is var _
&& _ != null) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_Already_Wrapped_Beginning()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v =
[||]a && b && c;
}",
BeginningOfLine,
@"class C {
bool v =
a
&& b
&& c;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInField_Already_Wrapped_End()
{
await TestAllWrappingCasesAsync(
@"class C {
bool v =
[||]a && b && c;
}",
EndOfLine,
@"class C {
bool v =
a &&
b &&
c;
}");
}
[WorkItem(34127, "https://github.com/dotnet/roslyn/issues/34127")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestWrapLowerPrecedenceInLargeBinary()
{
await TestAllWrappingCasesAsync(
@"class C
{
bool v = [||]a + b + c + d == x * y * z;
}",
EndOfLine,
@"class C
{
bool v = a + b + c + d ==
x * y * z;
}",
@"class C
{
bool v = a + b + c + d ==
x * y * z;
}");
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractDescriptionBuilder.LinkFlags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
{
internal abstract partial class AbstractDescriptionBuilder
{
[Flags]
protected enum LinkFlags
{
None = 0,
ExpandPredefinedTypes = 1 << 1,
SplitNamespaceAndType = 1 << 2
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
{
internal abstract partial class AbstractDescriptionBuilder
{
[Flags]
protected enum LinkFlags
{
None = 0,
ExpandPredefinedTypes = 1 << 1,
SplitNamespaceAndType = 1 << 2
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/CSharp/Portable/Symbols/CustomModifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a custom modifier (modopt/modreq).
/// </summary>
internal abstract partial class CSharpCustomModifier : CustomModifier
{
protected readonly NamedTypeSymbol modifier;
private CSharpCustomModifier(NamedTypeSymbol modifier)
{
Debug.Assert((object)modifier != null);
this.modifier = modifier;
}
/// <summary>
/// A type used as a tag that indicates which type of modification applies.
/// </summary>
public override INamedTypeSymbol Modifier
{
get
{
return modifier.GetPublicSymbol();
}
}
public NamedTypeSymbol ModifierSymbol
{
get
{
return modifier;
}
}
public abstract override int GetHashCode();
public abstract override bool Equals(object obj);
internal static CustomModifier CreateOptional(NamedTypeSymbol modifier)
{
return new OptionalCustomModifier(modifier);
}
internal static CustomModifier CreateRequired(NamedTypeSymbol modifier)
{
return new RequiredCustomModifier(modifier);
}
internal static ImmutableArray<CustomModifier> Convert(ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers)
{
if (customModifiers.IsDefault)
{
return ImmutableArray<CustomModifier>.Empty;
}
return customModifiers.SelectAsArray(Convert);
}
private static CustomModifier Convert(ModifierInfo<TypeSymbol> customModifier)
{
var modifier = (NamedTypeSymbol)customModifier.Modifier;
return customModifier.IsOptional ? CreateOptional(modifier) : CreateRequired(modifier);
}
private class OptionalCustomModifier : CSharpCustomModifier
{
public OptionalCustomModifier(NamedTypeSymbol modifier)
: base(modifier)
{ }
public override bool IsOptional
{
get
{
return true;
}
}
public override int GetHashCode()
{
return modifier.GetHashCode();
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
OptionalCustomModifier other = obj as OptionalCustomModifier;
return other != null && other.modifier.Equals(this.modifier);
}
}
private class RequiredCustomModifier : CSharpCustomModifier
{
public RequiredCustomModifier(NamedTypeSymbol modifier)
: base(modifier)
{ }
public override bool IsOptional
{
get
{
return false;
}
}
public override int GetHashCode()
{
return modifier.GetHashCode();
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
RequiredCustomModifier other = obj as RequiredCustomModifier;
return other != null && other.modifier.Equals(this.modifier);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a custom modifier (modopt/modreq).
/// </summary>
internal abstract partial class CSharpCustomModifier : CustomModifier
{
protected readonly NamedTypeSymbol modifier;
private CSharpCustomModifier(NamedTypeSymbol modifier)
{
Debug.Assert((object)modifier != null);
this.modifier = modifier;
}
/// <summary>
/// A type used as a tag that indicates which type of modification applies.
/// </summary>
public override INamedTypeSymbol Modifier
{
get
{
return modifier.GetPublicSymbol();
}
}
public NamedTypeSymbol ModifierSymbol
{
get
{
return modifier;
}
}
public abstract override int GetHashCode();
public abstract override bool Equals(object obj);
internal static CustomModifier CreateOptional(NamedTypeSymbol modifier)
{
return new OptionalCustomModifier(modifier);
}
internal static CustomModifier CreateRequired(NamedTypeSymbol modifier)
{
return new RequiredCustomModifier(modifier);
}
internal static ImmutableArray<CustomModifier> Convert(ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers)
{
if (customModifiers.IsDefault)
{
return ImmutableArray<CustomModifier>.Empty;
}
return customModifiers.SelectAsArray(Convert);
}
private static CustomModifier Convert(ModifierInfo<TypeSymbol> customModifier)
{
var modifier = (NamedTypeSymbol)customModifier.Modifier;
return customModifier.IsOptional ? CreateOptional(modifier) : CreateRequired(modifier);
}
private class OptionalCustomModifier : CSharpCustomModifier
{
public OptionalCustomModifier(NamedTypeSymbol modifier)
: base(modifier)
{ }
public override bool IsOptional
{
get
{
return true;
}
}
public override int GetHashCode()
{
return modifier.GetHashCode();
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
OptionalCustomModifier other = obj as OptionalCustomModifier;
return other != null && other.modifier.Equals(this.modifier);
}
}
private class RequiredCustomModifier : CSharpCustomModifier
{
public RequiredCustomModifier(NamedTypeSymbol modifier)
: base(modifier)
{ }
public override bool IsOptional
{
get
{
return false;
}
}
public override int GetHashCode()
{
return modifier.GetHashCode();
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
RequiredCustomModifier other = obj as RequiredCustomModifier;
return other != null && other.modifier.Equals(this.modifier);
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal abstract partial class CSharpSelectionResult : SelectionResult
{
public static async Task<CSharpSelectionResult> CreateAsync(
OperationStatus status,
TextSpan originalSpan,
TextSpan finalSpan,
OptionSet options,
bool selectionInExpression,
SemanticDocument document,
SyntaxToken firstToken,
SyntaxToken lastToken,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(status);
Contract.ThrowIfNull(document);
var firstTokenAnnotation = new SyntaxAnnotation();
var lastTokenAnnotation = new SyntaxAnnotation();
var root = await document.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newDocument = await SemanticDocument.CreateAsync(document.Document.WithSyntaxRoot(root.AddAnnotations(
new[]
{
Tuple.Create<SyntaxToken, SyntaxAnnotation>(firstToken, firstTokenAnnotation),
Tuple.Create<SyntaxToken, SyntaxAnnotation>(lastToken, lastTokenAnnotation)
})), cancellationToken).ConfigureAwait(false);
if (selectionInExpression)
{
return new ExpressionResult(
status, originalSpan, finalSpan, options, selectionInExpression,
newDocument, firstTokenAnnotation, lastTokenAnnotation);
}
else
{
return new StatementResult(
status, originalSpan, finalSpan, options, selectionInExpression,
newDocument, firstTokenAnnotation, lastTokenAnnotation);
}
}
protected CSharpSelectionResult(
OperationStatus status,
TextSpan originalSpan,
TextSpan finalSpan,
OptionSet options,
bool selectionInExpression,
SemanticDocument document,
SyntaxAnnotation firstTokenAnnotation,
SyntaxAnnotation lastTokenAnnotation)
: base(status, originalSpan, finalSpan, options, selectionInExpression,
document, firstTokenAnnotation, lastTokenAnnotation)
{
}
protected override bool UnderAnonymousOrLocalMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken)
{
var current = token.Parent;
for (; current != null; current = current.Parent)
{
if (current is MemberDeclarationSyntax ||
current is SimpleLambdaExpressionSyntax ||
current is ParenthesizedLambdaExpressionSyntax ||
current is AnonymousMethodExpressionSyntax ||
current is LocalFunctionStatementSyntax)
{
break;
}
}
if (current == null || current is MemberDeclarationSyntax)
{
return false;
}
// make sure the selection contains the lambda
return firstToken.SpanStart <= current.GetFirstToken().SpanStart &&
current.GetLastToken().Span.End <= lastToken.Span.End;
}
public StatementSyntax GetFirstStatement()
=> GetFirstStatement<StatementSyntax>();
public StatementSyntax GetLastStatement()
=> GetLastStatement<StatementSyntax>();
public StatementSyntax GetFirstStatementUnderContainer()
{
Contract.ThrowIfTrue(SelectionInExpression);
var firstToken = GetFirstTokenInSelection();
var statement = firstToken.Parent.GetStatementUnderContainer();
Contract.ThrowIfNull(statement);
return statement;
}
public StatementSyntax GetLastStatementUnderContainer()
{
Contract.ThrowIfTrue(SelectionInExpression);
var lastToken = GetLastTokenInSelection();
var statement = lastToken.Parent.GetStatementUnderContainer();
Contract.ThrowIfNull(statement);
var firstStatementUnderContainer = GetFirstStatementUnderContainer();
Contract.ThrowIfFalse(statement.Parent == firstStatementUnderContainer.Parent);
return statement;
}
public SyntaxNode GetInnermostStatementContainer()
{
Contract.ThrowIfFalse(SelectionInExpression);
var containingScope = GetContainingScope();
var statements = containingScope.GetAncestorsOrThis<StatementSyntax>();
StatementSyntax last = null;
foreach (var statement in statements)
{
if (statement.IsStatementContainerNode())
{
return statement;
}
last = statement;
}
// expression bodied member case
var expressionBodiedMember = GetContainingScopeOf<ArrowExpressionClauseSyntax>();
if (expressionBodiedMember != null)
{
// the class/struct declaration is the innermost statement container, since the
// member does not have a block body
return GetContainingScopeOf<TypeDeclarationSyntax>();
}
// constructor initializer case
var constructorInitializer = GetContainingScopeOf<ConstructorInitializerSyntax>();
if (constructorInitializer != null)
{
return constructorInitializer.Parent;
}
// field initializer case
var field = GetContainingScopeOf<FieldDeclarationSyntax>();
if (field != null)
{
return field.Parent;
}
Contract.ThrowIfFalse(last.IsParentKind(SyntaxKind.GlobalStatement));
Contract.ThrowIfFalse(last.Parent.IsParentKind(SyntaxKind.CompilationUnit));
return last.Parent.Parent;
}
public bool ShouldPutUnsafeModifier()
{
var token = GetFirstTokenInSelection();
var ancestors = token.GetAncestors<SyntaxNode>();
// if enclosing type contains unsafe keyword, we don't need to put it again
if (ancestors.Where(a => SyntaxFacts.IsTypeDeclaration(a.Kind()))
.Cast<MemberDeclarationSyntax>()
.Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)))
{
return false;
}
return token.Parent.IsUnsafeContext();
}
public SyntaxKind UnderCheckedExpressionContext()
=> UnderCheckedContext<CheckedExpressionSyntax>();
public SyntaxKind UnderCheckedStatementContext()
=> UnderCheckedContext<CheckedStatementSyntax>();
private SyntaxKind UnderCheckedContext<T>() where T : SyntaxNode
{
var token = GetFirstTokenInSelection();
var contextNode = token.Parent.GetAncestor<T>();
if (contextNode == null)
{
return SyntaxKind.None;
}
return contextNode.Kind();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal abstract partial class CSharpSelectionResult : SelectionResult
{
public static async Task<CSharpSelectionResult> CreateAsync(
OperationStatus status,
TextSpan originalSpan,
TextSpan finalSpan,
OptionSet options,
bool selectionInExpression,
SemanticDocument document,
SyntaxToken firstToken,
SyntaxToken lastToken,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(status);
Contract.ThrowIfNull(document);
var firstTokenAnnotation = new SyntaxAnnotation();
var lastTokenAnnotation = new SyntaxAnnotation();
var root = await document.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newDocument = await SemanticDocument.CreateAsync(document.Document.WithSyntaxRoot(root.AddAnnotations(
new[]
{
Tuple.Create<SyntaxToken, SyntaxAnnotation>(firstToken, firstTokenAnnotation),
Tuple.Create<SyntaxToken, SyntaxAnnotation>(lastToken, lastTokenAnnotation)
})), cancellationToken).ConfigureAwait(false);
if (selectionInExpression)
{
return new ExpressionResult(
status, originalSpan, finalSpan, options, selectionInExpression,
newDocument, firstTokenAnnotation, lastTokenAnnotation);
}
else
{
return new StatementResult(
status, originalSpan, finalSpan, options, selectionInExpression,
newDocument, firstTokenAnnotation, lastTokenAnnotation);
}
}
protected CSharpSelectionResult(
OperationStatus status,
TextSpan originalSpan,
TextSpan finalSpan,
OptionSet options,
bool selectionInExpression,
SemanticDocument document,
SyntaxAnnotation firstTokenAnnotation,
SyntaxAnnotation lastTokenAnnotation)
: base(status, originalSpan, finalSpan, options, selectionInExpression,
document, firstTokenAnnotation, lastTokenAnnotation)
{
}
protected override bool UnderAnonymousOrLocalMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken)
{
var current = token.Parent;
for (; current != null; current = current.Parent)
{
if (current is MemberDeclarationSyntax ||
current is SimpleLambdaExpressionSyntax ||
current is ParenthesizedLambdaExpressionSyntax ||
current is AnonymousMethodExpressionSyntax ||
current is LocalFunctionStatementSyntax)
{
break;
}
}
if (current == null || current is MemberDeclarationSyntax)
{
return false;
}
// make sure the selection contains the lambda
return firstToken.SpanStart <= current.GetFirstToken().SpanStart &&
current.GetLastToken().Span.End <= lastToken.Span.End;
}
public StatementSyntax GetFirstStatement()
=> GetFirstStatement<StatementSyntax>();
public StatementSyntax GetLastStatement()
=> GetLastStatement<StatementSyntax>();
public StatementSyntax GetFirstStatementUnderContainer()
{
Contract.ThrowIfTrue(SelectionInExpression);
var firstToken = GetFirstTokenInSelection();
var statement = firstToken.Parent.GetStatementUnderContainer();
Contract.ThrowIfNull(statement);
return statement;
}
public StatementSyntax GetLastStatementUnderContainer()
{
Contract.ThrowIfTrue(SelectionInExpression);
var lastToken = GetLastTokenInSelection();
var statement = lastToken.Parent.GetStatementUnderContainer();
Contract.ThrowIfNull(statement);
var firstStatementUnderContainer = GetFirstStatementUnderContainer();
Contract.ThrowIfFalse(statement.Parent == firstStatementUnderContainer.Parent);
return statement;
}
public SyntaxNode GetInnermostStatementContainer()
{
Contract.ThrowIfFalse(SelectionInExpression);
var containingScope = GetContainingScope();
var statements = containingScope.GetAncestorsOrThis<StatementSyntax>();
StatementSyntax last = null;
foreach (var statement in statements)
{
if (statement.IsStatementContainerNode())
{
return statement;
}
last = statement;
}
// expression bodied member case
var expressionBodiedMember = GetContainingScopeOf<ArrowExpressionClauseSyntax>();
if (expressionBodiedMember != null)
{
// the class/struct declaration is the innermost statement container, since the
// member does not have a block body
return GetContainingScopeOf<TypeDeclarationSyntax>();
}
// constructor initializer case
var constructorInitializer = GetContainingScopeOf<ConstructorInitializerSyntax>();
if (constructorInitializer != null)
{
return constructorInitializer.Parent;
}
// field initializer case
var field = GetContainingScopeOf<FieldDeclarationSyntax>();
if (field != null)
{
return field.Parent;
}
Contract.ThrowIfFalse(last.IsParentKind(SyntaxKind.GlobalStatement));
Contract.ThrowIfFalse(last.Parent.IsParentKind(SyntaxKind.CompilationUnit));
return last.Parent.Parent;
}
public bool ShouldPutUnsafeModifier()
{
var token = GetFirstTokenInSelection();
var ancestors = token.GetAncestors<SyntaxNode>();
// if enclosing type contains unsafe keyword, we don't need to put it again
if (ancestors.Where(a => SyntaxFacts.IsTypeDeclaration(a.Kind()))
.Cast<MemberDeclarationSyntax>()
.Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)))
{
return false;
}
return token.Parent.IsUnsafeContext();
}
public SyntaxKind UnderCheckedExpressionContext()
=> UnderCheckedContext<CheckedExpressionSyntax>();
public SyntaxKind UnderCheckedStatementContext()
=> UnderCheckedContext<CheckedStatementSyntax>();
private SyntaxKind UnderCheckedContext<T>() where T : SyntaxNode
{
var token = GetFirstTokenInSelection();
var contextNode = token.Parent.GetAncestor<T>();
if (contextNode == null)
{
return SyntaxKind.None;
}
return contextNode.Kind();
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/Core/Def/Implementation/AbstractOleCommandTarget.Query.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio.OLE.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal abstract partial class AbstractOleCommandTarget
{
public int QueryStatus(ref Guid pguidCmdGroup, uint commandCount, OLECMD[] prgCmds, IntPtr commandText)
{
Contract.ThrowIfFalse(commandCount == 1);
Contract.ThrowIfFalse(prgCmds.Length == 1);
// TODO: We'll need to extend the command handler interfaces at some point when we have commands that
// require enabling/disabling at some point. For now, we just enable the few that we care about.
if (pguidCmdGroup == VSConstants.VsStd14)
{
return QueryVisualStudio2014Status(ref pguidCmdGroup, commandCount, prgCmds, commandText);
}
else
{
return NextCommandTarget.QueryStatus(ref pguidCmdGroup, commandCount, prgCmds, commandText);
}
}
private int QueryVisualStudio2014Status(ref Guid pguidCmdGroup, uint commandCount, OLECMD[] prgCmds, IntPtr commandText)
{
switch ((VSConstants.VSStd14CmdID)prgCmds[0].cmdID)
{
case VSConstants.VSStd14CmdID.SmartBreakLine:
prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE);
return VSConstants.S_OK;
default:
return NextCommandTarget.QueryStatus(ref pguidCmdGroup, commandCount, prgCmds, commandText);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio.OLE.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal abstract partial class AbstractOleCommandTarget
{
public int QueryStatus(ref Guid pguidCmdGroup, uint commandCount, OLECMD[] prgCmds, IntPtr commandText)
{
Contract.ThrowIfFalse(commandCount == 1);
Contract.ThrowIfFalse(prgCmds.Length == 1);
// TODO: We'll need to extend the command handler interfaces at some point when we have commands that
// require enabling/disabling at some point. For now, we just enable the few that we care about.
if (pguidCmdGroup == VSConstants.VsStd14)
{
return QueryVisualStudio2014Status(ref pguidCmdGroup, commandCount, prgCmds, commandText);
}
else
{
return NextCommandTarget.QueryStatus(ref pguidCmdGroup, commandCount, prgCmds, commandText);
}
}
private int QueryVisualStudio2014Status(ref Guid pguidCmdGroup, uint commandCount, OLECMD[] prgCmds, IntPtr commandText)
{
switch ((VSConstants.VSStd14CmdID)prgCmds[0].cmdID)
{
case VSConstants.VSStd14CmdID.SmartBreakLine:
prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE);
return VSConstants.S_OK;
default:
return NextCommandTarget.QueryStatus(ref pguidCmdGroup, commandCount, prgCmds, commandText);
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/Remote/Core/ExternalAccess/UnitTesting/Api/UnitTestingRemoteServiceCallbackDispatcher.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal abstract class UnitTestingRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
private readonly RemoteServiceCallbackDispatcher _dispatcher = new();
public object GetCallback(UnitTestingRemoteServiceCallbackIdWrapper callbackId)
=> _dispatcher.GetCallback(callbackId.UnderlyingObject);
RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance)
=> _dispatcher.CreateHandle(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.
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal abstract class UnitTestingRemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
private readonly RemoteServiceCallbackDispatcher _dispatcher = new();
public object GetCallback(UnitTestingRemoteServiceCallbackIdWrapper callbackId)
=> _dispatcher.GetCallback(callbackId.UnderlyingObject);
RemoteServiceCallbackDispatcher.Handle IRemoteServiceCallbackDispatcher.CreateHandle(object? instance)
=> _dispatcher.CreateHandle(instance);
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/TypeParameterSubstitution.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
{
internal partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
{
private static async ValueTask<ITypeSymbol> ReplaceTypeParametersBasedOnTypeConstraintsAsync(
Project project,
ITypeSymbol type,
Compilation compilation,
ISet<string> availableTypeParameterNames,
CancellationToken cancellationToken)
{
var visitor = new DetermineSubstitutionsVisitor(
compilation, availableTypeParameterNames, project, cancellationToken);
await visitor.Visit(type).ConfigureAwait(false);
return type.SubstituteTypes(visitor.Substitutions, compilation);
}
private sealed class DetermineSubstitutionsVisitor : AsyncSymbolVisitor
{
public readonly Dictionary<ITypeSymbol, ITypeSymbol> Substitutions =
new();
private readonly CancellationToken _cancellationToken;
private readonly Compilation _compilation;
private readonly ISet<string> _availableTypeParameterNames;
private readonly Project _project;
public DetermineSubstitutionsVisitor(
Compilation compilation, ISet<string> availableTypeParameterNames, Project project, CancellationToken cancellationToken)
{
_compilation = compilation;
_availableTypeParameterNames = availableTypeParameterNames;
_project = project;
_cancellationToken = cancellationToken;
}
public override ValueTask VisitDynamicType(IDynamicTypeSymbol symbol)
=> default;
public override ValueTask VisitArrayType(IArrayTypeSymbol symbol)
=> symbol.ElementType.Accept(this);
public override async ValueTask VisitNamedType(INamedTypeSymbol symbol)
{
foreach (var typeArg in symbol.TypeArguments)
await typeArg.Accept(this).ConfigureAwait(false);
}
public override ValueTask VisitPointerType(IPointerTypeSymbol symbol)
=> symbol.PointedAtType.Accept(this);
public override async ValueTask VisitTypeParameter(ITypeParameterSymbol symbol)
{
if (_availableTypeParameterNames.Contains(symbol.Name))
return;
switch (symbol.ConstraintTypes.Length)
{
case 0:
// If there are no constraint then there is no replacement required.
return;
case 1:
// If there is one constraint which is a INamedTypeSymbol then return the INamedTypeSymbol
// because the TypeParameter is expected to be of that type
// else return the original symbol
if (symbol.ConstraintTypes.ElementAt(0) is INamedTypeSymbol namedType)
Substitutions.Add(symbol, namedType);
return;
}
var commonDerivedType = await DetermineCommonDerivedTypeAsync(symbol).ConfigureAwait(false);
if (commonDerivedType != null)
Substitutions.Add(symbol, commonDerivedType);
}
private async ValueTask<ITypeSymbol> DetermineCommonDerivedTypeAsync(ITypeParameterSymbol symbol)
{
if (!symbol.ConstraintTypes.All(t => t is INamedTypeSymbol))
return null;
var solution = _project.Solution;
var projects = solution.Projects.ToImmutableHashSet();
var commonTypes = await GetDerivedAndImplementedTypesAsync(
(INamedTypeSymbol)symbol.ConstraintTypes[0], projects).ConfigureAwait(false);
for (var i = 1; i < symbol.ConstraintTypes.Length; i++)
{
var currentTypes = await GetDerivedAndImplementedTypesAsync(
(INamedTypeSymbol)symbol.ConstraintTypes[i], projects).ConfigureAwait(false);
commonTypes.IntersectWith(currentTypes);
if (commonTypes.Count == 0)
return null;
}
// If there was any intersecting derived type among the constraint types then pick the first of the lot.
if (commonTypes.Count == 0)
return null;
var commonType = commonTypes.First();
// If the resultant intersecting type contains any Type arguments that could be replaced
// using the type constraints then recursively update the type until all constraints are appropriately handled
var substitutedType = await ReplaceTypeParametersBasedOnTypeConstraintsAsync(
_project, commonType, _compilation, _availableTypeParameterNames, _cancellationToken).ConfigureAwait(false);
var similarTypes = SymbolFinder.FindSimilarSymbols(substitutedType, _compilation, _cancellationToken);
if (similarTypes.Any())
return similarTypes.First();
similarTypes = SymbolFinder.FindSimilarSymbols(commonType, _compilation, _cancellationToken);
return similarTypes.FirstOrDefault() ?? symbol;
}
private async Task<ISet<INamedTypeSymbol>> GetDerivedAndImplementedTypesAsync(
INamedTypeSymbol constraintType, IImmutableSet<Project> projects)
{
var solution = _project.Solution;
var symbol = constraintType;
var derivedClasses = await SymbolFinder.FindDerivedClassesAsync(
symbol, solution, transitive: true, projects, _cancellationToken).ConfigureAwait(false);
var implementedTypes = await SymbolFinder.FindImplementationsAsync(
symbol, solution, transitive: true, projects, _cancellationToken).ConfigureAwait(false);
return derivedClasses.Concat(implementedTypes).ToSet();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
{
internal partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>
{
private static async ValueTask<ITypeSymbol> ReplaceTypeParametersBasedOnTypeConstraintsAsync(
Project project,
ITypeSymbol type,
Compilation compilation,
ISet<string> availableTypeParameterNames,
CancellationToken cancellationToken)
{
var visitor = new DetermineSubstitutionsVisitor(
compilation, availableTypeParameterNames, project, cancellationToken);
await visitor.Visit(type).ConfigureAwait(false);
return type.SubstituteTypes(visitor.Substitutions, compilation);
}
private sealed class DetermineSubstitutionsVisitor : AsyncSymbolVisitor
{
public readonly Dictionary<ITypeSymbol, ITypeSymbol> Substitutions =
new();
private readonly CancellationToken _cancellationToken;
private readonly Compilation _compilation;
private readonly ISet<string> _availableTypeParameterNames;
private readonly Project _project;
public DetermineSubstitutionsVisitor(
Compilation compilation, ISet<string> availableTypeParameterNames, Project project, CancellationToken cancellationToken)
{
_compilation = compilation;
_availableTypeParameterNames = availableTypeParameterNames;
_project = project;
_cancellationToken = cancellationToken;
}
public override ValueTask VisitDynamicType(IDynamicTypeSymbol symbol)
=> default;
public override ValueTask VisitArrayType(IArrayTypeSymbol symbol)
=> symbol.ElementType.Accept(this);
public override async ValueTask VisitNamedType(INamedTypeSymbol symbol)
{
foreach (var typeArg in symbol.TypeArguments)
await typeArg.Accept(this).ConfigureAwait(false);
}
public override ValueTask VisitPointerType(IPointerTypeSymbol symbol)
=> symbol.PointedAtType.Accept(this);
public override async ValueTask VisitTypeParameter(ITypeParameterSymbol symbol)
{
if (_availableTypeParameterNames.Contains(symbol.Name))
return;
switch (symbol.ConstraintTypes.Length)
{
case 0:
// If there are no constraint then there is no replacement required.
return;
case 1:
// If there is one constraint which is a INamedTypeSymbol then return the INamedTypeSymbol
// because the TypeParameter is expected to be of that type
// else return the original symbol
if (symbol.ConstraintTypes.ElementAt(0) is INamedTypeSymbol namedType)
Substitutions.Add(symbol, namedType);
return;
}
var commonDerivedType = await DetermineCommonDerivedTypeAsync(symbol).ConfigureAwait(false);
if (commonDerivedType != null)
Substitutions.Add(symbol, commonDerivedType);
}
private async ValueTask<ITypeSymbol> DetermineCommonDerivedTypeAsync(ITypeParameterSymbol symbol)
{
if (!symbol.ConstraintTypes.All(t => t is INamedTypeSymbol))
return null;
var solution = _project.Solution;
var projects = solution.Projects.ToImmutableHashSet();
var commonTypes = await GetDerivedAndImplementedTypesAsync(
(INamedTypeSymbol)symbol.ConstraintTypes[0], projects).ConfigureAwait(false);
for (var i = 1; i < symbol.ConstraintTypes.Length; i++)
{
var currentTypes = await GetDerivedAndImplementedTypesAsync(
(INamedTypeSymbol)symbol.ConstraintTypes[i], projects).ConfigureAwait(false);
commonTypes.IntersectWith(currentTypes);
if (commonTypes.Count == 0)
return null;
}
// If there was any intersecting derived type among the constraint types then pick the first of the lot.
if (commonTypes.Count == 0)
return null;
var commonType = commonTypes.First();
// If the resultant intersecting type contains any Type arguments that could be replaced
// using the type constraints then recursively update the type until all constraints are appropriately handled
var substitutedType = await ReplaceTypeParametersBasedOnTypeConstraintsAsync(
_project, commonType, _compilation, _availableTypeParameterNames, _cancellationToken).ConfigureAwait(false);
var similarTypes = SymbolFinder.FindSimilarSymbols(substitutedType, _compilation, _cancellationToken);
if (similarTypes.Any())
return similarTypes.First();
similarTypes = SymbolFinder.FindSimilarSymbols(commonType, _compilation, _cancellationToken);
return similarTypes.FirstOrDefault() ?? symbol;
}
private async Task<ISet<INamedTypeSymbol>> GetDerivedAndImplementedTypesAsync(
INamedTypeSymbol constraintType, IImmutableSet<Project> projects)
{
var solution = _project.Solution;
var symbol = constraintType;
var derivedClasses = await SymbolFinder.FindDerivedClassesAsync(
symbol, solution, transitive: true, projects, _cancellationToken).ConfigureAwait(false);
var implementedTypes = await SymbolFinder.FindImplementationsAsync(
symbol, solution, transitive: true, projects, _cancellationToken).ConfigureAwait(false);
return derivedClasses.Concat(implementedTypes).ToSet();
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/LanguageServer/Protocol/Handler/Completion/CompletionListCache.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Completion;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Completion
{
/// <summary>
/// Caches completion lists in between calls to CompletionHandler and
/// CompletionResolveHandler. Used to avoid unnecessary recomputation.
/// </summary>
internal class CompletionListCache
{
/// <summary>
/// Maximum number of completion lists allowed in cache. Must be >= 1.
/// </summary>
private const int MaxCacheSize = 3;
/// <summary>
/// Multiple cache requests or updates may be received concurrently.
/// We need this lock to ensure that we aren't making concurrent
/// modifications to _nextResultId or _resultIdToCompletionList.
/// </summary>
private readonly object _accessLock = new object();
#region protected by _accessLock
/// <summary>
/// The next resultId available to use.
/// </summary>
private long _nextResultId;
/// <summary>
/// Keeps track of the resultIds in the cache and their associated
/// completion list.
/// </summary>
private readonly List<CacheEntry> _resultIdToCompletionList = new();
#endregion
/// <summary>
/// Adds a completion list to the cache. If the cache reaches its maximum size, the oldest completion
/// list in the cache is removed.
/// </summary>
/// <returns>
/// The generated resultId associated with the passed in completion list.
/// </returns>
public long UpdateCache(LSP.TextDocumentIdentifier textDocument, CompletionList completionList)
{
lock (_accessLock)
{
// If cache exceeds maximum size, remove the oldest list in the cache
if (_resultIdToCompletionList.Count >= MaxCacheSize)
{
_resultIdToCompletionList.RemoveAt(0);
}
// Getting the generated unique resultId
var resultId = _nextResultId++;
// Add passed in completion list to cache
var cacheEntry = new CacheEntry(resultId, textDocument, completionList);
_resultIdToCompletionList.Add(cacheEntry);
// Return generated resultId so completion list can later be retrieved from cache
return resultId;
}
}
/// <summary>
/// Attempts to return the completion list in the cache associated with the given resultId.
/// Returns null if no match is found.
/// </summary>
public CacheEntry? GetCachedCompletionList(long resultId)
{
lock (_accessLock)
{
foreach (var cacheEntry in _resultIdToCompletionList)
{
if (cacheEntry.ResultId == resultId)
{
// We found a match - return completion list
return cacheEntry;
}
}
// A completion list associated with the given resultId was not found
return null;
}
}
internal TestAccessor GetTestAccessor() => new(this);
internal readonly struct TestAccessor
{
private readonly CompletionListCache _completionListCache;
public static int MaximumCacheSize => MaxCacheSize;
public TestAccessor(CompletionListCache completionListCache)
=> _completionListCache = completionListCache;
public List<CacheEntry> GetCacheContents()
=> _completionListCache._resultIdToCompletionList;
}
public record CacheEntry(long ResultId, LSP.TextDocumentIdentifier TextDocument, CompletionList CompletionList);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Completion;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Completion
{
/// <summary>
/// Caches completion lists in between calls to CompletionHandler and
/// CompletionResolveHandler. Used to avoid unnecessary recomputation.
/// </summary>
internal class CompletionListCache
{
/// <summary>
/// Maximum number of completion lists allowed in cache. Must be >= 1.
/// </summary>
private const int MaxCacheSize = 3;
/// <summary>
/// Multiple cache requests or updates may be received concurrently.
/// We need this lock to ensure that we aren't making concurrent
/// modifications to _nextResultId or _resultIdToCompletionList.
/// </summary>
private readonly object _accessLock = new object();
#region protected by _accessLock
/// <summary>
/// The next resultId available to use.
/// </summary>
private long _nextResultId;
/// <summary>
/// Keeps track of the resultIds in the cache and their associated
/// completion list.
/// </summary>
private readonly List<CacheEntry> _resultIdToCompletionList = new();
#endregion
/// <summary>
/// Adds a completion list to the cache. If the cache reaches its maximum size, the oldest completion
/// list in the cache is removed.
/// </summary>
/// <returns>
/// The generated resultId associated with the passed in completion list.
/// </returns>
public long UpdateCache(LSP.TextDocumentIdentifier textDocument, CompletionList completionList)
{
lock (_accessLock)
{
// If cache exceeds maximum size, remove the oldest list in the cache
if (_resultIdToCompletionList.Count >= MaxCacheSize)
{
_resultIdToCompletionList.RemoveAt(0);
}
// Getting the generated unique resultId
var resultId = _nextResultId++;
// Add passed in completion list to cache
var cacheEntry = new CacheEntry(resultId, textDocument, completionList);
_resultIdToCompletionList.Add(cacheEntry);
// Return generated resultId so completion list can later be retrieved from cache
return resultId;
}
}
/// <summary>
/// Attempts to return the completion list in the cache associated with the given resultId.
/// Returns null if no match is found.
/// </summary>
public CacheEntry? GetCachedCompletionList(long resultId)
{
lock (_accessLock)
{
foreach (var cacheEntry in _resultIdToCompletionList)
{
if (cacheEntry.ResultId == resultId)
{
// We found a match - return completion list
return cacheEntry;
}
}
// A completion list associated with the given resultId was not found
return null;
}
}
internal TestAccessor GetTestAccessor() => new(this);
internal readonly struct TestAccessor
{
private readonly CompletionListCache _completionListCache;
public static int MaximumCacheSize => MaxCacheSize;
public TestAccessor(CompletionListCache completionListCache)
=> _completionListCache = completionListCache;
public List<CacheEntry> GetCacheContents()
=> _completionListCache._resultIdToCompletionList;
}
public record CacheEntry(long ResultId, LSP.TextDocumentIdentifier TextDocument, CompletionList CompletionList);
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/Core/Portable/Compilation/ScriptCompilationInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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
{
public abstract class ScriptCompilationInfo
{
internal Type? ReturnTypeOpt { get; }
public Type ReturnType => ReturnTypeOpt ?? typeof(object);
public Type? GlobalsType { get; }
internal ScriptCompilationInfo(Type? returnType, Type? globalsType)
{
ReturnTypeOpt = returnType;
GlobalsType = globalsType;
}
public Compilation? PreviousScriptCompilation => CommonPreviousScriptCompilation;
internal abstract Compilation? CommonPreviousScriptCompilation { get; }
public ScriptCompilationInfo WithPreviousScriptCompilation(Compilation? compilation) => CommonWithPreviousScriptCompilation(compilation);
internal abstract ScriptCompilationInfo CommonWithPreviousScriptCompilation(Compilation? 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.
using System;
namespace Microsoft.CodeAnalysis
{
public abstract class ScriptCompilationInfo
{
internal Type? ReturnTypeOpt { get; }
public Type ReturnType => ReturnTypeOpt ?? typeof(object);
public Type? GlobalsType { get; }
internal ScriptCompilationInfo(Type? returnType, Type? globalsType)
{
ReturnTypeOpt = returnType;
GlobalsType = globalsType;
}
public Compilation? PreviousScriptCompilation => CommonPreviousScriptCompilation;
internal abstract Compilation? CommonPreviousScriptCompilation { get; }
public ScriptCompilationInfo WithPreviousScriptCompilation(Compilation? compilation) => CommonWithPreviousScriptCompilation(compilation);
internal abstract ScriptCompilationInfo CommonWithPreviousScriptCompilation(Compilation? compilation);
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/Core/MSBuild/MSBuild/VisualBasic/VisualBasicCommandLineArgumentReader.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.MSBuild;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicCommandLineArgumentReader : CommandLineArgumentReader
{
public VisualBasicCommandLineArgumentReader(MSB.Execution.ProjectInstance project)
: base(project)
{
}
public static ImmutableArray<string> Read(MSB.Execution.ProjectInstance project)
{
return new VisualBasicCommandLineArgumentReader(project).Read();
}
protected override void ReadCore()
{
ReadAdditionalFiles();
ReadAnalyzers();
ReadCodePage();
ReadDebugInfo();
ReadDelaySign();
ReadDoc();
ReadErrorReport();
ReadFeatures();
ReadImports();
ReadOptions();
ReadPlatform();
ReadReferences();
ReadSigning();
ReadVbRuntime();
AddIfNotNullOrWhiteSpace("baseaddress", Project.ReadPropertyString(PropertyNames.BaseAddress));
AddIfNotNullOrWhiteSpace("define", Project.ReadPropertyString(PropertyNames.FinalDefineConstants));
AddIfNotNullOrWhiteSpace("filealign", Project.ReadPropertyString(PropertyNames.FileAlignment));
AddIfTrue("highentropyva", Project.ReadPropertyBool(PropertyNames.HighEntropyVA));
AddIfNotNullOrWhiteSpace("langversion", Project.ReadPropertyString(PropertyNames.LangVersion));
AddIfNotNullOrWhiteSpace("main", Project.ReadPropertyString(PropertyNames.StartupObject));
AddIfNotNullOrWhiteSpace("moduleassemblyname", Project.ReadPropertyString(PropertyNames.ModuleAssemblyName));
AddIfTrue("netcf", Project.ReadPropertyBool(PropertyNames.TargetCompactFramework));
AddIfTrue("nostdlib", Project.ReadPropertyBool(PropertyNames.NoCompilerStandardLib));
AddIfNotNullOrWhiteSpace("nowarn", Project.ReadPropertyString(PropertyNames.NoWarn));
AddIfTrue("nowarn", Project.ReadPropertyBool(PropertyNames._NoWarnings));
AddIfTrue("optimize", Project.ReadPropertyBool(PropertyNames.Optimize));
AddIfNotNullOrWhiteSpace("out", Project.ReadItemsAsString(PropertyNames.IntermediateAssembly));
AddIfTrue("removeintchecks", Project.ReadPropertyBool(PropertyNames.RemoveIntegerChecks));
AddIfNotNullOrWhiteSpace("rootnamespace", Project.ReadPropertyString(PropertyNames.RootNamespace));
AddIfNotNullOrWhiteSpace("ruleset", Project.ReadPropertyString(PropertyNames.ResolvedCodeAnalysisRuleSet));
AddIfNotNullOrWhiteSpace("sdkpath", Project.ReadPropertyString(PropertyNames.FrameworkPathOverride));
AddIfNotNullOrWhiteSpace("subsystemversion", Project.ReadPropertyString(PropertyNames.SubsystemVersion));
AddIfNotNullOrWhiteSpace("target", Project.ReadPropertyString(PropertyNames.OutputType));
AddIfTrue("warnaserror", Project.ReadPropertyBool(PropertyNames.TreatWarningsAsErrors));
AddIfNotNullOrWhiteSpace("warnaserror+", Project.ReadPropertyString(PropertyNames.WarningsAsErrors));
AddIfNotNullOrWhiteSpace("warnaserror-", Project.ReadPropertyString(PropertyNames.WarningsNotAsErrors));
}
private void ReadDoc()
{
var documentationFile = Project.ReadPropertyString(PropertyNames.DocFileItem);
var generateDocumentation = Project.ReadPropertyBool(PropertyNames.GenerateDocumentation);
var hasDocumentationFile = !RoslynString.IsNullOrWhiteSpace(documentationFile);
if (hasDocumentationFile || generateDocumentation)
{
if (!RoslynString.IsNullOrWhiteSpace(documentationFile))
{
Add("doc", documentationFile);
}
else
{
Add("doc");
}
}
}
private void ReadOptions()
{
var optionCompare = Project.ReadPropertyString(PropertyNames.OptionCompare);
if (string.Equals("binary", optionCompare, StringComparison.OrdinalIgnoreCase))
{
Add("optioncompare", "binary");
}
else if (string.Equals("text", optionCompare, StringComparison.OrdinalIgnoreCase))
{
Add("optioncompare", "text");
}
// default is on/true
AddIfFalse("optionexplicit-", Project.ReadPropertyBool(PropertyNames.OptionExplicit));
AddIfTrue("optioninfer", Project.ReadPropertyBool(PropertyNames.OptionInfer));
AddWithPlusOrMinus("optionstrict", Project.ReadPropertyBool(PropertyNames.OptionStrict));
AddIfNotNullOrWhiteSpace("optionstrict", Project.ReadPropertyString(PropertyNames.OptionStrictType));
}
private void ReadVbRuntime()
{
var vbRuntime = Project.ReadPropertyString(PropertyNames.VbRuntime);
if (!RoslynString.IsNullOrWhiteSpace(vbRuntime))
{
if (string.Equals("default", vbRuntime, StringComparison.OrdinalIgnoreCase))
{
Add("vbruntime+");
}
else if (string.Equals("embed", vbRuntime, StringComparison.OrdinalIgnoreCase))
{
Add("vbruntime*");
}
else if (string.Equals("none", vbRuntime, StringComparison.OrdinalIgnoreCase))
{
Add("vbruntime-");
}
else
{
Add("vbruntime", vbRuntime);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.MSBuild;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicCommandLineArgumentReader : CommandLineArgumentReader
{
public VisualBasicCommandLineArgumentReader(MSB.Execution.ProjectInstance project)
: base(project)
{
}
public static ImmutableArray<string> Read(MSB.Execution.ProjectInstance project)
{
return new VisualBasicCommandLineArgumentReader(project).Read();
}
protected override void ReadCore()
{
ReadAdditionalFiles();
ReadAnalyzers();
ReadCodePage();
ReadDebugInfo();
ReadDelaySign();
ReadDoc();
ReadErrorReport();
ReadFeatures();
ReadImports();
ReadOptions();
ReadPlatform();
ReadReferences();
ReadSigning();
ReadVbRuntime();
AddIfNotNullOrWhiteSpace("baseaddress", Project.ReadPropertyString(PropertyNames.BaseAddress));
AddIfNotNullOrWhiteSpace("define", Project.ReadPropertyString(PropertyNames.FinalDefineConstants));
AddIfNotNullOrWhiteSpace("filealign", Project.ReadPropertyString(PropertyNames.FileAlignment));
AddIfTrue("highentropyva", Project.ReadPropertyBool(PropertyNames.HighEntropyVA));
AddIfNotNullOrWhiteSpace("langversion", Project.ReadPropertyString(PropertyNames.LangVersion));
AddIfNotNullOrWhiteSpace("main", Project.ReadPropertyString(PropertyNames.StartupObject));
AddIfNotNullOrWhiteSpace("moduleassemblyname", Project.ReadPropertyString(PropertyNames.ModuleAssemblyName));
AddIfTrue("netcf", Project.ReadPropertyBool(PropertyNames.TargetCompactFramework));
AddIfTrue("nostdlib", Project.ReadPropertyBool(PropertyNames.NoCompilerStandardLib));
AddIfNotNullOrWhiteSpace("nowarn", Project.ReadPropertyString(PropertyNames.NoWarn));
AddIfTrue("nowarn", Project.ReadPropertyBool(PropertyNames._NoWarnings));
AddIfTrue("optimize", Project.ReadPropertyBool(PropertyNames.Optimize));
AddIfNotNullOrWhiteSpace("out", Project.ReadItemsAsString(PropertyNames.IntermediateAssembly));
AddIfTrue("removeintchecks", Project.ReadPropertyBool(PropertyNames.RemoveIntegerChecks));
AddIfNotNullOrWhiteSpace("rootnamespace", Project.ReadPropertyString(PropertyNames.RootNamespace));
AddIfNotNullOrWhiteSpace("ruleset", Project.ReadPropertyString(PropertyNames.ResolvedCodeAnalysisRuleSet));
AddIfNotNullOrWhiteSpace("sdkpath", Project.ReadPropertyString(PropertyNames.FrameworkPathOverride));
AddIfNotNullOrWhiteSpace("subsystemversion", Project.ReadPropertyString(PropertyNames.SubsystemVersion));
AddIfNotNullOrWhiteSpace("target", Project.ReadPropertyString(PropertyNames.OutputType));
AddIfTrue("warnaserror", Project.ReadPropertyBool(PropertyNames.TreatWarningsAsErrors));
AddIfNotNullOrWhiteSpace("warnaserror+", Project.ReadPropertyString(PropertyNames.WarningsAsErrors));
AddIfNotNullOrWhiteSpace("warnaserror-", Project.ReadPropertyString(PropertyNames.WarningsNotAsErrors));
}
private void ReadDoc()
{
var documentationFile = Project.ReadPropertyString(PropertyNames.DocFileItem);
var generateDocumentation = Project.ReadPropertyBool(PropertyNames.GenerateDocumentation);
var hasDocumentationFile = !RoslynString.IsNullOrWhiteSpace(documentationFile);
if (hasDocumentationFile || generateDocumentation)
{
if (!RoslynString.IsNullOrWhiteSpace(documentationFile))
{
Add("doc", documentationFile);
}
else
{
Add("doc");
}
}
}
private void ReadOptions()
{
var optionCompare = Project.ReadPropertyString(PropertyNames.OptionCompare);
if (string.Equals("binary", optionCompare, StringComparison.OrdinalIgnoreCase))
{
Add("optioncompare", "binary");
}
else if (string.Equals("text", optionCompare, StringComparison.OrdinalIgnoreCase))
{
Add("optioncompare", "text");
}
// default is on/true
AddIfFalse("optionexplicit-", Project.ReadPropertyBool(PropertyNames.OptionExplicit));
AddIfTrue("optioninfer", Project.ReadPropertyBool(PropertyNames.OptionInfer));
AddWithPlusOrMinus("optionstrict", Project.ReadPropertyBool(PropertyNames.OptionStrict));
AddIfNotNullOrWhiteSpace("optionstrict", Project.ReadPropertyString(PropertyNames.OptionStrictType));
}
private void ReadVbRuntime()
{
var vbRuntime = Project.ReadPropertyString(PropertyNames.VbRuntime);
if (!RoslynString.IsNullOrWhiteSpace(vbRuntime))
{
if (string.Equals("default", vbRuntime, StringComparison.OrdinalIgnoreCase))
{
Add("vbruntime+");
}
else if (string.Equals("embed", vbRuntime, StringComparison.OrdinalIgnoreCase))
{
Add("vbruntime*");
}
else if (string.Equals("none", vbRuntime, StringComparison.OrdinalIgnoreCase))
{
Add("vbruntime-");
}
else
{
Add("vbruntime", vbRuntime);
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/LazyInitialization.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace Roslyn.Utilities
{
internal static class LazyInitialization
{
internal static T InterlockedStore<T>([NotNull] ref T? target, T value) where T : class
=> Interlocked.CompareExchange(ref target, value, null) ?? value;
/// <summary>
/// Ensure that the given target value is initialized (not null) in a thread-safe manner.
/// </summary>
/// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam>
/// <param name="target">The target to initialize.</param>
/// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called
/// more than once by multiple threads, but only one of those values will successfully be written to the target.</param>
/// <returns>The target value.</returns>
public static T EnsureInitialized<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class
=> Volatile.Read(ref target!) ?? InterlockedStore(ref target!, valueFactory());
/// <summary>
/// Ensure that the given target value is initialized (not null) in a thread-safe manner.
/// </summary>
/// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam>
/// <param name="target">The target to initialize.</param>
/// <typeparam name="U">The type of the <paramref name="state"/> argument passed to the value factory.</typeparam>
/// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called
/// more than once by multiple threads, but only one of those values will successfully be written to the target.</param>
/// <param name="state">An argument passed to the value factory.</param>
/// <returns>The target value.</returns>
public static T EnsureInitialized<T, U>([NotNull] ref T? target, Func<U, T> valueFactory, U state)
where T : class
{
return Volatile.Read(ref target!) ?? InterlockedStore(ref target!, valueFactory(state));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace Roslyn.Utilities
{
internal static class LazyInitialization
{
internal static T InterlockedStore<T>([NotNull] ref T? target, T value) where T : class
=> Interlocked.CompareExchange(ref target, value, null) ?? value;
/// <summary>
/// Ensure that the given target value is initialized (not null) in a thread-safe manner.
/// </summary>
/// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam>
/// <param name="target">The target to initialize.</param>
/// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called
/// more than once by multiple threads, but only one of those values will successfully be written to the target.</param>
/// <returns>The target value.</returns>
public static T EnsureInitialized<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class
=> Volatile.Read(ref target!) ?? InterlockedStore(ref target!, valueFactory());
/// <summary>
/// Ensure that the given target value is initialized (not null) in a thread-safe manner.
/// </summary>
/// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam>
/// <param name="target">The target to initialize.</param>
/// <typeparam name="U">The type of the <paramref name="state"/> argument passed to the value factory.</typeparam>
/// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called
/// more than once by multiple threads, but only one of those values will successfully be written to the target.</param>
/// <param name="state">An argument passed to the value factory.</param>
/// <returns>The target value.</returns>
public static T EnsureInitialized<T, U>([NotNull] ref T? target, Func<U, T> valueFactory, U state)
where T : class
{
return Volatile.Read(ref target!) ?? InterlockedStore(ref target!, valueFactory(state));
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.ja.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../CSharpWorkspaceExtensionsResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">別の値が追加されたら、この値を削除します。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../CSharpWorkspaceExtensionsResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">別の値が追加されたら、この値を削除します。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.EnumeratedValueSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class ValueSetFactory
{
/// <summary>
/// A value set that only supports equality and works by including or excluding specific values.
/// This is used for value set of <see cref="System.String"/> because the language defines no
/// relational operators for it; such a set can be formed only by including explicitly mentioned
/// members (or the inverse, excluding them, by complementing the set).
/// </summary>
private sealed class EnumeratedValueSet<T, TTC> : IValueSet<T> where TTC : struct, IEquatableValueTC<T> where T : notnull
{
/// <summary>
/// In <see cref="_included"/>, then members are listed by inclusion. Otherwise all members
/// are assumed to be contained in the set unless excluded.
/// </summary>
private readonly bool _included;
private readonly ImmutableHashSet<T> _membersIncludedOrExcluded;
private EnumeratedValueSet(bool included, ImmutableHashSet<T> membersIncludedOrExcluded) =>
(this._included, this._membersIncludedOrExcluded) = (included, membersIncludedOrExcluded);
public static readonly EnumeratedValueSet<T, TTC> AllValues = new EnumeratedValueSet<T, TTC>(included: false, ImmutableHashSet<T>.Empty);
public static readonly EnumeratedValueSet<T, TTC> NoValues = new EnumeratedValueSet<T, TTC>(included: true, ImmutableHashSet<T>.Empty);
internal static EnumeratedValueSet<T, TTC> Including(T value) => new EnumeratedValueSet<T, TTC>(included: true, ImmutableHashSet<T>.Empty.Add(value));
public bool IsEmpty => _included && _membersIncludedOrExcluded.IsEmpty;
ConstantValue IValueSet.Sample
{
get
{
if (IsEmpty) throw new ArgumentException();
var tc = default(TTC);
if (_included)
return tc.ToConstantValue(_membersIncludedOrExcluded.OrderBy(k => k).First());
if (typeof(T) == typeof(string))
{
// try some simple strings.
if (this.Any(BinaryOperatorKind.Equal, (T)(object)""))
return tc.ToConstantValue((T)(object)"");
for (char c = 'A'; c <= 'z'; c++)
if (this.Any(BinaryOperatorKind.Equal, (T)(object)c.ToString()))
return tc.ToConstantValue((T)(object)c.ToString());
}
// If that doesn't work, choose from a sufficiently large random selection of values.
// Since this is an excluded set, they cannot all be excluded
var candidates = tc.RandomValues(_membersIncludedOrExcluded.Count + 1, new Random(0), _membersIncludedOrExcluded.Count + 1);
foreach (var value in candidates)
{
if (this.Any(BinaryOperatorKind.Equal, value))
return tc.ToConstantValue(value);
}
throw ExceptionUtilities.Unreachable;
}
}
public bool Any(BinaryOperatorKind relation, T value)
{
switch (relation)
{
case BinaryOperatorKind.Equal:
return _included == _membersIncludedOrExcluded.Contains(value);
default:
return true; // supported for error recovery
}
}
bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) => value.IsBad || Any(relation, default(TTC).FromConstantValue(value));
public bool All(BinaryOperatorKind relation, T value)
{
switch (relation)
{
case BinaryOperatorKind.Equal:
if (!_included)
return false;
switch (_membersIncludedOrExcluded.Count)
{
case 0:
return true;
case 1:
return _membersIncludedOrExcluded.Contains(value);
default:
return false;
}
default:
return false; // supported for error recovery
}
}
bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) => !value.IsBad && All(relation, default(TTC).FromConstantValue(value));
public IValueSet<T> Complement() => new EnumeratedValueSet<T, TTC>(!_included, _membersIncludedOrExcluded);
IValueSet IValueSet.Complement() => this.Complement();
public IValueSet<T> Intersect(IValueSet<T> o)
{
if (this == o)
return this;
var other = (EnumeratedValueSet<T, TTC>)o;
var (larger, smaller) = (this._membersIncludedOrExcluded.Count > other._membersIncludedOrExcluded.Count) ? (this, other) : (other, this);
switch (larger._included, smaller._included)
{
case (true, true):
return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Intersect(smaller._membersIncludedOrExcluded));
case (true, false):
return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Except(smaller._membersIncludedOrExcluded));
case (false, false):
return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Union(smaller._membersIncludedOrExcluded));
case (false, true):
return new EnumeratedValueSet<T, TTC>(true, smaller._membersIncludedOrExcluded.Except(larger._membersIncludedOrExcluded));
}
}
IValueSet IValueSet.Intersect(IValueSet other) => Intersect((IValueSet<T>)other);
public IValueSet<T> Union(IValueSet<T> o)
{
if (this == o)
return this;
var other = (EnumeratedValueSet<T, TTC>)o;
var (larger, smaller) = (this._membersIncludedOrExcluded.Count > other._membersIncludedOrExcluded.Count) ? (this, other) : (other, this);
switch (larger._included, smaller._included)
{
case (false, false):
return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Intersect(smaller._membersIncludedOrExcluded));
case (false, true):
return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Except(smaller._membersIncludedOrExcluded));
case (true, true):
return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Union(smaller._membersIncludedOrExcluded));
case (true, false):
return new EnumeratedValueSet<T, TTC>(false, smaller._membersIncludedOrExcluded.Except(larger._membersIncludedOrExcluded));
}
}
IValueSet IValueSet.Union(IValueSet other) => Union((IValueSet<T>)other);
public override bool Equals(object? obj) => obj is EnumeratedValueSet<T, TTC> other &&
this._included == other._included && this._membersIncludedOrExcluded.SetEquals(other._membersIncludedOrExcluded);
public override int GetHashCode() => Hash.Combine(this._included.GetHashCode(), this._membersIncludedOrExcluded.GetHashCode());
public override string ToString() => $"{(this._included ? "" : "~")}{{{string.Join(",", _membersIncludedOrExcluded.Select(o => o.ToString()))}{"}"}";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class ValueSetFactory
{
/// <summary>
/// A value set that only supports equality and works by including or excluding specific values.
/// This is used for value set of <see cref="System.String"/> because the language defines no
/// relational operators for it; such a set can be formed only by including explicitly mentioned
/// members (or the inverse, excluding them, by complementing the set).
/// </summary>
private sealed class EnumeratedValueSet<T, TTC> : IValueSet<T> where TTC : struct, IEquatableValueTC<T> where T : notnull
{
/// <summary>
/// In <see cref="_included"/>, then members are listed by inclusion. Otherwise all members
/// are assumed to be contained in the set unless excluded.
/// </summary>
private readonly bool _included;
private readonly ImmutableHashSet<T> _membersIncludedOrExcluded;
private EnumeratedValueSet(bool included, ImmutableHashSet<T> membersIncludedOrExcluded) =>
(this._included, this._membersIncludedOrExcluded) = (included, membersIncludedOrExcluded);
public static readonly EnumeratedValueSet<T, TTC> AllValues = new EnumeratedValueSet<T, TTC>(included: false, ImmutableHashSet<T>.Empty);
public static readonly EnumeratedValueSet<T, TTC> NoValues = new EnumeratedValueSet<T, TTC>(included: true, ImmutableHashSet<T>.Empty);
internal static EnumeratedValueSet<T, TTC> Including(T value) => new EnumeratedValueSet<T, TTC>(included: true, ImmutableHashSet<T>.Empty.Add(value));
public bool IsEmpty => _included && _membersIncludedOrExcluded.IsEmpty;
ConstantValue IValueSet.Sample
{
get
{
if (IsEmpty) throw new ArgumentException();
var tc = default(TTC);
if (_included)
return tc.ToConstantValue(_membersIncludedOrExcluded.OrderBy(k => k).First());
if (typeof(T) == typeof(string))
{
// try some simple strings.
if (this.Any(BinaryOperatorKind.Equal, (T)(object)""))
return tc.ToConstantValue((T)(object)"");
for (char c = 'A'; c <= 'z'; c++)
if (this.Any(BinaryOperatorKind.Equal, (T)(object)c.ToString()))
return tc.ToConstantValue((T)(object)c.ToString());
}
// If that doesn't work, choose from a sufficiently large random selection of values.
// Since this is an excluded set, they cannot all be excluded
var candidates = tc.RandomValues(_membersIncludedOrExcluded.Count + 1, new Random(0), _membersIncludedOrExcluded.Count + 1);
foreach (var value in candidates)
{
if (this.Any(BinaryOperatorKind.Equal, value))
return tc.ToConstantValue(value);
}
throw ExceptionUtilities.Unreachable;
}
}
public bool Any(BinaryOperatorKind relation, T value)
{
switch (relation)
{
case BinaryOperatorKind.Equal:
return _included == _membersIncludedOrExcluded.Contains(value);
default:
return true; // supported for error recovery
}
}
bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) => value.IsBad || Any(relation, default(TTC).FromConstantValue(value));
public bool All(BinaryOperatorKind relation, T value)
{
switch (relation)
{
case BinaryOperatorKind.Equal:
if (!_included)
return false;
switch (_membersIncludedOrExcluded.Count)
{
case 0:
return true;
case 1:
return _membersIncludedOrExcluded.Contains(value);
default:
return false;
}
default:
return false; // supported for error recovery
}
}
bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) => !value.IsBad && All(relation, default(TTC).FromConstantValue(value));
public IValueSet<T> Complement() => new EnumeratedValueSet<T, TTC>(!_included, _membersIncludedOrExcluded);
IValueSet IValueSet.Complement() => this.Complement();
public IValueSet<T> Intersect(IValueSet<T> o)
{
if (this == o)
return this;
var other = (EnumeratedValueSet<T, TTC>)o;
var (larger, smaller) = (this._membersIncludedOrExcluded.Count > other._membersIncludedOrExcluded.Count) ? (this, other) : (other, this);
switch (larger._included, smaller._included)
{
case (true, true):
return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Intersect(smaller._membersIncludedOrExcluded));
case (true, false):
return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Except(smaller._membersIncludedOrExcluded));
case (false, false):
return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Union(smaller._membersIncludedOrExcluded));
case (false, true):
return new EnumeratedValueSet<T, TTC>(true, smaller._membersIncludedOrExcluded.Except(larger._membersIncludedOrExcluded));
}
}
IValueSet IValueSet.Intersect(IValueSet other) => Intersect((IValueSet<T>)other);
public IValueSet<T> Union(IValueSet<T> o)
{
if (this == o)
return this;
var other = (EnumeratedValueSet<T, TTC>)o;
var (larger, smaller) = (this._membersIncludedOrExcluded.Count > other._membersIncludedOrExcluded.Count) ? (this, other) : (other, this);
switch (larger._included, smaller._included)
{
case (false, false):
return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Intersect(smaller._membersIncludedOrExcluded));
case (false, true):
return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Except(smaller._membersIncludedOrExcluded));
case (true, true):
return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Union(smaller._membersIncludedOrExcluded));
case (true, false):
return new EnumeratedValueSet<T, TTC>(false, smaller._membersIncludedOrExcluded.Except(larger._membersIncludedOrExcluded));
}
}
IValueSet IValueSet.Union(IValueSet other) => Union((IValueSet<T>)other);
public override bool Equals(object? obj) => obj is EnumeratedValueSet<T, TTC> other &&
this._included == other._included && this._membersIncludedOrExcluded.SetEquals(other._membersIncludedOrExcluded);
public override int GetHashCode() => Hash.Combine(this._included.GetHashCode(), this._membersIncludedOrExcluded.GetHashCode());
public override string ToString() => $"{(this._included ? "" : "~")}{{{string.Join(",", _membersIncludedOrExcluded.Select(o => o.ToString()))}{"}"}";
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/IGeneratedCodeRecognitionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GeneratedCodeRecognition
{
internal interface IGeneratedCodeRecognitionService : ILanguageService
{
#if !CODE_STYLE
bool IsGeneratedCode(Document document, CancellationToken cancellationToken);
#endif
Task<bool> IsGeneratedCodeAsync(Document document, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GeneratedCodeRecognition
{
internal interface IGeneratedCodeRecognitionService : ILanguageService
{
#if !CODE_STYLE
bool IsGeneratedCode(Document document, CancellationToken cancellationToken);
#endif
Task<bool> IsGeneratedCodeAsync(Document document, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Analyzers/VisualBasic/Tests/RemoveUnnecessarySuppressions/RemoveUnnecessarySuppressionsTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions.VisualBasicRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer,
Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions.RemoveUnnecessaryAttributeSuppressionsCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnnecessarySuppressions
<Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)>
<WorkItem(44176, "https://github.com/dotnet/roslyn/issues/44176")>
Public Class RemoveUnnecessarySuppressionsTests
<Theory, CombinatorialData>
Public Sub TestStandardProperty([property] As AnalyzerProperty)
VerifyVB.VerifyStandardProperty([property])
End Sub
<Theory>
<InlineData("Scope:=""member""", "Target:=""~F:N.C.F""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~P:N.C.P""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~T:N.C""", "Assembly")>
<InlineData("Scope:=""namespace""", "Target:=""~N:N""", "Assembly")>
<InlineData("Scope:=""namespaceanddescendants""", "Target:=""~N:N""", "Assembly")>
<InlineData(Nothing, Nothing, "Assembly")>
<InlineData("Scope:=""module""", Nothing, "Assembly")>
<InlineData("Scope:=""module""", "Target:=Nothing", "Assembly")>
<InlineData("Scope:=""resource""", "Target:=""""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Module")>
<InlineData("Scope:=""type""", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=""namespace""", "Target:=""~F:N.C.F""", "Assembly")>
<InlineData("Scope:=""Member""", "Target:=""~F:N.C.F""", "Assembly")>
<InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F""", "Assembly")>
Public Async Function ValidSuppressions(scope As String, target As String, attributeTarget As String) As Task
Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty)
Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty)
Dim input = $"
<{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})>
Namespace N
Class C
Public F As Integer
Public ReadOnly Property P As Integer
Public Sub M()
End Sub
End Class
End Namespace
"
Await VerifyVB.VerifyCodeFixAsync(input, input)
End Function
<Theory>
<InlineData("Scope:=""member""", "Target:=""~F:N.C.F2""", "Assembly")>
<InlineData("Scope:=""Member""", "Target:=""~F:N.C.F2""", "Assembly")>
<InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F2""", "Assembly")>
<InlineData("Scope:=""invalid""", "Target:=""~P:N.C.P""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~M:N.C.M(System.Int32)""", "Assembly")>
<InlineData("Scope:=""module""", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=Nothing", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData(Nothing, "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=Nothing", "Assembly")>
<InlineData("Scope:=""member""", Nothing, "Assembly")>
<InlineData("Scope:=""type""", "Target:=""~T:N2.C""", "Assembly")>
<InlineData("Scope:=""namespace""", "Target:=""~N:N.N2""", "Assembly")>
<InlineData("Scope:=""namespaceanddescendants""", "Target:=""""", "Assembly")>
<InlineData(Nothing, "Target:=""""", "Assembly")>
<InlineData(Nothing, "Target:=""~T:N.C""", "Assembly")>
<InlineData("Scope:=""module""", "Target:=""""", "Assembly")>
<InlineData("Scope:=""module""", "Target:=""~T:N.C""", "Assembly")>
Public Async Function InvalidSuppressions(scope As String, target As String, attributeTarget As String) As Task
Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty)
Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty)
Dim input = $"
<[|{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})|]>
Namespace N
Class C
Public F As Integer
Public ReadOnly Property P As Integer
Public Sub M()
End Sub
End Class
End Namespace
"
Dim fixedCode = $"
Namespace N
Class C
Public F As Integer
Public ReadOnly Property P As Integer
Public Sub M()
End Sub
End Class
End Namespace
"
Await VerifyVB.VerifyCodeFixAsync(input, fixedCode)
End Function
<Fact>
Public Async Function ValidAndInvalidSuppressions() As Task
Dim attributePrefix = "Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending"""
Dim validSuppression = $"{attributePrefix}, Scope:=""member"", Target:=""~T:C"")"
Dim invalidSuppression = $"[|{attributePrefix}, Scope:=""member"", Target:="""")|]"
Dim input = $"
<{validSuppression}>
<{invalidSuppression}>
<{validSuppression}, {validSuppression}>
<{invalidSuppression}, {invalidSuppression}>
<{validSuppression}, {invalidSuppression}>
<{invalidSuppression}, {validSuppression}>
<{invalidSuppression}, {validSuppression}, {invalidSuppression}, {validSuppression}>
Class C
End Class
"
Dim fixedCode = $"
<{validSuppression}>
<{validSuppression}, {validSuppression}>
<{validSuppression}>
<{validSuppression}>
<{validSuppression}, {validSuppression}>
Class C
End Class
"
Await VerifyVB.VerifyCodeFixAsync(input, fixedCode)
End Function
<Theory>
<InlineData("")>
<InlineData(", Scope:=""member"", Target:=""~M:C.M()""")>
<InlineData(", Scope:=""invalid"", Target:=""invalid""")>
Public Async Function LocalSuppressions(ByVal scopeAndTarget As String) As Task
Dim input = $"
<System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeAndTarget})>
Class C
Sub M()
End Sub
End Class"
Await VerifyVB.VerifyCodeFixAsync(input, input)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions.VisualBasicRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer,
Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions.RemoveUnnecessaryAttributeSuppressionsCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnnecessarySuppressions
<Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessarySuppressions)>
<WorkItem(44176, "https://github.com/dotnet/roslyn/issues/44176")>
Public Class RemoveUnnecessarySuppressionsTests
<Theory, CombinatorialData>
Public Sub TestStandardProperty([property] As AnalyzerProperty)
VerifyVB.VerifyStandardProperty([property])
End Sub
<Theory>
<InlineData("Scope:=""member""", "Target:=""~F:N.C.F""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~P:N.C.P""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~T:N.C""", "Assembly")>
<InlineData("Scope:=""namespace""", "Target:=""~N:N""", "Assembly")>
<InlineData("Scope:=""namespaceanddescendants""", "Target:=""~N:N""", "Assembly")>
<InlineData(Nothing, Nothing, "Assembly")>
<InlineData("Scope:=""module""", Nothing, "Assembly")>
<InlineData("Scope:=""module""", "Target:=Nothing", "Assembly")>
<InlineData("Scope:=""resource""", "Target:=""""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~M:N.C.M()""", "Module")>
<InlineData("Scope:=""type""", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=""namespace""", "Target:=""~F:N.C.F""", "Assembly")>
<InlineData("Scope:=""Member""", "Target:=""~F:N.C.F""", "Assembly")>
<InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F""", "Assembly")>
Public Async Function ValidSuppressions(scope As String, target As String, attributeTarget As String) As Task
Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty)
Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty)
Dim input = $"
<{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})>
Namespace N
Class C
Public F As Integer
Public ReadOnly Property P As Integer
Public Sub M()
End Sub
End Class
End Namespace
"
Await VerifyVB.VerifyCodeFixAsync(input, input)
End Function
<Theory>
<InlineData("Scope:=""member""", "Target:=""~F:N.C.F2""", "Assembly")>
<InlineData("Scope:=""Member""", "Target:=""~F:N.C.F2""", "Assembly")>
<InlineData("Scope:=""MEMBER""", "Target:=""~F:N.C.F2""", "Assembly")>
<InlineData("Scope:=""invalid""", "Target:=""~P:N.C.P""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=""~M:N.C.M(System.Int32)""", "Assembly")>
<InlineData("Scope:=""module""", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=Nothing", "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData(Nothing, "Target:=""~M:N.C.M()""", "Assembly")>
<InlineData("Scope:=""member""", "Target:=Nothing", "Assembly")>
<InlineData("Scope:=""member""", Nothing, "Assembly")>
<InlineData("Scope:=""type""", "Target:=""~T:N2.C""", "Assembly")>
<InlineData("Scope:=""namespace""", "Target:=""~N:N.N2""", "Assembly")>
<InlineData("Scope:=""namespaceanddescendants""", "Target:=""""", "Assembly")>
<InlineData(Nothing, "Target:=""""", "Assembly")>
<InlineData(Nothing, "Target:=""~T:N.C""", "Assembly")>
<InlineData("Scope:=""module""", "Target:=""""", "Assembly")>
<InlineData("Scope:=""module""", "Target:=""~T:N.C""", "Assembly")>
Public Async Function InvalidSuppressions(scope As String, target As String, attributeTarget As String) As Task
Dim scopeString = If(scope IsNot Nothing, $", {scope}", String.Empty)
Dim targetString = If(target IsNot Nothing, $", {target}", String.Empty)
Dim input = $"
<[|{attributeTarget}: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeString}{targetString})|]>
Namespace N
Class C
Public F As Integer
Public ReadOnly Property P As Integer
Public Sub M()
End Sub
End Class
End Namespace
"
Dim fixedCode = $"
Namespace N
Class C
Public F As Integer
Public ReadOnly Property P As Integer
Public Sub M()
End Sub
End Class
End Namespace
"
Await VerifyVB.VerifyCodeFixAsync(input, fixedCode)
End Function
<Fact>
Public Async Function ValidAndInvalidSuppressions() As Task
Dim attributePrefix = "Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending"""
Dim validSuppression = $"{attributePrefix}, Scope:=""member"", Target:=""~T:C"")"
Dim invalidSuppression = $"[|{attributePrefix}, Scope:=""member"", Target:="""")|]"
Dim input = $"
<{validSuppression}>
<{invalidSuppression}>
<{validSuppression}, {validSuppression}>
<{invalidSuppression}, {invalidSuppression}>
<{validSuppression}, {invalidSuppression}>
<{invalidSuppression}, {validSuppression}>
<{invalidSuppression}, {validSuppression}, {invalidSuppression}, {validSuppression}>
Class C
End Class
"
Dim fixedCode = $"
<{validSuppression}>
<{validSuppression}, {validSuppression}>
<{validSuppression}>
<{validSuppression}>
<{validSuppression}, {validSuppression}>
Class C
End Class
"
Await VerifyVB.VerifyCodeFixAsync(input, fixedCode)
End Function
<Theory>
<InlineData("")>
<InlineData(", Scope:=""member"", Target:=""~M:C.M()""")>
<InlineData(", Scope:=""invalid"", Target:=""invalid""")>
Public Async Function LocalSuppressions(ByVal scopeAndTarget As String) As Task
Dim input = $"
<System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Justification:=""Pending""{scopeAndTarget})>
Class C
Sub M()
End Sub
End Class"
Await VerifyVB.VerifyCodeFixAsync(input, input)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/EditorFeatures/VisualBasicTest/ConflictMarkerResolution/ConflictMarkerResolutionTests.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.ConflictMarkerResolution
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer,
Microsoft.CodeAnalysis.VisualBasic.ConflictMarkerResolution.VisualBasicResolveConflictMarkerCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConflictMarkerResolution
Public Class ConflictMarkerResolutionTests
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestTakeTop1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
{|BC37284:=======|}
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 1,
.CodeActionIndex = 0,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestTakeBottom1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
{|BC37284:=======|}
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 1,
.CodeActionIndex = 1,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestTakeBoth1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
{|BC37284:=======|}
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 1,
.CodeActionIndex = 2,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey
}.RunAsync()
End Function
<WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestFixAll1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
end class
{|BC37284:=======|}
class Program2
end class
{|BC37284:>>>>>>> This is theirs!|}
{|BC37284:<<<<<<< This is mine!|}
class Program3
end class
{|BC37284:=======|}
class Program4
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
end class
class Program3
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 2,
.CodeActionIndex = 0,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey
}.RunAsync()
End Function
<WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestFixAll2() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
end class
{|BC37284:=======|}
class Program2
end class
{|BC37284:>>>>>>> This is theirs!|}
{|BC37284:<<<<<<< This is mine!|}
class Program3
end class
{|BC37284:=======|}
class Program4
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program2
end class
class Program4
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 2,
.CodeActionIndex = 1,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey
}.RunAsync()
End Function
<WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestFixAll3() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
end class
{|BC37284:=======|}
class Program2
end class
{|BC37284:>>>>>>> This is theirs!|}
{|BC37284:<<<<<<< This is mine!|}
class Program3
end class
{|BC37284:=======|}
class Program4
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
end class
class Program2
end class
class Program3
end class
class Program4
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 2,
.CodeActionIndex = 2,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey
}.RunAsync()
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.ConflictMarkerResolution
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer,
Microsoft.CodeAnalysis.VisualBasic.ConflictMarkerResolution.VisualBasicResolveConflictMarkerCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConflictMarkerResolution
Public Class ConflictMarkerResolutionTests
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestTakeTop1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
{|BC37284:=======|}
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 1,
.CodeActionIndex = 0,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestTakeBottom1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
{|BC37284:=======|}
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 1,
.CodeActionIndex = 1,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey
}.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestTakeBoth1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
{|BC37284:=======|}
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
sub Main()
dim p as Program
Console.WriteLine(""My section"")
end sub
end class
class Program2
sub Main2()
dim p as Program2
Console.WriteLine(""Their section"")
end sub
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 1,
.CodeActionIndex = 2,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey
}.RunAsync()
End Function
<WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestFixAll1() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
end class
{|BC37284:=======|}
class Program2
end class
{|BC37284:>>>>>>> This is theirs!|}
{|BC37284:<<<<<<< This is mine!|}
class Program3
end class
{|BC37284:=======|}
class Program4
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
end class
class Program3
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 2,
.CodeActionIndex = 0,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey
}.RunAsync()
End Function
<WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestFixAll2() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
end class
{|BC37284:=======|}
class Program2
end class
{|BC37284:>>>>>>> This is theirs!|}
{|BC37284:<<<<<<< This is mine!|}
class Program3
end class
{|BC37284:=======|}
class Program4
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program2
end class
class Program4
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 2,
.CodeActionIndex = 1,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey
}.RunAsync()
End Function
<WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)>
Public Async Function TestFixAll3() As Task
Dim source =
"
imports System
namespace N
{|BC37284:<<<<<<< This is mine!|}
class Program
end class
{|BC37284:=======|}
class Program2
end class
{|BC37284:>>>>>>> This is theirs!|}
{|BC37284:<<<<<<< This is mine!|}
class Program3
end class
{|BC37284:=======|}
class Program4
end class
{|BC37284:>>>>>>> This is theirs!|}
end namespace"
Dim fixedSource = "
imports System
namespace N
class Program
end class
class Program2
end class
class Program3
end class
class Program4
end class
end namespace"
Await New VerifyVB.Test With
{
.TestCode = source,
.FixedCode = fixedSource,
.NumberOfIncrementalIterations = 2,
.CodeActionIndex = 2,
.CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey
}.RunAsync()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/Core/Portable/RQName/Nodes/RQMember.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQMember : RQNode
{
public readonly RQUnconstructedType ContainingType;
public RQMember(RQUnconstructedType containingType)
=> ContainingType = containingType;
public abstract string MemberName { get; }
protected override void AppendChildren(List<SimpleTreeNode> childList)
=> childList.Add(ContainingType.ToSimpleTree());
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQMember : RQNode
{
public readonly RQUnconstructedType ContainingType;
public RQMember(RQUnconstructedType containingType)
=> ContainingType = containingType;
public abstract string MemberName { get; }
protected override void AppendChildren(List<SimpleTreeNode> childList)
=> childList.Add(ContainingType.ToSimpleTree());
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./eng/common/templates/steps/telemetry-end.yml | parameters:
maxRetries: 5
retryDelay: 10 # in seconds
steps:
- bash: |
if [ "$AGENT_JOBSTATUS" = "Succeeded" ] || [ "$AGENT_JOBSTATUS" = "PartiallySucceeded" ]; then
errorCount=0
else
errorCount=1
fi
warningCount=0
curlStatus=1
retryCount=0
# retry loop to harden against spotty telemetry connections
# we don't retry successes and 4xx client errors
until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]]
do
if [ $retryCount -gt 0 ]; then
echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..."
sleep $RetryDelay
fi
# create a temporary file for curl output
res=`mktemp`
curlResult=`
curl --verbose --output $res --write-out "%{http_code}"\
-H 'Content-Type: application/json' \
-H "X-Helix-Job-Token: $Helix_JobToken" \
-H 'Content-Length: 0' \
-X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$Helix_WorkItemId/finish" \
--data-urlencode "errorCount=$errorCount" \
--data-urlencode "warningCount=$warningCount"`
curlStatus=$?
if [ $curlStatus -eq 0 ]; then
if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then
curlStatus=$curlResult
fi
fi
let retryCount++
done
if [ $curlStatus -ne 0 ]; then
echo "Failed to Send Build Finish information after $retryCount retries"
vstsLogOutput="vso[task.logissue type=error;sourcepath=templates/steps/telemetry-end.yml;code=1;]Failed to Send Build Finish information: $curlStatus"
echo "##$vstsLogOutput"
exit 1
fi
displayName: Send Unix Build End Telemetry
env:
# defined via VSTS variables in start-job.sh
Helix_JobToken: $(Helix_JobToken)
Helix_WorkItemId: $(Helix_WorkItemId)
MaxRetries: ${{ parameters.maxRetries }}
RetryDelay: ${{ parameters.retryDelay }}
condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT'))
- powershell: |
if (($env:Agent_JobStatus -eq 'Succeeded') -or ($env:Agent_JobStatus -eq 'PartiallySucceeded')) {
$ErrorCount = 0
} else {
$ErrorCount = 1
}
$WarningCount = 0
# Basic retry loop to harden against server flakiness
$retryCount = 0
while ($retryCount -lt $env:MaxRetries) {
try {
Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$env:Helix_WorkItemId/finish?errorCount=$ErrorCount&warningCount=$WarningCount" -Method Post -ContentType "application/json" -Body "" `
-Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken }
break
}
catch {
$statusCode = $_.Exception.Response.StatusCode.value__
if ($statusCode -ge 400 -and $statusCode -le 499) {
Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)"
Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message
exit 1
}
Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..."
$retryCount++
sleep $env:RetryDelay
continue
}
}
if ($retryCount -ge $env:MaxRetries) {
Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries."
exit 1
}
displayName: Send Windows Build End Telemetry
env:
# defined via VSTS variables in start-job.ps1
Helix_JobToken: $(Helix_JobToken)
Helix_WorkItemId: $(Helix_WorkItemId)
MaxRetries: ${{ parameters.maxRetries }}
RetryDelay: ${{ parameters.retryDelay }}
condition: and(always(),eq(variables['Agent.Os'], 'Windows_NT'))
| parameters:
maxRetries: 5
retryDelay: 10 # in seconds
steps:
- bash: |
if [ "$AGENT_JOBSTATUS" = "Succeeded" ] || [ "$AGENT_JOBSTATUS" = "PartiallySucceeded" ]; then
errorCount=0
else
errorCount=1
fi
warningCount=0
curlStatus=1
retryCount=0
# retry loop to harden against spotty telemetry connections
# we don't retry successes and 4xx client errors
until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]]
do
if [ $retryCount -gt 0 ]; then
echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..."
sleep $RetryDelay
fi
# create a temporary file for curl output
res=`mktemp`
curlResult=`
curl --verbose --output $res --write-out "%{http_code}"\
-H 'Content-Type: application/json' \
-H "X-Helix-Job-Token: $Helix_JobToken" \
-H 'Content-Length: 0' \
-X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$Helix_WorkItemId/finish" \
--data-urlencode "errorCount=$errorCount" \
--data-urlencode "warningCount=$warningCount"`
curlStatus=$?
if [ $curlStatus -eq 0 ]; then
if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then
curlStatus=$curlResult
fi
fi
let retryCount++
done
if [ $curlStatus -ne 0 ]; then
echo "Failed to Send Build Finish information after $retryCount retries"
vstsLogOutput="vso[task.logissue type=error;sourcepath=templates/steps/telemetry-end.yml;code=1;]Failed to Send Build Finish information: $curlStatus"
echo "##$vstsLogOutput"
exit 1
fi
displayName: Send Unix Build End Telemetry
env:
# defined via VSTS variables in start-job.sh
Helix_JobToken: $(Helix_JobToken)
Helix_WorkItemId: $(Helix_WorkItemId)
MaxRetries: ${{ parameters.maxRetries }}
RetryDelay: ${{ parameters.retryDelay }}
condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT'))
- powershell: |
if (($env:Agent_JobStatus -eq 'Succeeded') -or ($env:Agent_JobStatus -eq 'PartiallySucceeded')) {
$ErrorCount = 0
} else {
$ErrorCount = 1
}
$WarningCount = 0
# Basic retry loop to harden against server flakiness
$retryCount = 0
while ($retryCount -lt $env:MaxRetries) {
try {
Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$env:Helix_WorkItemId/finish?errorCount=$ErrorCount&warningCount=$WarningCount" -Method Post -ContentType "application/json" -Body "" `
-Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken }
break
}
catch {
$statusCode = $_.Exception.Response.StatusCode.value__
if ($statusCode -ge 400 -and $statusCode -le 499) {
Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)"
Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message
exit 1
}
Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..."
$retryCount++
sleep $env:RetryDelay
continue
}
}
if ($retryCount -ge $env:MaxRetries) {
Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries."
exit 1
}
displayName: Send Windows Build End Telemetry
env:
# defined via VSTS variables in start-job.ps1
Helix_JobToken: $(Helix_JobToken)
Helix_WorkItemId: $(Helix_WorkItemId)
MaxRetries: ${{ parameters.maxRetries }}
RetryDelay: ${{ parameters.retryDelay }}
condition: and(always(),eq(variables['Agent.Os'], 'Windows_NT'))
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/LiveShare/Impl/ProjectsHandler.Exports.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare
{
[ExportLspRequestHandler(LiveShareConstants.RoslynContractName, RoslynMethods.ProjectsName)]
[Obsolete("Used for backwards compatibility with old liveshare clients.")]
internal class RoslynProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RoslynProjectsHandler()
{
}
}
[ExportLspRequestHandler(LiveShareConstants.CSharpContractName, RoslynMethods.ProjectsName)]
internal class CSharpProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpProjectsHandler()
{
}
}
[ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, RoslynMethods.ProjectsName)]
internal class VisualBasicProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualBasicProjectsHandler()
{
}
}
[ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, RoslynMethods.ProjectsName)]
internal class TypeScriptProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TypeScriptProjectsHandler()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare
{
[ExportLspRequestHandler(LiveShareConstants.RoslynContractName, RoslynMethods.ProjectsName)]
[Obsolete("Used for backwards compatibility with old liveshare clients.")]
internal class RoslynProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RoslynProjectsHandler()
{
}
}
[ExportLspRequestHandler(LiveShareConstants.CSharpContractName, RoslynMethods.ProjectsName)]
internal class CSharpProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpProjectsHandler()
{
}
}
[ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, RoslynMethods.ProjectsName)]
internal class VisualBasicProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualBasicProjectsHandler()
{
}
}
[ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, RoslynMethods.ProjectsName)]
internal class TypeScriptProjectsHandler : ProjectsHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TypeScriptProjectsHandler()
{
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Naming;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class DocumentExtensions
{
public static bool ShouldHideAdvancedMembers(this Document document)
{
// Since we don't actually have a way to configure this per-document, we can fetch from the solution
return document.Project.Solution.Options.GetOption(CompletionOptions.HideAdvancedMembers, document.Project.Language);
}
public static async Task<Document> ReplaceNodeAsync<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNodeSynchronously<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNode<TNode>(this Document document, SyntaxNode root, TNode oldNode, TNode newNode)
where TNode : SyntaxNode
{
Debug.Assert(document.GetRequiredSyntaxRootSynchronously(CancellationToken.None) == root);
var newRoot = root.ReplaceNode(oldNode, newNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<Document> ReplaceNodesAsync(this Document document,
IEnumerable<SyntaxNode> nodes,
Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNodes(nodes, computeReplacementNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<ImmutableArray<T>> GetUnionItemsFromDocumentAndLinkedDocumentsAsync<T>(
this Document document,
IEqualityComparer<T> comparer,
Func<Document, Task<ImmutableArray<T>>> getItemsWorker)
{
var totalItems = new HashSet<T>(comparer);
var values = await getItemsWorker(document).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
values = await getItemsWorker(document.Project.Solution.GetRequiredDocument(linkedDocumentId)).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
}
return totalItems.ToImmutableArray();
}
public static async Task<bool> IsValidContextForDocumentOrLinkedDocumentsAsync(
this Document document,
Func<Document, CancellationToken, Task<bool>> contextChecker,
CancellationToken cancellationToken)
{
if (await contextChecker(document, cancellationToken).ConfigureAwait(false))
{
return true;
}
var solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
if (await contextChecker(linkedDocument, cancellationToken).ConfigureAwait(false))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets the set of naming rules the user has set for this document. Will include a set of default naming rules
/// that match if the user hasn't specified any for a particular symbol type. The are added at the end so they
/// will only be used if the user hasn't specified a preference.
/// </summary>
public static Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(
this Document document, CancellationToken cancellationToken)
=> document.GetNamingRulesAsync(FallbackNamingRules.Default, cancellationToken);
/// <summary>
/// Get the user-specified naming rules, with the added <paramref name="defaultRules"/>.
/// </summary>
public static async Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(this Document document,
ImmutableArray<NamingRule> defaultRules, CancellationToken cancellationToken)
{
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var namingStyleOptions = options.GetOption(NamingStyleOptions.NamingPreferences);
var rules = namingStyleOptions.CreateRules().NamingRules;
return defaultRules.IsDefaultOrEmpty ? rules : rules.AddRange(defaultRules);
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(this Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbol))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKind symbolKind, Accessibility accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbolKind, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(kind, modifiers, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static ImmutableArray<AbstractFormattingRule> GetFormattingRules(this Document document, TextSpan span, IEnumerable<AbstractFormattingRule>? additionalRules)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
// Not sure why this is being done... there aren't any docs on CreateRule either.
var position = (span.Start + span.End) / 2;
var rules = ImmutableArray.Create(formattingRuleFactory.CreateRule(document, position));
if (additionalRules != null)
{
rules = rules.AddRange(additionalRules);
}
return rules.AddRange(Formatter.GetDefaultFormattingRules(document));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Naming;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class DocumentExtensions
{
public static bool ShouldHideAdvancedMembers(this Document document)
{
// Since we don't actually have a way to configure this per-document, we can fetch from the solution
return document.Project.Solution.Options.GetOption(CompletionOptions.HideAdvancedMembers, document.Project.Language);
}
public static async Task<Document> ReplaceNodeAsync<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNodeSynchronously<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNode<TNode>(this Document document, SyntaxNode root, TNode oldNode, TNode newNode)
where TNode : SyntaxNode
{
Debug.Assert(document.GetRequiredSyntaxRootSynchronously(CancellationToken.None) == root);
var newRoot = root.ReplaceNode(oldNode, newNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<Document> ReplaceNodesAsync(this Document document,
IEnumerable<SyntaxNode> nodes,
Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNodes(nodes, computeReplacementNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<ImmutableArray<T>> GetUnionItemsFromDocumentAndLinkedDocumentsAsync<T>(
this Document document,
IEqualityComparer<T> comparer,
Func<Document, Task<ImmutableArray<T>>> getItemsWorker)
{
var totalItems = new HashSet<T>(comparer);
var values = await getItemsWorker(document).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
values = await getItemsWorker(document.Project.Solution.GetRequiredDocument(linkedDocumentId)).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
}
return totalItems.ToImmutableArray();
}
public static async Task<bool> IsValidContextForDocumentOrLinkedDocumentsAsync(
this Document document,
Func<Document, CancellationToken, Task<bool>> contextChecker,
CancellationToken cancellationToken)
{
if (await contextChecker(document, cancellationToken).ConfigureAwait(false))
{
return true;
}
var solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
if (await contextChecker(linkedDocument, cancellationToken).ConfigureAwait(false))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets the set of naming rules the user has set for this document. Will include a set of default naming rules
/// that match if the user hasn't specified any for a particular symbol type. The are added at the end so they
/// will only be used if the user hasn't specified a preference.
/// </summary>
public static Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(
this Document document, CancellationToken cancellationToken)
=> document.GetNamingRulesAsync(FallbackNamingRules.Default, cancellationToken);
/// <summary>
/// Get the user-specified naming rules, with the added <paramref name="defaultRules"/>.
/// </summary>
public static async Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(this Document document,
ImmutableArray<NamingRule> defaultRules, CancellationToken cancellationToken)
{
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var namingStyleOptions = options.GetOption(NamingStyleOptions.NamingPreferences);
var rules = namingStyleOptions.CreateRules().NamingRules;
return defaultRules.IsDefaultOrEmpty ? rules : rules.AddRange(defaultRules);
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(this Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbol))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKind symbolKind, Accessibility accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbolKind, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(kind, modifiers, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static ImmutableArray<AbstractFormattingRule> GetFormattingRules(this Document document, TextSpan span, IEnumerable<AbstractFormattingRule>? additionalRules)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
// Not sure why this is being done... there aren't any docs on CreateRule either.
var position = (span.Start + span.End) / 2;
var rules = ImmutableArray.Create(formattingRuleFactory.CreateRule(document, position));
if (additionalRules != null)
{
rules = rules.AddRange(additionalRules);
}
return rules.AddRange(Formatter.GetDefaultFormattingRules(document));
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
{
[Export(typeof(IViewTaggerProvider))]
[TagType(typeof(KeywordHighlightTag))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider<KeywordHighlightTag>
{
private readonly IHighlightingService _highlightingService;
private static readonly PooledObjects.ObjectPool<List<TextSpan>> s_listPool = new(() => new List<TextSpan>());
// Whenever an edit happens, clear all highlights. When moving the caret, preserve
// highlights if the caret stays within an existing tag.
protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag;
protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags;
protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting);
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public HighlighterViewTaggerProvider(
IThreadingContext threadingContext,
IHighlightingService highlightingService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, listenerProvider.GetListener(FeatureAttribute.KeywordHighlighting))
{
_highlightingService = highlightingService;
}
protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate;
protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer)
{
return TaggerEventSources.Compose(
TaggerEventSources.OnTextChanged(subjectBuffer),
TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer),
TaggerEventSources.OnParseOptionChanged(subjectBuffer));
}
protected override async Task ProduceTagsAsync(TaggerContext<KeywordHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition)
{
var cancellationToken = context.CancellationToken;
var document = documentSnapshotSpan.Document;
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988
// It turns out a document might be associated with a project of wrong language, e.g. C# document in a Xaml project.
// Even though we couldn't repro the crash above, a fix is made in one of possibly multiple code paths that could cause
// us to end up in this situation.
// Regardless of the effective of the fix, we want to enhance the guard against such scenario here until an audit in
// workspace is completed to eliminate the root cause.
if (document?.SupportsSyntaxTree != true)
{
return;
}
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
if (!documentOptions.GetOption(FeatureOnOffOptions.KeywordHighlighting))
{
return;
}
if (!caretPosition.HasValue)
{
return;
}
var snapshotSpan = documentSnapshotSpan.SnapshotSpan;
var position = caretPosition.Value;
var snapshot = snapshotSpan.Snapshot;
// See if the user is just moving their caret around in an existing tag. If so, we don't
// want to actually go recompute things. Note: this only works for containment. If the
// user moves their caret to the end of a highlighted reference, we do want to recompute
// as they may now be at the start of some other reference that should be highlighted instead.
var existingTags = context.GetExistingContainingTags(new SnapshotPoint(snapshot, position));
if (!existingTags.IsEmpty())
{
context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>());
return;
}
using (Logger.LogBlock(FunctionId.Tagger_Highlighter_TagProducer_ProduceTags, cancellationToken))
using (s_listPool.GetPooledObject(out var highlights))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
_highlightingService.AddHighlights(root, position, highlights, cancellationToken);
foreach (var span in highlights)
{
context.AddTag(new TagSpan<KeywordHighlightTag>(span.ToSnapshotSpan(snapshot), KeywordHighlightTag.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.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
{
[Export(typeof(IViewTaggerProvider))]
[TagType(typeof(KeywordHighlightTag))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider<KeywordHighlightTag>
{
private readonly IHighlightingService _highlightingService;
private static readonly PooledObjects.ObjectPool<List<TextSpan>> s_listPool = new(() => new List<TextSpan>());
// Whenever an edit happens, clear all highlights. When moving the caret, preserve
// highlights if the caret stays within an existing tag.
protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag;
protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags;
protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting);
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public HighlighterViewTaggerProvider(
IThreadingContext threadingContext,
IHighlightingService highlightingService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, listenerProvider.GetListener(FeatureAttribute.KeywordHighlighting))
{
_highlightingService = highlightingService;
}
protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate;
protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer)
{
return TaggerEventSources.Compose(
TaggerEventSources.OnTextChanged(subjectBuffer),
TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer),
TaggerEventSources.OnParseOptionChanged(subjectBuffer));
}
protected override async Task ProduceTagsAsync(TaggerContext<KeywordHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition)
{
var cancellationToken = context.CancellationToken;
var document = documentSnapshotSpan.Document;
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988
// It turns out a document might be associated with a project of wrong language, e.g. C# document in a Xaml project.
// Even though we couldn't repro the crash above, a fix is made in one of possibly multiple code paths that could cause
// us to end up in this situation.
// Regardless of the effective of the fix, we want to enhance the guard against such scenario here until an audit in
// workspace is completed to eliminate the root cause.
if (document?.SupportsSyntaxTree != true)
{
return;
}
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
if (!documentOptions.GetOption(FeatureOnOffOptions.KeywordHighlighting))
{
return;
}
if (!caretPosition.HasValue)
{
return;
}
var snapshotSpan = documentSnapshotSpan.SnapshotSpan;
var position = caretPosition.Value;
var snapshot = snapshotSpan.Snapshot;
// See if the user is just moving their caret around in an existing tag. If so, we don't
// want to actually go recompute things. Note: this only works for containment. If the
// user moves their caret to the end of a highlighted reference, we do want to recompute
// as they may now be at the start of some other reference that should be highlighted instead.
var existingTags = context.GetExistingContainingTags(new SnapshotPoint(snapshot, position));
if (!existingTags.IsEmpty())
{
context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>());
return;
}
using (Logger.LogBlock(FunctionId.Tagger_Highlighter_TagProducer_ProduceTags, cancellationToken))
using (s_listPool.GetPooledObject(out var highlights))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
_highlightingService.AddHighlights(root, position, highlights, cancellationToken);
foreach (var span in highlights)
{
context.AddTag(new TagSpan<KeywordHighlightTag>(span.ToSnapshotSpan(snapshot), KeywordHighlightTag.Instance));
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/VisualBasic/Portable/Symbols/Attributes/WellKnownAttributeData/ParameterEarlyWellKnownAttributeData.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.Symbols
''' <summary>
''' Information decoded from early well-known custom attributes applied on a parameter.
''' </summary>
Friend NotInheritable Class ParameterEarlyWellKnownAttributeData
Inherits CommonParameterEarlyWellKnownAttributeData
#Region "MarshalAsAttribute"
' only used for parameters of Declare methods
Private _hasMarshalAsAttribute As Boolean
Friend Property HasMarshalAsAttribute As Boolean
Get
VerifySealed(expected:=True)
Return Me._hasMarshalAsAttribute
End Get
Set(value As Boolean)
VerifySealed(expected:=False)
Me._hasMarshalAsAttribute = value
SetDataStored()
End Set
End Property
#End Region
#Region "ParamArrayAttribute"
' only used for parameters
Private _hasParamArrayAttribute As Boolean
Friend Property HasParamArrayAttribute As Boolean
Get
VerifySealed(expected:=True)
Return Me._hasParamArrayAttribute
End Get
Set(value As Boolean)
VerifySealed(expected:=False)
Me._hasParamArrayAttribute = 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.
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Information decoded from early well-known custom attributes applied on a parameter.
''' </summary>
Friend NotInheritable Class ParameterEarlyWellKnownAttributeData
Inherits CommonParameterEarlyWellKnownAttributeData
#Region "MarshalAsAttribute"
' only used for parameters of Declare methods
Private _hasMarshalAsAttribute As Boolean
Friend Property HasMarshalAsAttribute As Boolean
Get
VerifySealed(expected:=True)
Return Me._hasMarshalAsAttribute
End Get
Set(value As Boolean)
VerifySealed(expected:=False)
Me._hasMarshalAsAttribute = value
SetDataStored()
End Set
End Property
#End Region
#Region "ParamArrayAttribute"
' only used for parameters
Private _hasParamArrayAttribute As Boolean
Friend Property HasParamArrayAttribute As Boolean
Get
VerifySealed(expected:=True)
Return Me._hasParamArrayAttribute
End Get
Set(value As Boolean)
VerifySealed(expected:=False)
Me._hasParamArrayAttribute = value
SetDataStored()
End Set
End Property
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/CodeLens/xlf/CodeLensVSResources.tr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CodeLensVSResources.resx">
<body>
<trans-unit id="CSharp_VisualBasic_References">
<source>C# and Visual Basic References</source>
<target state="translated">C# ve Visual Basic Başvuruları</target>
<note />
</trans-unit>
<trans-unit id="This_0_has_1_references">
<source>This {0} has {1} reference(s).</source>
<target state="translated">Bu {0}, {1} Başvuru içeriyor.</target>
<note />
</trans-unit>
<trans-unit id="_0_reference">
<source>{0} reference</source>
<target state="translated">{0} başvuru</target>
<note />
</trans-unit>
<trans-unit id="_0_references">
<source>{0} references</source>
<target state="translated">{0} başvuru</target>
<note />
</trans-unit>
<trans-unit id="method">
<source>method</source>
<target state="translated">yöntem</target>
<note />
</trans-unit>
<trans-unit id="property">
<source>property</source>
<target state="translated">özellik</target>
<note />
</trans-unit>
<trans-unit id="type">
<source>type</source>
<target state="translated">tür</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CodeLensVSResources.resx">
<body>
<trans-unit id="CSharp_VisualBasic_References">
<source>C# and Visual Basic References</source>
<target state="translated">C# ve Visual Basic Başvuruları</target>
<note />
</trans-unit>
<trans-unit id="This_0_has_1_references">
<source>This {0} has {1} reference(s).</source>
<target state="translated">Bu {0}, {1} Başvuru içeriyor.</target>
<note />
</trans-unit>
<trans-unit id="_0_reference">
<source>{0} reference</source>
<target state="translated">{0} başvuru</target>
<note />
</trans-unit>
<trans-unit id="_0_references">
<source>{0} references</source>
<target state="translated">{0} başvuru</target>
<note />
</trans-unit>
<trans-unit id="method">
<source>method</source>
<target state="translated">yöntem</target>
<note />
</trans-unit>
<trans-unit id="property">
<source>property</source>
<target state="translated">özellik</target>
<note />
</trans-unit>
<trans-unit id="type">
<source>type</source>
<target state="translated">tür</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ru" original="../Commands.vsct">
<body>
<trans-unit id="ECMD_RUNFXCOPSEL|ButtonText">
<source>Run Code &Analysis on Selection</source>
<target state="translated">Выполнить &анализ кода в выделенном фрагменте</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText">
<source>&Current Document</source>
<target state="new">&Current Document</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName">
<source>AnalysisScopeCurrentDocument</source>
<target state="new">AnalysisScopeCurrentDocument</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName">
<source>Current Document</source>
<target state="new">Current Document</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeDefault|ButtonText">
<source>&Default</source>
<target state="new">&Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeDefault|CommandName">
<source>AnalysisScopeDefault</source>
<target state="new">AnalysisScopeDefault</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName">
<source>Default</source>
<target state="new">Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText">
<source>&Entire Solution</source>
<target state="new">&Entire Solution</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName">
<source>AnalysisScopeEntireSolution</source>
<target state="new">AnalysisScopeEntireSolution</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName">
<source>Entire Solution</source>
<target state="new">Entire Solution</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText">
<source>&Open Documents</source>
<target state="new">&Open Documents</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName">
<source>AnalysisScopeOpenDocuments</source>
<target state="new">AnalysisScopeOpenDocuments</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName">
<source>Open Documents</source>
<target state="new">Open Documents</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText">
<source>Set Analysis Scope</source>
<target state="new">Set Analysis Scope</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeSubMenu|CommandName">
<source>Set Analysis Scope</source>
<target state="new">Set Analysis Scope</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName">
<source>SetAnalysisScope</source>
<target state="new">SetAnalysisScope</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText">
<source>Sort &Usings</source>
<target state="translated">Сортировать д&ирективы using</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName">
<source>SortUsings</source>
<target state="translated">SortUsings</target>
<note />
</trans-unit>
<trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText">
<source>Remove &and Sort</source>
<target state="translated">Удалить &и упорядочить</target>
<note />
</trans-unit>
<trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName">
<source>RemoveAndSort</source>
<target state="translated">RemoveAndSort</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText">
<source>Remove &and Sort</source>
<target state="translated">Удалить &и упорядочить</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName">
<source>RemoveAndSort</source>
<target state="translated">RemoveAndSort</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText">
<source>&Default</source>
<target state="new">&Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityDefault|CommandName">
<source>ErrorListSetSeverityDefault</source>
<target state="new">ErrorListSetSeverityDefault</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName">
<source>Default</source>
<target state="new">Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityError|ButtonText">
<source>&Error</source>
<target state="new">&Error</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityError|CommandName">
<source>ErrorListSetSeverityError</source>
<target state="new">ErrorListSetSeverityError</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName">
<source>Error</source>
<target state="new">Error</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText">
<source>&Silent</source>
<target state="new">&Silent</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityHidden|CommandName">
<source>ErrorListSetSeverityHidden</source>
<target state="new">ErrorListSetSeverityHidden</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName">
<source>Silent</source>
<target state="new">Silent</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText">
<source>&Suggestion</source>
<target state="new">&Suggestion</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityInfo|CommandName">
<source>ErrorListSetSeverityInfo</source>
<target state="new">ErrorListSetSeverityInfo</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName">
<source>Suggestion</source>
<target state="new">Suggestion</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityNone|ButtonText">
<source>&None</source>
<target state="new">&None</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityNone|CommandName">
<source>ErrorListSetSeverityNone</source>
<target state="new">ErrorListSetSeverityNone</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName">
<source>None</source>
<target state="new">None</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText">
<source>Set severity</source>
<target state="new">Set severity</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName">
<source>Set severity</source>
<target state="new">Set severity</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName">
<source>Set severity</source>
<target state="new">Set severity</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText">
<source>&Warning</source>
<target state="new">&Warning</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityWarning|CommandName">
<source>ErrorListSetSeverityWarning</source>
<target state="new">ErrorListSetSeverityWarning</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName">
<source>Warning</source>
<target state="new">Warning</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText">
<source>&Analyzer...</source>
<target state="translated">&Анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectAddAnalyzer|ButtonText">
<source>Add &Analyzer...</source>
<target state="translated">Добавить &анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText">
<source>Add &Analyzer...</source>
<target state="translated">Добавить &анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddAnalyzer|ButtonText">
<source>Add &Analyzer...</source>
<target state="translated">Добавить &анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveAnalyzer|ButtonText">
<source>&Remove</source>
<target state="translated">&Удалить</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName">
<source>RemoveAnalyzer</source>
<target state="translated">RemoveAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveAnalyzer|CommandName">
<source>RemoveAnalyzer</source>
<target state="translated">RemoveAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenRuleSet|ButtonText">
<source>&Open Active Rule Set</source>
<target state="translated">&Открыть активный набор правил</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenRuleSet|LocCanonicalName">
<source>OpenActiveRuleSet</source>
<target state="translated">OpenActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenRuleSet|CommandName">
<source>OpenActiveRuleSet</source>
<target state="translated">OpenActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveUnusedReferences|ButtonText">
<source>Remove Unused References...</source>
<target state="translated">&Удалить неиспользуемые ссылки…</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveUnusedReferences|CommandName">
<source>RemoveUnusedReferences</source>
<target state="translated">RemoveUnusedReferences</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName">
<source>RemoveUnusedReferences</source>
<target state="translated">RemoveUnusedReferences</target>
<note />
</trans-unit>
<trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText">
<source>Run C&ode Analysis</source>
<target state="translated">&Запустить анализ кода</target>
<note />
</trans-unit>
<trans-unit id="cmdidRunCodeAnalysisForProject|CommandName">
<source>RunCodeAnalysisForProject</source>
<target state="translated">RunCodeAnalysisForProject</target>
<note />
</trans-unit>
<trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName">
<source>RunCodeAnalysisForProject</source>
<target state="translated">RunCodeAnalysisForProject</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityDefault|ButtonText">
<source>&Default</source>
<target state="translated">&По умолчанию</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityDefault|LocCanonicalName">
<source>Default</source>
<target state="translated">По умолчанию</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityDefault|CommandName">
<source>SetSeverityDefault</source>
<target state="translated">SetSeverityDefault</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityError|ButtonText">
<source>&Error</source>
<target state="translated">&Ошибка</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityError|LocCanonicalName">
<source>Error</source>
<target state="translated">Ошибка</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityError|CommandName">
<source>SetSeverityError</source>
<target state="translated">SetSeverityError</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityWarning|ButtonText">
<source>&Warning</source>
<target state="translated">&Предупреждение</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityWarning|LocCanonicalName">
<source>Warning</source>
<target state="translated">Предупреждение</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityWarning|CommandName">
<source>SetSeverityWarning</source>
<target state="translated">SetSeverityWarning</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityInfo|ButtonText">
<source>&Suggestion</source>
<target state="translated">Рекоменд&ация</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityInfo|LocCanonicalName">
<source>Suggestion</source>
<target state="translated">Рекомендация</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityInfo|CommandName">
<source>SetSeverityInfo</source>
<target state="translated">SetSeverityInfo</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityHidden|ButtonText">
<source>&Silent</source>
<target state="translated">&Автоматически</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityHidden|LocCanonicalName">
<source>Silent</source>
<target state="translated">Автоматически</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityHidden|CommandName">
<source>SetSeverityHidden</source>
<target state="translated">SetSeverityHidden</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityNone|ButtonText">
<source>&None</source>
<target state="translated">&Нет</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityNone|LocCanonicalName">
<source>None</source>
<target state="translated">NONE</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityNone|CommandName">
<source>SetSeverityNone</source>
<target state="translated">SetSeverityNone</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText">
<source>&View Help...</source>
<target state="translated">&Перейти в справку...</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName">
<source>ViewHelp</source>
<target state="translated">ViewHelp</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName">
<source>ViewHelp</source>
<target state="translated">ViewHelp</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetActiveRuleSet|ButtonText">
<source>&Set as Active Rule Set</source>
<target state="translated">&Установить как активный набор правил</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName">
<source>SetAsActiveRuleSet</source>
<target state="translated">SetAsActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetActiveRuleSet|CommandName">
<source>SetAsActiveRuleSet</source>
<target state="translated">SetAsActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveSuppressions|ButtonText">
<source>Remove& Suppression(s)</source>
<target state="translated">Удалит&ь подавления</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveSuppressions|LocCanonicalName">
<source>RemoveSuppressions</source>
<target state="translated">RemoveSuppressions</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveSuppressions|CommandName">
<source>RemoveSuppressions</source>
<target state="translated">RemoveSuppressions</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSource|ButtonText">
<source>In &Source</source>
<target state="translated">В &источнике</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName">
<source>AddSuppressionsInSource</source>
<target state="translated">AddSuppressionsInSource</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSource|CommandName">
<source>AddSuppressionsInSource</source>
<target state="translated">AddSuppressionsInSource</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText">
<source>In& Suppression File</source>
<target state="translated">В файле &блокируемых предупреждений</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName">
<source>AddSuppressionsInSuppressionFile</source>
<target state="translated">AddSuppressionsInSuppressionFile</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName">
<source>AddSuppressionsInSuppressionFile</source>
<target state="translated">AddSuppressionsInSuppressionFile</target>
<note />
</trans-unit>
<trans-unit id="cmdidGoToImplementation|ButtonText">
<source>Go To Implementation</source>
<target state="translated">Перейти к реализации</target>
<note />
</trans-unit>
<trans-unit id="cmdidGoToImplementation|LocCanonicalName">
<source>GoToImplementation</source>
<target state="translated">GoToImplementation</target>
<note />
</trans-unit>
<trans-unit id="cmdidGoToImplementation|CommandName">
<source>Go To Implementation</source>
<target state="translated">Перейти к реализации</target>
<note />
</trans-unit>
<trans-unit id="cmdidSyncNamespaces|ButtonText">
<source>Sync &Namespaces</source>
<target state="new">Sync &Namespaces</target>
<note />
</trans-unit>
<trans-unit id="cmdidSyncNamespaces|CommandName">
<source>SyncNamespaces</source>
<target state="new">SyncNamespaces</target>
<note />
</trans-unit>
<trans-unit id="cmdidSyncNamespaces|LocCanonicalName">
<source>SyncNamespaces</source>
<target state="new">SyncNamespaces</target>
<note />
</trans-unit>
<trans-unit id="cmdidshowValueTracking|ButtonText">
<source>Track Value Source</source>
<target state="new">Track Value Source</target>
<note />
</trans-unit>
<trans-unit id="cmdidshowValueTracking|CommandName">
<source>ShowValueTrackingCommandName</source>
<target state="new">ShowValueTrackingCommandName</target>
<note />
</trans-unit>
<trans-unit id="cmdidshowValueTracking|LocCanonicalName">
<source>ViewEditorConfigSettings</source>
<target state="new">ViewEditorConfigSettings</target>
<note />
</trans-unit>
<trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText">
<source>Initialize Interactive with Project</source>
<target state="translated">Инициализировать интерактивное окно с проектом</target>
<note />
</trans-unit>
<trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName">
<source>ResetC#InteractiveFromProject</source>
<target state="translated">ResetC#InteractiveFromProject</target>
<note />
</trans-unit>
<trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText">
<source>Reset Visual Basic Interactive from Project</source>
<target state="translated">Сбросить интерактивное окно Visual Basic из проекта</target>
<note />
</trans-unit>
<trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName">
<source>ResetVisualBasicInteractiveFromProject</source>
<target state="translated">ResetVisualBasicInteractiveFromProject</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerContextMenu|ButtonText">
<source>Analyzer</source>
<target state="translated">Анализатор</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName">
<source>Analyzer</source>
<target state="translated">Анализатор</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText">
<source>Analyzers</source>
<target state="translated">Анализаторы</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName">
<source>Analyzers</source>
<target state="translated">Анализаторы</target>
<note />
</trans-unit>
<trans-unit id="cmdidDiagnosticContextMenu|ButtonText">
<source>Diagnostic</source>
<target state="translated">Диагностика</target>
<note />
</trans-unit>
<trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName">
<source>Diagnostic</source>
<target state="translated">Диагностика</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeveritySubMenu|ButtonText">
<source>Set severity</source>
<target state="translated">Задать серьезность</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeveritySubMenu|CommandName">
<source>Set severity</source>
<target state="translated">Задать серьезность</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName">
<source>Set severity</source>
<target state="translated">Задать серьезность</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText">
<source>S&uppress</source>
<target state="translated">&Подавить</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName">
<source>S&uppress</source>
<target state="translated">&Подавить</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsContextMenu|CommandName">
<source>S&uppress</source>
<target state="translated">&Подавить</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ru" original="../Commands.vsct">
<body>
<trans-unit id="ECMD_RUNFXCOPSEL|ButtonText">
<source>Run Code &Analysis on Selection</source>
<target state="translated">Выполнить &анализ кода в выделенном фрагменте</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText">
<source>&Current Document</source>
<target state="new">&Current Document</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName">
<source>AnalysisScopeCurrentDocument</source>
<target state="new">AnalysisScopeCurrentDocument</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName">
<source>Current Document</source>
<target state="new">Current Document</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeDefault|ButtonText">
<source>&Default</source>
<target state="new">&Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeDefault|CommandName">
<source>AnalysisScopeDefault</source>
<target state="new">AnalysisScopeDefault</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName">
<source>Default</source>
<target state="new">Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText">
<source>&Entire Solution</source>
<target state="new">&Entire Solution</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName">
<source>AnalysisScopeEntireSolution</source>
<target state="new">AnalysisScopeEntireSolution</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName">
<source>Entire Solution</source>
<target state="new">Entire Solution</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText">
<source>&Open Documents</source>
<target state="new">&Open Documents</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName">
<source>AnalysisScopeOpenDocuments</source>
<target state="new">AnalysisScopeOpenDocuments</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName">
<source>Open Documents</source>
<target state="new">Open Documents</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText">
<source>Set Analysis Scope</source>
<target state="new">Set Analysis Scope</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeSubMenu|CommandName">
<source>Set Analysis Scope</source>
<target state="new">Set Analysis Scope</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName">
<source>SetAnalysisScope</source>
<target state="new">SetAnalysisScope</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText">
<source>Sort &Usings</source>
<target state="translated">Сортировать д&ирективы using</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName">
<source>SortUsings</source>
<target state="translated">SortUsings</target>
<note />
</trans-unit>
<trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText">
<source>Remove &and Sort</source>
<target state="translated">Удалить &и упорядочить</target>
<note />
</trans-unit>
<trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName">
<source>RemoveAndSort</source>
<target state="translated">RemoveAndSort</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText">
<source>Remove &and Sort</source>
<target state="translated">Удалить &и упорядочить</target>
<note />
</trans-unit>
<trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName">
<source>RemoveAndSort</source>
<target state="translated">RemoveAndSort</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText">
<source>&Default</source>
<target state="new">&Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityDefault|CommandName">
<source>ErrorListSetSeverityDefault</source>
<target state="new">ErrorListSetSeverityDefault</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName">
<source>Default</source>
<target state="new">Default</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityError|ButtonText">
<source>&Error</source>
<target state="new">&Error</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityError|CommandName">
<source>ErrorListSetSeverityError</source>
<target state="new">ErrorListSetSeverityError</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName">
<source>Error</source>
<target state="new">Error</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText">
<source>&Silent</source>
<target state="new">&Silent</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityHidden|CommandName">
<source>ErrorListSetSeverityHidden</source>
<target state="new">ErrorListSetSeverityHidden</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName">
<source>Silent</source>
<target state="new">Silent</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText">
<source>&Suggestion</source>
<target state="new">&Suggestion</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityInfo|CommandName">
<source>ErrorListSetSeverityInfo</source>
<target state="new">ErrorListSetSeverityInfo</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName">
<source>Suggestion</source>
<target state="new">Suggestion</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityNone|ButtonText">
<source>&None</source>
<target state="new">&None</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityNone|CommandName">
<source>ErrorListSetSeverityNone</source>
<target state="new">ErrorListSetSeverityNone</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName">
<source>None</source>
<target state="new">None</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText">
<source>Set severity</source>
<target state="new">Set severity</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName">
<source>Set severity</source>
<target state="new">Set severity</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName">
<source>Set severity</source>
<target state="new">Set severity</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText">
<source>&Warning</source>
<target state="new">&Warning</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityWarning|CommandName">
<source>ErrorListSetSeverityWarning</source>
<target state="new">ErrorListSetSeverityWarning</target>
<note />
</trans-unit>
<trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName">
<source>Warning</source>
<target state="new">Warning</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText">
<source>&Analyzer...</source>
<target state="translated">&Анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectAddAnalyzer|ButtonText">
<source>Add &Analyzer...</source>
<target state="translated">Добавить &анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText">
<source>Add &Analyzer...</source>
<target state="translated">Добавить &анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddAnalyzer|ButtonText">
<source>Add &Analyzer...</source>
<target state="translated">Добавить &анализатор...</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddAnalyzer|LocCanonicalName">
<source>AddAnalyzer</source>
<target state="translated">AddAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveAnalyzer|ButtonText">
<source>&Remove</source>
<target state="translated">&Удалить</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName">
<source>RemoveAnalyzer</source>
<target state="translated">RemoveAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveAnalyzer|CommandName">
<source>RemoveAnalyzer</source>
<target state="translated">RemoveAnalyzer</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenRuleSet|ButtonText">
<source>&Open Active Rule Set</source>
<target state="translated">&Открыть активный набор правил</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenRuleSet|LocCanonicalName">
<source>OpenActiveRuleSet</source>
<target state="translated">OpenActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenRuleSet|CommandName">
<source>OpenActiveRuleSet</source>
<target state="translated">OpenActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveUnusedReferences|ButtonText">
<source>Remove Unused References...</source>
<target state="translated">&Удалить неиспользуемые ссылки…</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveUnusedReferences|CommandName">
<source>RemoveUnusedReferences</source>
<target state="translated">RemoveUnusedReferences</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName">
<source>RemoveUnusedReferences</source>
<target state="translated">RemoveUnusedReferences</target>
<note />
</trans-unit>
<trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText">
<source>Run C&ode Analysis</source>
<target state="translated">&Запустить анализ кода</target>
<note />
</trans-unit>
<trans-unit id="cmdidRunCodeAnalysisForProject|CommandName">
<source>RunCodeAnalysisForProject</source>
<target state="translated">RunCodeAnalysisForProject</target>
<note />
</trans-unit>
<trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName">
<source>RunCodeAnalysisForProject</source>
<target state="translated">RunCodeAnalysisForProject</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityDefault|ButtonText">
<source>&Default</source>
<target state="translated">&По умолчанию</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityDefault|LocCanonicalName">
<source>Default</source>
<target state="translated">По умолчанию</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityDefault|CommandName">
<source>SetSeverityDefault</source>
<target state="translated">SetSeverityDefault</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityError|ButtonText">
<source>&Error</source>
<target state="translated">&Ошибка</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityError|LocCanonicalName">
<source>Error</source>
<target state="translated">Ошибка</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityError|CommandName">
<source>SetSeverityError</source>
<target state="translated">SetSeverityError</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityWarning|ButtonText">
<source>&Warning</source>
<target state="translated">&Предупреждение</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityWarning|LocCanonicalName">
<source>Warning</source>
<target state="translated">Предупреждение</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityWarning|CommandName">
<source>SetSeverityWarning</source>
<target state="translated">SetSeverityWarning</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityInfo|ButtonText">
<source>&Suggestion</source>
<target state="translated">Рекоменд&ация</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityInfo|LocCanonicalName">
<source>Suggestion</source>
<target state="translated">Рекомендация</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityInfo|CommandName">
<source>SetSeverityInfo</source>
<target state="translated">SetSeverityInfo</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityHidden|ButtonText">
<source>&Silent</source>
<target state="translated">&Автоматически</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityHidden|LocCanonicalName">
<source>Silent</source>
<target state="translated">Автоматически</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityHidden|CommandName">
<source>SetSeverityHidden</source>
<target state="translated">SetSeverityHidden</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityNone|ButtonText">
<source>&None</source>
<target state="translated">&Нет</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityNone|LocCanonicalName">
<source>None</source>
<target state="translated">NONE</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeverityNone|CommandName">
<source>SetSeverityNone</source>
<target state="translated">SetSeverityNone</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText">
<source>&View Help...</source>
<target state="translated">&Перейти в справку...</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName">
<source>ViewHelp</source>
<target state="translated">ViewHelp</target>
<note />
</trans-unit>
<trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName">
<source>ViewHelp</source>
<target state="translated">ViewHelp</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetActiveRuleSet|ButtonText">
<source>&Set as Active Rule Set</source>
<target state="translated">&Установить как активный набор правил</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName">
<source>SetAsActiveRuleSet</source>
<target state="translated">SetAsActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetActiveRuleSet|CommandName">
<source>SetAsActiveRuleSet</source>
<target state="translated">SetAsActiveRuleSet</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveSuppressions|ButtonText">
<source>Remove& Suppression(s)</source>
<target state="translated">Удалит&ь подавления</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveSuppressions|LocCanonicalName">
<source>RemoveSuppressions</source>
<target state="translated">RemoveSuppressions</target>
<note />
</trans-unit>
<trans-unit id="cmdidRemoveSuppressions|CommandName">
<source>RemoveSuppressions</source>
<target state="translated">RemoveSuppressions</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSource|ButtonText">
<source>In &Source</source>
<target state="translated">В &источнике</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName">
<source>AddSuppressionsInSource</source>
<target state="translated">AddSuppressionsInSource</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSource|CommandName">
<source>AddSuppressionsInSource</source>
<target state="translated">AddSuppressionsInSource</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText">
<source>In& Suppression File</source>
<target state="translated">В файле &блокируемых предупреждений</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName">
<source>AddSuppressionsInSuppressionFile</source>
<target state="translated">AddSuppressionsInSuppressionFile</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName">
<source>AddSuppressionsInSuppressionFile</source>
<target state="translated">AddSuppressionsInSuppressionFile</target>
<note />
</trans-unit>
<trans-unit id="cmdidGoToImplementation|ButtonText">
<source>Go To Implementation</source>
<target state="translated">Перейти к реализации</target>
<note />
</trans-unit>
<trans-unit id="cmdidGoToImplementation|LocCanonicalName">
<source>GoToImplementation</source>
<target state="translated">GoToImplementation</target>
<note />
</trans-unit>
<trans-unit id="cmdidGoToImplementation|CommandName">
<source>Go To Implementation</source>
<target state="translated">Перейти к реализации</target>
<note />
</trans-unit>
<trans-unit id="cmdidSyncNamespaces|ButtonText">
<source>Sync &Namespaces</source>
<target state="new">Sync &Namespaces</target>
<note />
</trans-unit>
<trans-unit id="cmdidSyncNamespaces|CommandName">
<source>SyncNamespaces</source>
<target state="new">SyncNamespaces</target>
<note />
</trans-unit>
<trans-unit id="cmdidSyncNamespaces|LocCanonicalName">
<source>SyncNamespaces</source>
<target state="new">SyncNamespaces</target>
<note />
</trans-unit>
<trans-unit id="cmdidshowValueTracking|ButtonText">
<source>Track Value Source</source>
<target state="new">Track Value Source</target>
<note />
</trans-unit>
<trans-unit id="cmdidshowValueTracking|CommandName">
<source>ShowValueTrackingCommandName</source>
<target state="new">ShowValueTrackingCommandName</target>
<note />
</trans-unit>
<trans-unit id="cmdidshowValueTracking|LocCanonicalName">
<source>ViewEditorConfigSettings</source>
<target state="new">ViewEditorConfigSettings</target>
<note />
</trans-unit>
<trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText">
<source>Initialize Interactive with Project</source>
<target state="translated">Инициализировать интерактивное окно с проектом</target>
<note />
</trans-unit>
<trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName">
<source>ResetC#InteractiveFromProject</source>
<target state="translated">ResetC#InteractiveFromProject</target>
<note />
</trans-unit>
<trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText">
<source>Reset Visual Basic Interactive from Project</source>
<target state="translated">Сбросить интерактивное окно Visual Basic из проекта</target>
<note />
</trans-unit>
<trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName">
<source>ResetVisualBasicInteractiveFromProject</source>
<target state="translated">ResetVisualBasicInteractiveFromProject</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerContextMenu|ButtonText">
<source>Analyzer</source>
<target state="translated">Анализатор</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName">
<source>Analyzer</source>
<target state="translated">Анализатор</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText">
<source>Analyzers</source>
<target state="translated">Анализаторы</target>
<note />
</trans-unit>
<trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName">
<source>Analyzers</source>
<target state="translated">Анализаторы</target>
<note />
</trans-unit>
<trans-unit id="cmdidDiagnosticContextMenu|ButtonText">
<source>Diagnostic</source>
<target state="translated">Диагностика</target>
<note />
</trans-unit>
<trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName">
<source>Diagnostic</source>
<target state="translated">Диагностика</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeveritySubMenu|ButtonText">
<source>Set severity</source>
<target state="translated">Задать серьезность</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeveritySubMenu|CommandName">
<source>Set severity</source>
<target state="translated">Задать серьезность</target>
<note />
</trans-unit>
<trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName">
<source>Set severity</source>
<target state="translated">Задать серьезность</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText">
<source>S&uppress</source>
<target state="translated">&Подавить</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName">
<source>S&uppress</source>
<target state="translated">&Подавить</target>
<note />
</trans-unit>
<trans-unit id="cmdidAddSuppressionsContextMenu|CommandName">
<source>S&uppress</source>
<target state="translated">&Подавить</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/SetKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class SetKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public SetKeywordRecommender()
: base(SyntaxKind.SetKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, SyntaxKind.SetKeyword) ||
context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, SyntaxKind.SetKeyword);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class SetKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public SetKeywordRecommender()
: base(SyntaxKind.SetKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, SyntaxKind.SetKeyword) ||
context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, SyntaxKind.SetKeyword);
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/EditorFeatures/Core/Shared/Tagging/Tags/ConflictTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 ConflictTag : TextMarkerTag
{
public const string TagId = "RoslynConflictTag";
public static readonly ConflictTag Instance = new();
private ConflictTag()
: 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 ConflictTag : TextMarkerTag
{
public const string TagId = "RoslynConflictTag";
public static readonly ConflictTag Instance = new();
private ConflictTag()
: base(TagId)
{
}
}
}
| -1 |
dotnet/roslyn | 56,153 | Use SpillSequences when appropriate instead of Sequences | Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | 333fred | "2021-09-03T00:32:48Z" | "2021-09-14T23:49:39Z" | 7bc2467b978ba0d6df8576e241c9ed13e05a6c08 | d4315a175368888f7d6baf4804d1ae9b57fcb68d | Use SpillSequences when appropriate instead of Sequences. Fixes https://github.com/dotnet/roslyn/issues/54704. This means that, instead of expressions that need to `&& true` in the case of builders with void returns but a bool constructor parameter, we now generate `if (builderConstructorSuccess) { appendCalls }`. As part of this, I simplified the code around how the sequence/spillsequence is actually generated to reduce unnecessary sequence nesting, but that had no affect on the final codegen.
Commit 2 is a quick fix for part of https://github.com/dotnet/roslyn/issues/56044. | ./src/Compilers/CSharp/Portable/Parser/SyntaxParser.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
internal abstract partial class SyntaxParser : IDisposable
{
protected readonly Lexer lexer;
private readonly bool _isIncremental;
private readonly bool _allowModeReset;
protected readonly CancellationToken cancellationToken;
private LexerMode _mode;
private Blender _firstBlender;
private BlendedNode _currentNode;
private SyntaxToken _currentToken;
private ArrayElement<SyntaxToken>[] _lexedTokens;
private GreenNode _prevTokenTrailingTrivia;
private int _firstToken; // The position of _lexedTokens[0] (or _blendedTokens[0]).
private int _tokenOffset; // The index of the current token within _lexedTokens or _blendedTokens.
private int _tokenCount;
private int _resetCount;
private int _resetStart;
private static readonly ObjectPool<BlendedNode[]> s_blendedNodesPool = new ObjectPool<BlendedNode[]>(() => new BlendedNode[32], 2);
private BlendedNode[] _blendedTokens;
protected SyntaxParser(
Lexer lexer,
LexerMode mode,
CSharp.CSharpSyntaxNode oldTree,
IEnumerable<TextChangeRange> changes,
bool allowModeReset,
bool preLexIfNotIncremental = false,
CancellationToken cancellationToken = default(CancellationToken))
{
this.lexer = lexer;
_mode = mode;
_allowModeReset = allowModeReset;
this.cancellationToken = cancellationToken;
_currentNode = default(BlendedNode);
_isIncremental = oldTree != null;
if (this.IsIncremental || allowModeReset)
{
_firstBlender = new Blender(lexer, oldTree, changes);
_blendedTokens = s_blendedNodesPool.Allocate();
}
else
{
_firstBlender = default(Blender);
_lexedTokens = new ArrayElement<SyntaxToken>[32];
}
// PreLex is not cancellable.
// If we may cancel why would we aggressively lex ahead?
// Cancellations in a constructor make disposing complicated
//
// So, if we have a real cancellation token, do not do prelexing.
if (preLexIfNotIncremental && !this.IsIncremental && !cancellationToken.CanBeCanceled)
{
this.PreLex();
}
}
public void Dispose()
{
var blendedTokens = _blendedTokens;
if (blendedTokens != null)
{
_blendedTokens = null;
if (blendedTokens.Length < 4096)
{
Array.Clear(blendedTokens, 0, blendedTokens.Length);
s_blendedNodesPool.Free(blendedTokens);
}
else
{
s_blendedNodesPool.ForgetTrackedObject(blendedTokens);
}
}
}
protected void ReInitialize()
{
_firstToken = 0;
_tokenOffset = 0;
_tokenCount = 0;
_resetCount = 0;
_resetStart = 0;
_currentToken = null;
_prevTokenTrailingTrivia = null;
if (this.IsIncremental || _allowModeReset)
{
_firstBlender = new Blender(this.lexer, null, null);
}
}
protected bool IsIncremental
{
get
{
return _isIncremental;
}
}
private void PreLex()
{
// NOTE: Do not cancel in this method. It is called from the constructor.
var size = Math.Min(4096, Math.Max(32, this.lexer.TextWindow.Text.Length / 2));
_lexedTokens = new ArrayElement<SyntaxToken>[size];
var lexer = this.lexer;
var mode = _mode;
for (int i = 0; i < size; i++)
{
var token = lexer.Lex(mode);
this.AddLexedToken(token);
if (token.Kind == SyntaxKind.EndOfFileToken)
{
break;
}
}
}
protected ResetPoint GetResetPoint()
{
var pos = CurrentTokenPosition;
if (_resetCount == 0)
{
_resetStart = pos; // low water mark
}
_resetCount++;
return new ResetPoint(_resetCount, _mode, pos, _prevTokenTrailingTrivia);
}
protected void Reset(ref ResetPoint point)
{
var offset = point.Position - _firstToken;
Debug.Assert(offset >= 0);
if (offset >= _tokenCount)
{
// Re-fetch tokens to the position in the reset point
PeekToken(offset - _tokenOffset);
// Re-calculate new offset in case tokens got shifted to the left while we were peeking.
offset = point.Position - _firstToken;
}
_mode = point.Mode;
Debug.Assert(offset >= 0 && offset < _tokenCount);
_tokenOffset = offset;
_currentToken = null;
_currentNode = default(BlendedNode);
_prevTokenTrailingTrivia = point.PrevTokenTrailingTrivia;
if (_blendedTokens != null)
{
// look forward for slots not holding a token
for (int i = _tokenOffset; i < _tokenCount; i++)
{
if (_blendedTokens[i].Token == null)
{
// forget anything after and including any slot not holding a token
_tokenCount = i;
if (_tokenCount == _tokenOffset)
{
FetchCurrentToken();
}
break;
}
}
}
}
protected void Release(ref ResetPoint point)
{
Debug.Assert(_resetCount == point.ResetCount);
_resetCount--;
if (_resetCount == 0)
{
_resetStart = -1;
}
}
public CSharpParseOptions Options
{
get { return this.lexer.Options; }
}
public bool IsScript
{
get { return Options.Kind == SourceCodeKind.Script; }
}
protected LexerMode Mode
{
get
{
return _mode;
}
set
{
if (_mode != value)
{
Debug.Assert(_allowModeReset);
_mode = value;
_currentToken = null;
_currentNode = default(BlendedNode);
_tokenCount = _tokenOffset;
}
}
}
protected CSharp.CSharpSyntaxNode CurrentNode
{
get
{
// we will fail anyways. Assert is just to catch that earlier.
Debug.Assert(_blendedTokens != null);
//PERF: currentNode is a BlendedNode, which is a fairly large struct.
// the following code tries not to pull the whole struct into a local
// we only need .Node
var node = _currentNode.Node;
if (node != null)
{
return node;
}
this.ReadCurrentNode();
return _currentNode.Node;
}
}
protected SyntaxKind CurrentNodeKind
{
get
{
var cn = this.CurrentNode;
return cn != null ? cn.Kind() : SyntaxKind.None;
}
}
private void ReadCurrentNode()
{
if (_tokenOffset == 0)
{
_currentNode = _firstBlender.ReadNode(_mode);
}
else
{
_currentNode = _blendedTokens[_tokenOffset - 1].Blender.ReadNode(_mode);
}
}
protected GreenNode EatNode()
{
// we will fail anyways. Assert is just to catch that earlier.
Debug.Assert(_blendedTokens != null);
// remember result
var result = CurrentNode.Green;
// store possible non-token in token sequence
if (_tokenOffset >= _blendedTokens.Length)
{
this.AddTokenSlot();
}
_blendedTokens[_tokenOffset++] = _currentNode;
_tokenCount = _tokenOffset; // forget anything after this slot
// erase current state
_currentNode = default(BlendedNode);
_currentToken = null;
return result;
}
protected SyntaxToken CurrentToken
{
get
{
return _currentToken ?? (_currentToken = this.FetchCurrentToken());
}
}
private SyntaxToken FetchCurrentToken()
{
if (_tokenOffset >= _tokenCount)
{
this.AddNewToken();
}
if (_blendedTokens != null)
{
return _blendedTokens[_tokenOffset].Token;
}
else
{
return _lexedTokens[_tokenOffset];
}
}
private void AddNewToken()
{
if (_blendedTokens != null)
{
if (_tokenCount > 0)
{
this.AddToken(_blendedTokens[_tokenCount - 1].Blender.ReadToken(_mode));
}
else
{
if (_currentNode.Token != null)
{
this.AddToken(_currentNode);
}
else
{
this.AddToken(_firstBlender.ReadToken(_mode));
}
}
}
else
{
this.AddLexedToken(this.lexer.Lex(_mode));
}
}
// adds token to end of current token array
private void AddToken(in BlendedNode tokenResult)
{
Debug.Assert(tokenResult.Token != null);
if (_tokenCount >= _blendedTokens.Length)
{
this.AddTokenSlot();
}
_blendedTokens[_tokenCount] = tokenResult;
_tokenCount++;
}
private void AddLexedToken(SyntaxToken token)
{
Debug.Assert(token != null);
if (_tokenCount >= _lexedTokens.Length)
{
this.AddLexedTokenSlot();
}
_lexedTokens[_tokenCount].Value = token;
_tokenCount++;
}
private void AddTokenSlot()
{
// shift tokens to left if we are far to the right
// don't shift if reset points have fixed locked the starting point at the token in the window
if (_tokenOffset > (_blendedTokens.Length >> 1)
&& (_resetStart == -1 || _resetStart > _firstToken))
{
int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;
int shiftCount = _tokenCount - shiftOffset;
Debug.Assert(shiftOffset > 0);
_firstBlender = _blendedTokens[shiftOffset - 1].Blender;
if (shiftCount > 0)
{
Array.Copy(_blendedTokens, shiftOffset, _blendedTokens, 0, shiftCount);
}
_firstToken += shiftOffset;
_tokenCount -= shiftOffset;
_tokenOffset -= shiftOffset;
}
else
{
var old = _blendedTokens;
Array.Resize(ref _blendedTokens, _blendedTokens.Length * 2);
s_blendedNodesPool.ForgetTrackedObject(old, replacement: _blendedTokens);
}
}
private void AddLexedTokenSlot()
{
// shift tokens to left if we are far to the right
// don't shift if reset points have fixed locked the starting point at the token in the window
if (_tokenOffset > (_lexedTokens.Length >> 1)
&& (_resetStart == -1 || _resetStart > _firstToken))
{
int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;
int shiftCount = _tokenCount - shiftOffset;
Debug.Assert(shiftOffset > 0);
if (shiftCount > 0)
{
Array.Copy(_lexedTokens, shiftOffset, _lexedTokens, 0, shiftCount);
}
_firstToken += shiftOffset;
_tokenCount -= shiftOffset;
_tokenOffset -= shiftOffset;
}
else
{
var tmp = new ArrayElement<SyntaxToken>[_lexedTokens.Length * 2];
Array.Copy(_lexedTokens, tmp, _lexedTokens.Length);
_lexedTokens = tmp;
}
}
protected SyntaxToken PeekToken(int n)
{
Debug.Assert(n >= 0);
while (_tokenOffset + n >= _tokenCount)
{
this.AddNewToken();
}
if (_blendedTokens != null)
{
return _blendedTokens[_tokenOffset + n].Token;
}
else
{
return _lexedTokens[_tokenOffset + n];
}
}
//this method is called very frequently
//we should keep it simple so that it can be inlined.
protected SyntaxToken EatToken()
{
var ct = this.CurrentToken;
MoveToNextToken();
return ct;
}
/// <summary>
/// Returns and consumes the current token if it has the requested <paramref name="kind"/>.
/// Otherwise, returns <see langword="null"/>.
/// </summary>
protected SyntaxToken TryEatToken(SyntaxKind kind)
=> this.CurrentToken.Kind == kind ? this.EatToken() : null;
private void MoveToNextToken()
{
_prevTokenTrailingTrivia = _currentToken.GetTrailingTrivia();
_currentToken = null;
if (_blendedTokens != null)
{
_currentNode = default(BlendedNode);
}
_tokenOffset++;
}
protected void ForceEndOfFile()
{
_currentToken = SyntaxFactory.Token(SyntaxKind.EndOfFileToken);
}
//this method is called very frequently
//we should keep it simple so that it can be inlined.
protected SyntaxToken EatToken(SyntaxKind kind)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
var ct = this.CurrentToken;
if (ct.Kind == kind)
{
MoveToNextToken();
return ct;
}
//slow part of EatToken(SyntaxKind kind)
return CreateMissingToken(kind, this.CurrentToken.Kind, reportError: true);
}
// Consume a token if it is the right kind. Otherwise skip a token and replace it with one of the correct kind.
protected SyntaxToken EatTokenAsKind(SyntaxKind expected)
{
Debug.Assert(SyntaxFacts.IsAnyToken(expected));
var ct = this.CurrentToken;
if (ct.Kind == expected)
{
MoveToNextToken();
return ct;
}
var replacement = CreateMissingToken(expected, this.CurrentToken.Kind, reportError: true);
return AddTrailingSkippedSyntax(replacement, this.EatToken());
}
private SyntaxToken CreateMissingToken(SyntaxKind expected, SyntaxKind actual, bool reportError)
{
// should we eat the current ParseToken's leading trivia?
var token = SyntaxFactory.MissingToken(expected);
if (reportError)
{
token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(expected, actual));
}
return token;
}
private SyntaxToken CreateMissingToken(SyntaxKind expected, ErrorCode code, bool reportError)
{
// should we eat the current ParseToken's leading trivia?
var token = SyntaxFactory.MissingToken(expected);
if (reportError)
{
token = AddError(token, code);
}
return token;
}
protected SyntaxToken EatToken(SyntaxKind kind, bool reportError)
{
if (reportError)
{
return EatToken(kind);
}
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (this.CurrentToken.Kind != kind)
{
// should we eat the current ParseToken's leading trivia?
return SyntaxFactory.MissingToken(kind);
}
else
{
return this.EatToken();
}
}
protected SyntaxToken EatToken(SyntaxKind kind, ErrorCode code, bool reportError = true)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (this.CurrentToken.Kind != kind)
{
return CreateMissingToken(kind, code, reportError);
}
else
{
return this.EatToken();
}
}
protected SyntaxToken EatTokenWithPrejudice(SyntaxKind kind)
{
var token = this.CurrentToken;
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (token.Kind != kind)
{
token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(kind, token.Kind));
}
this.MoveToNextToken();
return token;
}
protected SyntaxToken EatTokenWithPrejudice(ErrorCode errorCode, params object[] args)
{
var token = this.EatToken();
token = WithAdditionalDiagnostics(token, MakeError(token.GetLeadingTriviaWidth(), token.Width, errorCode, args));
return token;
}
protected SyntaxToken EatContextualToken(SyntaxKind kind, ErrorCode code, bool reportError = true)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (this.CurrentToken.ContextualKind != kind)
{
return CreateMissingToken(kind, code, reportError);
}
else
{
return ConvertToKeyword(this.EatToken());
}
}
protected SyntaxToken EatContextualToken(SyntaxKind kind, bool reportError = true)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
var contextualKind = this.CurrentToken.ContextualKind;
if (contextualKind != kind)
{
return CreateMissingToken(kind, contextualKind, reportError);
}
else
{
return ConvertToKeyword(this.EatToken());
}
}
protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int width)
{
var code = GetExpectedTokenErrorCode(expected, actual);
if (code == ErrorCode.ERR_SyntaxError || code == ErrorCode.ERR_IdentifierExpectedKW)
{
return new SyntaxDiagnosticInfo(offset, width, code, SyntaxFacts.GetText(expected), SyntaxFacts.GetText(actual));
}
else
{
return new SyntaxDiagnosticInfo(offset, width, code);
}
}
protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual)
{
int offset, width;
this.GetDiagnosticSpanForMissingToken(out offset, out width);
return this.GetExpectedTokenError(expected, actual, offset, width);
}
private static ErrorCode GetExpectedTokenErrorCode(SyntaxKind expected, SyntaxKind actual)
{
switch (expected)
{
case SyntaxKind.IdentifierToken:
if (SyntaxFacts.IsReservedKeyword(actual))
{
return ErrorCode.ERR_IdentifierExpectedKW; // A keyword -- use special message.
}
else
{
return ErrorCode.ERR_IdentifierExpected;
}
case SyntaxKind.SemicolonToken:
return ErrorCode.ERR_SemicolonExpected;
// case TokenKind::Colon: iError = ERR_ColonExpected; break;
// case TokenKind::OpenParen: iError = ERR_LparenExpected; break;
case SyntaxKind.CloseParenToken:
return ErrorCode.ERR_CloseParenExpected;
case SyntaxKind.OpenBraceToken:
return ErrorCode.ERR_LbraceExpected;
case SyntaxKind.CloseBraceToken:
return ErrorCode.ERR_RbraceExpected;
// case TokenKind::CloseSquare: iError = ERR_CloseSquareExpected; break;
default:
return ErrorCode.ERR_SyntaxError;
}
}
protected void GetDiagnosticSpanForMissingToken(out int offset, out int width)
{
// If the previous token has a trailing EndOfLineTrivia,
// the missing token diagnostic position is moved to the
// end of line containing the previous token and
// its width is set to zero.
// Otherwise the diagnostic offset and width is set
// to the corresponding values of the current token
var trivia = _prevTokenTrailingTrivia;
if (trivia != null)
{
SyntaxList<CSharpSyntaxNode> triviaList = new SyntaxList<CSharpSyntaxNode>(trivia);
bool prevTokenHasEndOfLineTrivia = triviaList.Any((int)SyntaxKind.EndOfLineTrivia);
if (prevTokenHasEndOfLineTrivia)
{
offset = -trivia.FullWidth;
width = 0;
return;
}
}
SyntaxToken ct = this.CurrentToken;
offset = ct.GetLeadingTriviaWidth();
width = ct.Width;
}
protected virtual TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics) where TNode : GreenNode
{
DiagnosticInfo[] existingDiags = node.GetDiagnostics();
int existingLength = existingDiags.Length;
if (existingLength == 0)
{
return node.WithDiagnosticsGreen(diagnostics);
}
else
{
DiagnosticInfo[] result = new DiagnosticInfo[existingDiags.Length + diagnostics.Length];
existingDiags.CopyTo(result, 0);
diagnostics.CopyTo(result, existingLength);
return node.WithDiagnosticsGreen(result);
}
}
protected TNode AddError<TNode>(TNode node, ErrorCode code) where TNode : GreenNode
{
return AddError(node, code, Array.Empty<object>());
}
protected TNode AddError<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode
{
if (!node.IsMissing)
{
return WithAdditionalDiagnostics(node, MakeError(node, code, args));
}
int offset, width;
SyntaxToken token = node as SyntaxToken;
if (token != null && token.ContainsSkippedText)
{
// This code exists to clean up an anti-pattern:
// 1) an undesirable token is parsed,
// 2) a desirable missing token is created and the parsed token is appended as skipped text,
// 3) an error is attached to the missing token describing the problem.
// If this occurs, then this.previousTokenTrailingTrivia is still populated with the trivia
// of the undesirable token (now skipped text). Since the trivia no longer precedes the
// node to which the error is to be attached, the computed offset will be incorrect.
offset = token.GetLeadingTriviaWidth(); // Should always be zero, but at least we'll do something sensible if it's not.
Debug.Assert(offset == 0, "Why are we producing a missing token that has both skipped text and leading trivia?");
width = 0;
bool seenSkipped = false;
foreach (var trivia in token.TrailingTrivia)
{
if (trivia.Kind == SyntaxKind.SkippedTokensTrivia)
{
seenSkipped = true;
width += trivia.Width;
}
else if (seenSkipped)
{
break;
}
else
{
offset += trivia.Width;
}
}
}
else
{
this.GetDiagnosticSpanForMissingToken(out offset, out width);
}
return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));
}
protected TNode AddError<TNode>(TNode node, int offset, int length, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
return WithAdditionalDiagnostics(node, MakeError(offset, length, code, args));
}
protected TNode AddError<TNode>(TNode node, CSharpSyntaxNode location, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
// assumes non-terminals will at most appear once in sub-tree
int offset;
FindOffset(node, location, out offset);
return WithAdditionalDiagnostics(node, MakeError(offset, location.Width, code, args));
}
protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode
{
var firstToken = node.GetFirstToken();
return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code));
}
protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
var firstToken = node.GetFirstToken();
return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code, args));
}
protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode
{
int offset;
int width;
GetOffsetAndWidthForLastToken(node, out offset, out width);
return WithAdditionalDiagnostics(node, MakeError(offset, width, code));
}
protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
int offset;
int width;
GetOffsetAndWidthForLastToken(node, out offset, out width);
return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));
}
private static void GetOffsetAndWidthForLastToken<TNode>(TNode node, out int offset, out int width) where TNode : CSharpSyntaxNode
{
var lastToken = node.GetLastNonmissingToken();
offset = node.FullWidth; //advance to end of entire node
width = 0;
if (lastToken != null) //will be null if all tokens are missing
{
offset -= lastToken.FullWidth; //rewind past last token
offset += lastToken.GetLeadingTriviaWidth(); //advance past last token leading trivia - now at start of last token
width += lastToken.Width;
}
}
protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code)
{
return new SyntaxDiagnosticInfo(offset, width, code);
}
protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(offset, width, code, args);
}
protected static SyntaxDiagnosticInfo MakeError(GreenNode node, ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(node.GetLeadingTriviaWidth(), node.Width, code, args);
}
protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(code, args);
}
protected TNode AddLeadingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode
{
var oldToken = node as SyntaxToken ?? node.GetFirstToken();
var newToken = AddSkippedSyntax(oldToken, skippedSyntax, trailing: false);
return SyntaxFirstTokenReplacer.Replace(node, oldToken, newToken, skippedSyntax.FullWidth);
}
protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax)
{
list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], skippedSyntax);
}
protected void AddTrailingSkippedSyntax<TNode>(SyntaxListBuilder<TNode> list, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode
{
list[list.Count - 1] = AddTrailingSkippedSyntax(list[list.Count - 1], skippedSyntax);
}
protected TNode AddTrailingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode
{
var token = node as SyntaxToken;
if (token != null)
{
return (TNode)(object)AddSkippedSyntax(token, skippedSyntax, trailing: true);
}
else
{
var lastToken = node.GetLastToken();
var newToken = AddSkippedSyntax(lastToken, skippedSyntax, trailing: true);
return SyntaxLastTokenReplacer.Replace(node, newToken);
}
}
/// <summary>
/// Converts skippedSyntax node into tokens and adds these as trivia on the target token.
/// Also adds the first error (in depth-first preorder) found in the skipped syntax tree to the target token.
/// </summary>
internal SyntaxToken AddSkippedSyntax(SyntaxToken target, GreenNode skippedSyntax, bool trailing)
{
var builder = new SyntaxListBuilder(4);
// the error in we'll attach to the node
SyntaxDiagnosticInfo diagnostic = null;
// the position of the error within the skippedSyntax node full tree
int diagnosticOffset = 0;
int currentOffset = 0;
foreach (var node in skippedSyntax.EnumerateNodes())
{
SyntaxToken token = node as SyntaxToken;
if (token != null)
{
builder.Add(token.GetLeadingTrivia());
if (token.Width > 0)
{
// separate trivia from the tokens
SyntaxToken tk = token.TokenWithLeadingTrivia(null).TokenWithTrailingTrivia(null);
// adjust relative offsets of diagnostics attached to the token:
int leadingWidth = token.GetLeadingTriviaWidth();
if (leadingWidth > 0)
{
var tokenDiagnostics = tk.GetDiagnostics();
for (int i = 0; i < tokenDiagnostics.Length; i++)
{
var d = (SyntaxDiagnosticInfo)tokenDiagnostics[i];
tokenDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset - leadingWidth, d.Width, (ErrorCode)d.Code, d.Arguments);
}
}
builder.Add(SyntaxFactory.SkippedTokensTrivia(tk));
}
else
{
// do not create zero-width structured trivia, GetStructure doesn't work well for them
var existing = (SyntaxDiagnosticInfo)token.GetDiagnostics().FirstOrDefault();
if (existing != null)
{
diagnostic = existing;
diagnosticOffset = currentOffset;
}
}
builder.Add(token.GetTrailingTrivia());
currentOffset += token.FullWidth;
}
else if (node.ContainsDiagnostics && diagnostic == null)
{
// only propagate the first error to reduce noise:
var existing = (SyntaxDiagnosticInfo)node.GetDiagnostics().FirstOrDefault();
if (existing != null)
{
diagnostic = existing;
diagnosticOffset = currentOffset;
}
}
}
int triviaWidth = currentOffset;
var trivia = builder.ToListNode();
// total width of everything preceding the added trivia
int triviaOffset;
if (trailing)
{
var trailingTrivia = target.GetTrailingTrivia();
triviaOffset = target.FullWidth; //added trivia is full width (before addition)
target = target.TokenWithTrailingTrivia(SyntaxList.Concat(trailingTrivia, trivia));
}
else
{
// Since we're adding triviaWidth before the token, we have to add that much to
// the offset of each of its diagnostics.
if (triviaWidth > 0)
{
var targetDiagnostics = target.GetDiagnostics();
for (int i = 0; i < targetDiagnostics.Length; i++)
{
var d = (SyntaxDiagnosticInfo)targetDiagnostics[i];
targetDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset + triviaWidth, d.Width, (ErrorCode)d.Code, d.Arguments);
}
}
var leadingTrivia = target.GetLeadingTrivia();
target = target.TokenWithLeadingTrivia(SyntaxList.Concat(trivia, leadingTrivia));
triviaOffset = 0; //added trivia is first, so offset is zero
}
if (diagnostic != null)
{
int newOffset = triviaOffset + diagnosticOffset + diagnostic.Offset;
target = WithAdditionalDiagnostics(target,
new SyntaxDiagnosticInfo(newOffset, diagnostic.Width, (ErrorCode)diagnostic.Code, diagnostic.Arguments)
);
}
return target;
}
/// <summary>
/// This function searches for the given location node within the subtree rooted at root node.
/// If it finds it, the function computes the offset span of that child node within the root and returns true,
/// otherwise it returns false.
/// </summary>
/// <param name="root">Root node</param>
/// <param name="location">Node to search in the subtree rooted at root node</param>
/// <param name="offset">Offset of the location node within the subtree rooted at child</param>
/// <returns></returns>
private bool FindOffset(GreenNode root, CSharpSyntaxNode location, out int offset)
{
int currentOffset = 0;
offset = 0;
if (root != null)
{
for (int i = 0, n = root.SlotCount; i < n; i++)
{
var child = root.GetSlot(i);
if (child == null)
{
// ignore null slots
continue;
}
// check if the child node is the location node
if (child == location)
{
// Found the location node in the subtree
// Initialize offset with the offset of the location node within its parent
// and walk up the stack of recursive calls adding the offset of each node
// within its parent
offset = currentOffset;
return true;
}
// search for the location node in the subtree rooted at child node
if (this.FindOffset(child, location, out offset))
{
// Found the location node in child's subtree
// Add the offset of child node within its parent to offset
// and continue walking up the stack
offset += child.GetLeadingTriviaWidth() + currentOffset;
return true;
}
// We didn't find the location node in the subtree rooted at child
// Move on to the next child
currentOffset += child.FullWidth;
}
}
// We didn't find the location node within the subtree rooted at root node
return false;
}
protected static SyntaxToken ConvertToKeyword(SyntaxToken token)
{
if (token.Kind != token.ContextualKind)
{
var kw = token.IsMissing
? SyntaxFactory.MissingToken(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node)
: SyntaxFactory.Token(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node);
var d = token.GetDiagnostics();
if (d != null && d.Length > 0)
{
kw = kw.WithDiagnosticsGreen(d);
}
return kw;
}
return token;
}
protected static SyntaxToken ConvertToIdentifier(SyntaxToken token)
{
Debug.Assert(!token.IsMissing);
return SyntaxToken.Identifier(token.Kind, token.LeadingTrivia.Node, token.Text, token.ValueText, token.TrailingTrivia.Node);
}
internal DirectiveStack Directives
{
get { return lexer.Directives; }
}
#nullable enable
/// <remarks>
/// NOTE: we are specifically diverging from dev11 to improve the user experience.
/// Since treating the "async" keyword as an identifier in older language
/// versions can never result in a correct program, we instead accept it as a
/// keyword regardless of the language version and produce an error if the version
/// is insufficient.
/// </remarks>
protected TNode CheckFeatureAvailability<TNode>(TNode node, MessageID feature, bool forceWarning = false)
where TNode : GreenNode
{
LanguageVersion availableVersion = this.Options.LanguageVersion;
LanguageVersion requiredVersion = feature.RequiredVersion();
// There are special error codes for some features, so handle those separately.
switch (feature)
{
case MessageID.IDS_FeatureModuleAttrLoc:
return availableVersion >= LanguageVersion.CSharp2
? node
: this.AddError(node, ErrorCode.WRN_NonECMAFeature, feature.Localize());
case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings:
return availableVersion >= requiredVersion
? node
: this.AddError(node, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable,
new CSharpRequiredLanguageVersion(requiredVersion));
}
var info = feature.GetFeatureAvailabilityDiagnosticInfo(this.Options);
if (info != null)
{
if (forceWarning)
{
return AddError(node, ErrorCode.WRN_ErrorOverride, info, (int)info.Code);
}
return AddError(node, info.Code, info.Arguments);
}
return node;
}
#nullable disable
protected bool IsFeatureEnabled(MessageID feature)
{
return this.Options.IsFeatureEnabled(feature);
}
/// <summary>
/// Whenever parsing in a <c>while (true)</c> loop and a bug could prevent the loop from making progress,
/// this method can prevent the parsing from hanging.
/// Use as:
/// int tokenProgress = -1;
/// while (IsMakingProgress(ref tokenProgress))
/// It should be used as a guardrail, not as a crutch, so it asserts if no progress was made.
/// </summary>
protected bool IsMakingProgress(ref int lastTokenPosition, bool assertIfFalse = true)
{
var pos = CurrentTokenPosition;
if (pos > lastTokenPosition)
{
lastTokenPosition = pos;
return true;
}
Debug.Assert(!assertIfFalse);
return false;
}
private int CurrentTokenPosition => _firstToken + _tokenOffset;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
internal abstract partial class SyntaxParser : IDisposable
{
protected readonly Lexer lexer;
private readonly bool _isIncremental;
private readonly bool _allowModeReset;
protected readonly CancellationToken cancellationToken;
private LexerMode _mode;
private Blender _firstBlender;
private BlendedNode _currentNode;
private SyntaxToken _currentToken;
private ArrayElement<SyntaxToken>[] _lexedTokens;
private GreenNode _prevTokenTrailingTrivia;
private int _firstToken; // The position of _lexedTokens[0] (or _blendedTokens[0]).
private int _tokenOffset; // The index of the current token within _lexedTokens or _blendedTokens.
private int _tokenCount;
private int _resetCount;
private int _resetStart;
private static readonly ObjectPool<BlendedNode[]> s_blendedNodesPool = new ObjectPool<BlendedNode[]>(() => new BlendedNode[32], 2);
private BlendedNode[] _blendedTokens;
protected SyntaxParser(
Lexer lexer,
LexerMode mode,
CSharp.CSharpSyntaxNode oldTree,
IEnumerable<TextChangeRange> changes,
bool allowModeReset,
bool preLexIfNotIncremental = false,
CancellationToken cancellationToken = default(CancellationToken))
{
this.lexer = lexer;
_mode = mode;
_allowModeReset = allowModeReset;
this.cancellationToken = cancellationToken;
_currentNode = default(BlendedNode);
_isIncremental = oldTree != null;
if (this.IsIncremental || allowModeReset)
{
_firstBlender = new Blender(lexer, oldTree, changes);
_blendedTokens = s_blendedNodesPool.Allocate();
}
else
{
_firstBlender = default(Blender);
_lexedTokens = new ArrayElement<SyntaxToken>[32];
}
// PreLex is not cancellable.
// If we may cancel why would we aggressively lex ahead?
// Cancellations in a constructor make disposing complicated
//
// So, if we have a real cancellation token, do not do prelexing.
if (preLexIfNotIncremental && !this.IsIncremental && !cancellationToken.CanBeCanceled)
{
this.PreLex();
}
}
public void Dispose()
{
var blendedTokens = _blendedTokens;
if (blendedTokens != null)
{
_blendedTokens = null;
if (blendedTokens.Length < 4096)
{
Array.Clear(blendedTokens, 0, blendedTokens.Length);
s_blendedNodesPool.Free(blendedTokens);
}
else
{
s_blendedNodesPool.ForgetTrackedObject(blendedTokens);
}
}
}
protected void ReInitialize()
{
_firstToken = 0;
_tokenOffset = 0;
_tokenCount = 0;
_resetCount = 0;
_resetStart = 0;
_currentToken = null;
_prevTokenTrailingTrivia = null;
if (this.IsIncremental || _allowModeReset)
{
_firstBlender = new Blender(this.lexer, null, null);
}
}
protected bool IsIncremental
{
get
{
return _isIncremental;
}
}
private void PreLex()
{
// NOTE: Do not cancel in this method. It is called from the constructor.
var size = Math.Min(4096, Math.Max(32, this.lexer.TextWindow.Text.Length / 2));
_lexedTokens = new ArrayElement<SyntaxToken>[size];
var lexer = this.lexer;
var mode = _mode;
for (int i = 0; i < size; i++)
{
var token = lexer.Lex(mode);
this.AddLexedToken(token);
if (token.Kind == SyntaxKind.EndOfFileToken)
{
break;
}
}
}
protected ResetPoint GetResetPoint()
{
var pos = CurrentTokenPosition;
if (_resetCount == 0)
{
_resetStart = pos; // low water mark
}
_resetCount++;
return new ResetPoint(_resetCount, _mode, pos, _prevTokenTrailingTrivia);
}
protected void Reset(ref ResetPoint point)
{
var offset = point.Position - _firstToken;
Debug.Assert(offset >= 0);
if (offset >= _tokenCount)
{
// Re-fetch tokens to the position in the reset point
PeekToken(offset - _tokenOffset);
// Re-calculate new offset in case tokens got shifted to the left while we were peeking.
offset = point.Position - _firstToken;
}
_mode = point.Mode;
Debug.Assert(offset >= 0 && offset < _tokenCount);
_tokenOffset = offset;
_currentToken = null;
_currentNode = default(BlendedNode);
_prevTokenTrailingTrivia = point.PrevTokenTrailingTrivia;
if (_blendedTokens != null)
{
// look forward for slots not holding a token
for (int i = _tokenOffset; i < _tokenCount; i++)
{
if (_blendedTokens[i].Token == null)
{
// forget anything after and including any slot not holding a token
_tokenCount = i;
if (_tokenCount == _tokenOffset)
{
FetchCurrentToken();
}
break;
}
}
}
}
protected void Release(ref ResetPoint point)
{
Debug.Assert(_resetCount == point.ResetCount);
_resetCount--;
if (_resetCount == 0)
{
_resetStart = -1;
}
}
public CSharpParseOptions Options
{
get { return this.lexer.Options; }
}
public bool IsScript
{
get { return Options.Kind == SourceCodeKind.Script; }
}
protected LexerMode Mode
{
get
{
return _mode;
}
set
{
if (_mode != value)
{
Debug.Assert(_allowModeReset);
_mode = value;
_currentToken = null;
_currentNode = default(BlendedNode);
_tokenCount = _tokenOffset;
}
}
}
protected CSharp.CSharpSyntaxNode CurrentNode
{
get
{
// we will fail anyways. Assert is just to catch that earlier.
Debug.Assert(_blendedTokens != null);
//PERF: currentNode is a BlendedNode, which is a fairly large struct.
// the following code tries not to pull the whole struct into a local
// we only need .Node
var node = _currentNode.Node;
if (node != null)
{
return node;
}
this.ReadCurrentNode();
return _currentNode.Node;
}
}
protected SyntaxKind CurrentNodeKind
{
get
{
var cn = this.CurrentNode;
return cn != null ? cn.Kind() : SyntaxKind.None;
}
}
private void ReadCurrentNode()
{
if (_tokenOffset == 0)
{
_currentNode = _firstBlender.ReadNode(_mode);
}
else
{
_currentNode = _blendedTokens[_tokenOffset - 1].Blender.ReadNode(_mode);
}
}
protected GreenNode EatNode()
{
// we will fail anyways. Assert is just to catch that earlier.
Debug.Assert(_blendedTokens != null);
// remember result
var result = CurrentNode.Green;
// store possible non-token in token sequence
if (_tokenOffset >= _blendedTokens.Length)
{
this.AddTokenSlot();
}
_blendedTokens[_tokenOffset++] = _currentNode;
_tokenCount = _tokenOffset; // forget anything after this slot
// erase current state
_currentNode = default(BlendedNode);
_currentToken = null;
return result;
}
protected SyntaxToken CurrentToken
{
get
{
return _currentToken ?? (_currentToken = this.FetchCurrentToken());
}
}
private SyntaxToken FetchCurrentToken()
{
if (_tokenOffset >= _tokenCount)
{
this.AddNewToken();
}
if (_blendedTokens != null)
{
return _blendedTokens[_tokenOffset].Token;
}
else
{
return _lexedTokens[_tokenOffset];
}
}
private void AddNewToken()
{
if (_blendedTokens != null)
{
if (_tokenCount > 0)
{
this.AddToken(_blendedTokens[_tokenCount - 1].Blender.ReadToken(_mode));
}
else
{
if (_currentNode.Token != null)
{
this.AddToken(_currentNode);
}
else
{
this.AddToken(_firstBlender.ReadToken(_mode));
}
}
}
else
{
this.AddLexedToken(this.lexer.Lex(_mode));
}
}
// adds token to end of current token array
private void AddToken(in BlendedNode tokenResult)
{
Debug.Assert(tokenResult.Token != null);
if (_tokenCount >= _blendedTokens.Length)
{
this.AddTokenSlot();
}
_blendedTokens[_tokenCount] = tokenResult;
_tokenCount++;
}
private void AddLexedToken(SyntaxToken token)
{
Debug.Assert(token != null);
if (_tokenCount >= _lexedTokens.Length)
{
this.AddLexedTokenSlot();
}
_lexedTokens[_tokenCount].Value = token;
_tokenCount++;
}
private void AddTokenSlot()
{
// shift tokens to left if we are far to the right
// don't shift if reset points have fixed locked the starting point at the token in the window
if (_tokenOffset > (_blendedTokens.Length >> 1)
&& (_resetStart == -1 || _resetStart > _firstToken))
{
int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;
int shiftCount = _tokenCount - shiftOffset;
Debug.Assert(shiftOffset > 0);
_firstBlender = _blendedTokens[shiftOffset - 1].Blender;
if (shiftCount > 0)
{
Array.Copy(_blendedTokens, shiftOffset, _blendedTokens, 0, shiftCount);
}
_firstToken += shiftOffset;
_tokenCount -= shiftOffset;
_tokenOffset -= shiftOffset;
}
else
{
var old = _blendedTokens;
Array.Resize(ref _blendedTokens, _blendedTokens.Length * 2);
s_blendedNodesPool.ForgetTrackedObject(old, replacement: _blendedTokens);
}
}
private void AddLexedTokenSlot()
{
// shift tokens to left if we are far to the right
// don't shift if reset points have fixed locked the starting point at the token in the window
if (_tokenOffset > (_lexedTokens.Length >> 1)
&& (_resetStart == -1 || _resetStart > _firstToken))
{
int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken;
int shiftCount = _tokenCount - shiftOffset;
Debug.Assert(shiftOffset > 0);
if (shiftCount > 0)
{
Array.Copy(_lexedTokens, shiftOffset, _lexedTokens, 0, shiftCount);
}
_firstToken += shiftOffset;
_tokenCount -= shiftOffset;
_tokenOffset -= shiftOffset;
}
else
{
var tmp = new ArrayElement<SyntaxToken>[_lexedTokens.Length * 2];
Array.Copy(_lexedTokens, tmp, _lexedTokens.Length);
_lexedTokens = tmp;
}
}
protected SyntaxToken PeekToken(int n)
{
Debug.Assert(n >= 0);
while (_tokenOffset + n >= _tokenCount)
{
this.AddNewToken();
}
if (_blendedTokens != null)
{
return _blendedTokens[_tokenOffset + n].Token;
}
else
{
return _lexedTokens[_tokenOffset + n];
}
}
//this method is called very frequently
//we should keep it simple so that it can be inlined.
protected SyntaxToken EatToken()
{
var ct = this.CurrentToken;
MoveToNextToken();
return ct;
}
/// <summary>
/// Returns and consumes the current token if it has the requested <paramref name="kind"/>.
/// Otherwise, returns <see langword="null"/>.
/// </summary>
protected SyntaxToken TryEatToken(SyntaxKind kind)
=> this.CurrentToken.Kind == kind ? this.EatToken() : null;
private void MoveToNextToken()
{
_prevTokenTrailingTrivia = _currentToken.GetTrailingTrivia();
_currentToken = null;
if (_blendedTokens != null)
{
_currentNode = default(BlendedNode);
}
_tokenOffset++;
}
protected void ForceEndOfFile()
{
_currentToken = SyntaxFactory.Token(SyntaxKind.EndOfFileToken);
}
//this method is called very frequently
//we should keep it simple so that it can be inlined.
protected SyntaxToken EatToken(SyntaxKind kind)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
var ct = this.CurrentToken;
if (ct.Kind == kind)
{
MoveToNextToken();
return ct;
}
//slow part of EatToken(SyntaxKind kind)
return CreateMissingToken(kind, this.CurrentToken.Kind, reportError: true);
}
// Consume a token if it is the right kind. Otherwise skip a token and replace it with one of the correct kind.
protected SyntaxToken EatTokenAsKind(SyntaxKind expected)
{
Debug.Assert(SyntaxFacts.IsAnyToken(expected));
var ct = this.CurrentToken;
if (ct.Kind == expected)
{
MoveToNextToken();
return ct;
}
var replacement = CreateMissingToken(expected, this.CurrentToken.Kind, reportError: true);
return AddTrailingSkippedSyntax(replacement, this.EatToken());
}
private SyntaxToken CreateMissingToken(SyntaxKind expected, SyntaxKind actual, bool reportError)
{
// should we eat the current ParseToken's leading trivia?
var token = SyntaxFactory.MissingToken(expected);
if (reportError)
{
token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(expected, actual));
}
return token;
}
private SyntaxToken CreateMissingToken(SyntaxKind expected, ErrorCode code, bool reportError)
{
// should we eat the current ParseToken's leading trivia?
var token = SyntaxFactory.MissingToken(expected);
if (reportError)
{
token = AddError(token, code);
}
return token;
}
protected SyntaxToken EatToken(SyntaxKind kind, bool reportError)
{
if (reportError)
{
return EatToken(kind);
}
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (this.CurrentToken.Kind != kind)
{
// should we eat the current ParseToken's leading trivia?
return SyntaxFactory.MissingToken(kind);
}
else
{
return this.EatToken();
}
}
protected SyntaxToken EatToken(SyntaxKind kind, ErrorCode code, bool reportError = true)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (this.CurrentToken.Kind != kind)
{
return CreateMissingToken(kind, code, reportError);
}
else
{
return this.EatToken();
}
}
protected SyntaxToken EatTokenWithPrejudice(SyntaxKind kind)
{
var token = this.CurrentToken;
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (token.Kind != kind)
{
token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(kind, token.Kind));
}
this.MoveToNextToken();
return token;
}
protected SyntaxToken EatTokenWithPrejudice(ErrorCode errorCode, params object[] args)
{
var token = this.EatToken();
token = WithAdditionalDiagnostics(token, MakeError(token.GetLeadingTriviaWidth(), token.Width, errorCode, args));
return token;
}
protected SyntaxToken EatContextualToken(SyntaxKind kind, ErrorCode code, bool reportError = true)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
if (this.CurrentToken.ContextualKind != kind)
{
return CreateMissingToken(kind, code, reportError);
}
else
{
return ConvertToKeyword(this.EatToken());
}
}
protected SyntaxToken EatContextualToken(SyntaxKind kind, bool reportError = true)
{
Debug.Assert(SyntaxFacts.IsAnyToken(kind));
var contextualKind = this.CurrentToken.ContextualKind;
if (contextualKind != kind)
{
return CreateMissingToken(kind, contextualKind, reportError);
}
else
{
return ConvertToKeyword(this.EatToken());
}
}
protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int width)
{
var code = GetExpectedTokenErrorCode(expected, actual);
if (code == ErrorCode.ERR_SyntaxError || code == ErrorCode.ERR_IdentifierExpectedKW)
{
return new SyntaxDiagnosticInfo(offset, width, code, SyntaxFacts.GetText(expected), SyntaxFacts.GetText(actual));
}
else
{
return new SyntaxDiagnosticInfo(offset, width, code);
}
}
protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual)
{
int offset, width;
this.GetDiagnosticSpanForMissingToken(out offset, out width);
return this.GetExpectedTokenError(expected, actual, offset, width);
}
private static ErrorCode GetExpectedTokenErrorCode(SyntaxKind expected, SyntaxKind actual)
{
switch (expected)
{
case SyntaxKind.IdentifierToken:
if (SyntaxFacts.IsReservedKeyword(actual))
{
return ErrorCode.ERR_IdentifierExpectedKW; // A keyword -- use special message.
}
else
{
return ErrorCode.ERR_IdentifierExpected;
}
case SyntaxKind.SemicolonToken:
return ErrorCode.ERR_SemicolonExpected;
// case TokenKind::Colon: iError = ERR_ColonExpected; break;
// case TokenKind::OpenParen: iError = ERR_LparenExpected; break;
case SyntaxKind.CloseParenToken:
return ErrorCode.ERR_CloseParenExpected;
case SyntaxKind.OpenBraceToken:
return ErrorCode.ERR_LbraceExpected;
case SyntaxKind.CloseBraceToken:
return ErrorCode.ERR_RbraceExpected;
// case TokenKind::CloseSquare: iError = ERR_CloseSquareExpected; break;
default:
return ErrorCode.ERR_SyntaxError;
}
}
protected void GetDiagnosticSpanForMissingToken(out int offset, out int width)
{
// If the previous token has a trailing EndOfLineTrivia,
// the missing token diagnostic position is moved to the
// end of line containing the previous token and
// its width is set to zero.
// Otherwise the diagnostic offset and width is set
// to the corresponding values of the current token
var trivia = _prevTokenTrailingTrivia;
if (trivia != null)
{
SyntaxList<CSharpSyntaxNode> triviaList = new SyntaxList<CSharpSyntaxNode>(trivia);
bool prevTokenHasEndOfLineTrivia = triviaList.Any((int)SyntaxKind.EndOfLineTrivia);
if (prevTokenHasEndOfLineTrivia)
{
offset = -trivia.FullWidth;
width = 0;
return;
}
}
SyntaxToken ct = this.CurrentToken;
offset = ct.GetLeadingTriviaWidth();
width = ct.Width;
}
protected virtual TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics) where TNode : GreenNode
{
DiagnosticInfo[] existingDiags = node.GetDiagnostics();
int existingLength = existingDiags.Length;
if (existingLength == 0)
{
return node.WithDiagnosticsGreen(diagnostics);
}
else
{
DiagnosticInfo[] result = new DiagnosticInfo[existingDiags.Length + diagnostics.Length];
existingDiags.CopyTo(result, 0);
diagnostics.CopyTo(result, existingLength);
return node.WithDiagnosticsGreen(result);
}
}
protected TNode AddError<TNode>(TNode node, ErrorCode code) where TNode : GreenNode
{
return AddError(node, code, Array.Empty<object>());
}
protected TNode AddError<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode
{
if (!node.IsMissing)
{
return WithAdditionalDiagnostics(node, MakeError(node, code, args));
}
int offset, width;
SyntaxToken token = node as SyntaxToken;
if (token != null && token.ContainsSkippedText)
{
// This code exists to clean up an anti-pattern:
// 1) an undesirable token is parsed,
// 2) a desirable missing token is created and the parsed token is appended as skipped text,
// 3) an error is attached to the missing token describing the problem.
// If this occurs, then this.previousTokenTrailingTrivia is still populated with the trivia
// of the undesirable token (now skipped text). Since the trivia no longer precedes the
// node to which the error is to be attached, the computed offset will be incorrect.
offset = token.GetLeadingTriviaWidth(); // Should always be zero, but at least we'll do something sensible if it's not.
Debug.Assert(offset == 0, "Why are we producing a missing token that has both skipped text and leading trivia?");
width = 0;
bool seenSkipped = false;
foreach (var trivia in token.TrailingTrivia)
{
if (trivia.Kind == SyntaxKind.SkippedTokensTrivia)
{
seenSkipped = true;
width += trivia.Width;
}
else if (seenSkipped)
{
break;
}
else
{
offset += trivia.Width;
}
}
}
else
{
this.GetDiagnosticSpanForMissingToken(out offset, out width);
}
return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));
}
protected TNode AddError<TNode>(TNode node, int offset, int length, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
return WithAdditionalDiagnostics(node, MakeError(offset, length, code, args));
}
protected TNode AddError<TNode>(TNode node, CSharpSyntaxNode location, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
// assumes non-terminals will at most appear once in sub-tree
int offset;
FindOffset(node, location, out offset);
return WithAdditionalDiagnostics(node, MakeError(offset, location.Width, code, args));
}
protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode
{
var firstToken = node.GetFirstToken();
return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code));
}
protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
var firstToken = node.GetFirstToken();
return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code, args));
}
protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode
{
int offset;
int width;
GetOffsetAndWidthForLastToken(node, out offset, out width);
return WithAdditionalDiagnostics(node, MakeError(offset, width, code));
}
protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode
{
int offset;
int width;
GetOffsetAndWidthForLastToken(node, out offset, out width);
return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args));
}
private static void GetOffsetAndWidthForLastToken<TNode>(TNode node, out int offset, out int width) where TNode : CSharpSyntaxNode
{
var lastToken = node.GetLastNonmissingToken();
offset = node.FullWidth; //advance to end of entire node
width = 0;
if (lastToken != null) //will be null if all tokens are missing
{
offset -= lastToken.FullWidth; //rewind past last token
offset += lastToken.GetLeadingTriviaWidth(); //advance past last token leading trivia - now at start of last token
width += lastToken.Width;
}
}
protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code)
{
return new SyntaxDiagnosticInfo(offset, width, code);
}
protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(offset, width, code, args);
}
protected static SyntaxDiagnosticInfo MakeError(GreenNode node, ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(node.GetLeadingTriviaWidth(), node.Width, code, args);
}
protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args)
{
return new SyntaxDiagnosticInfo(code, args);
}
protected TNode AddLeadingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode
{
var oldToken = node as SyntaxToken ?? node.GetFirstToken();
var newToken = AddSkippedSyntax(oldToken, skippedSyntax, trailing: false);
return SyntaxFirstTokenReplacer.Replace(node, oldToken, newToken, skippedSyntax.FullWidth);
}
protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax)
{
list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], skippedSyntax);
}
protected void AddTrailingSkippedSyntax<TNode>(SyntaxListBuilder<TNode> list, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode
{
list[list.Count - 1] = AddTrailingSkippedSyntax(list[list.Count - 1], skippedSyntax);
}
protected TNode AddTrailingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode
{
var token = node as SyntaxToken;
if (token != null)
{
return (TNode)(object)AddSkippedSyntax(token, skippedSyntax, trailing: true);
}
else
{
var lastToken = node.GetLastToken();
var newToken = AddSkippedSyntax(lastToken, skippedSyntax, trailing: true);
return SyntaxLastTokenReplacer.Replace(node, newToken);
}
}
/// <summary>
/// Converts skippedSyntax node into tokens and adds these as trivia on the target token.
/// Also adds the first error (in depth-first preorder) found in the skipped syntax tree to the target token.
/// </summary>
internal SyntaxToken AddSkippedSyntax(SyntaxToken target, GreenNode skippedSyntax, bool trailing)
{
var builder = new SyntaxListBuilder(4);
// the error in we'll attach to the node
SyntaxDiagnosticInfo diagnostic = null;
// the position of the error within the skippedSyntax node full tree
int diagnosticOffset = 0;
int currentOffset = 0;
foreach (var node in skippedSyntax.EnumerateNodes())
{
SyntaxToken token = node as SyntaxToken;
if (token != null)
{
builder.Add(token.GetLeadingTrivia());
if (token.Width > 0)
{
// separate trivia from the tokens
SyntaxToken tk = token.TokenWithLeadingTrivia(null).TokenWithTrailingTrivia(null);
// adjust relative offsets of diagnostics attached to the token:
int leadingWidth = token.GetLeadingTriviaWidth();
if (leadingWidth > 0)
{
var tokenDiagnostics = tk.GetDiagnostics();
for (int i = 0; i < tokenDiagnostics.Length; i++)
{
var d = (SyntaxDiagnosticInfo)tokenDiagnostics[i];
tokenDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset - leadingWidth, d.Width, (ErrorCode)d.Code, d.Arguments);
}
}
builder.Add(SyntaxFactory.SkippedTokensTrivia(tk));
}
else
{
// do not create zero-width structured trivia, GetStructure doesn't work well for them
var existing = (SyntaxDiagnosticInfo)token.GetDiagnostics().FirstOrDefault();
if (existing != null)
{
diagnostic = existing;
diagnosticOffset = currentOffset;
}
}
builder.Add(token.GetTrailingTrivia());
currentOffset += token.FullWidth;
}
else if (node.ContainsDiagnostics && diagnostic == null)
{
// only propagate the first error to reduce noise:
var existing = (SyntaxDiagnosticInfo)node.GetDiagnostics().FirstOrDefault();
if (existing != null)
{
diagnostic = existing;
diagnosticOffset = currentOffset;
}
}
}
int triviaWidth = currentOffset;
var trivia = builder.ToListNode();
// total width of everything preceding the added trivia
int triviaOffset;
if (trailing)
{
var trailingTrivia = target.GetTrailingTrivia();
triviaOffset = target.FullWidth; //added trivia is full width (before addition)
target = target.TokenWithTrailingTrivia(SyntaxList.Concat(trailingTrivia, trivia));
}
else
{
// Since we're adding triviaWidth before the token, we have to add that much to
// the offset of each of its diagnostics.
if (triviaWidth > 0)
{
var targetDiagnostics = target.GetDiagnostics();
for (int i = 0; i < targetDiagnostics.Length; i++)
{
var d = (SyntaxDiagnosticInfo)targetDiagnostics[i];
targetDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset + triviaWidth, d.Width, (ErrorCode)d.Code, d.Arguments);
}
}
var leadingTrivia = target.GetLeadingTrivia();
target = target.TokenWithLeadingTrivia(SyntaxList.Concat(trivia, leadingTrivia));
triviaOffset = 0; //added trivia is first, so offset is zero
}
if (diagnostic != null)
{
int newOffset = triviaOffset + diagnosticOffset + diagnostic.Offset;
target = WithAdditionalDiagnostics(target,
new SyntaxDiagnosticInfo(newOffset, diagnostic.Width, (ErrorCode)diagnostic.Code, diagnostic.Arguments)
);
}
return target;
}
/// <summary>
/// This function searches for the given location node within the subtree rooted at root node.
/// If it finds it, the function computes the offset span of that child node within the root and returns true,
/// otherwise it returns false.
/// </summary>
/// <param name="root">Root node</param>
/// <param name="location">Node to search in the subtree rooted at root node</param>
/// <param name="offset">Offset of the location node within the subtree rooted at child</param>
/// <returns></returns>
private bool FindOffset(GreenNode root, CSharpSyntaxNode location, out int offset)
{
int currentOffset = 0;
offset = 0;
if (root != null)
{
for (int i = 0, n = root.SlotCount; i < n; i++)
{
var child = root.GetSlot(i);
if (child == null)
{
// ignore null slots
continue;
}
// check if the child node is the location node
if (child == location)
{
// Found the location node in the subtree
// Initialize offset with the offset of the location node within its parent
// and walk up the stack of recursive calls adding the offset of each node
// within its parent
offset = currentOffset;
return true;
}
// search for the location node in the subtree rooted at child node
if (this.FindOffset(child, location, out offset))
{
// Found the location node in child's subtree
// Add the offset of child node within its parent to offset
// and continue walking up the stack
offset += child.GetLeadingTriviaWidth() + currentOffset;
return true;
}
// We didn't find the location node in the subtree rooted at child
// Move on to the next child
currentOffset += child.FullWidth;
}
}
// We didn't find the location node within the subtree rooted at root node
return false;
}
protected static SyntaxToken ConvertToKeyword(SyntaxToken token)
{
if (token.Kind != token.ContextualKind)
{
var kw = token.IsMissing
? SyntaxFactory.MissingToken(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node)
: SyntaxFactory.Token(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node);
var d = token.GetDiagnostics();
if (d != null && d.Length > 0)
{
kw = kw.WithDiagnosticsGreen(d);
}
return kw;
}
return token;
}
protected static SyntaxToken ConvertToIdentifier(SyntaxToken token)
{
Debug.Assert(!token.IsMissing);
return SyntaxToken.Identifier(token.Kind, token.LeadingTrivia.Node, token.Text, token.ValueText, token.TrailingTrivia.Node);
}
internal DirectiveStack Directives
{
get { return lexer.Directives; }
}
#nullable enable
/// <remarks>
/// NOTE: we are specifically diverging from dev11 to improve the user experience.
/// Since treating the "async" keyword as an identifier in older language
/// versions can never result in a correct program, we instead accept it as a
/// keyword regardless of the language version and produce an error if the version
/// is insufficient.
/// </remarks>
protected TNode CheckFeatureAvailability<TNode>(TNode node, MessageID feature, bool forceWarning = false)
where TNode : GreenNode
{
LanguageVersion availableVersion = this.Options.LanguageVersion;
LanguageVersion requiredVersion = feature.RequiredVersion();
// There are special error codes for some features, so handle those separately.
switch (feature)
{
case MessageID.IDS_FeatureModuleAttrLoc:
return availableVersion >= LanguageVersion.CSharp2
? node
: this.AddError(node, ErrorCode.WRN_NonECMAFeature, feature.Localize());
case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings:
return availableVersion >= requiredVersion
? node
: this.AddError(node, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable,
new CSharpRequiredLanguageVersion(requiredVersion));
}
var info = feature.GetFeatureAvailabilityDiagnosticInfo(this.Options);
if (info != null)
{
if (forceWarning)
{
return AddError(node, ErrorCode.WRN_ErrorOverride, info, (int)info.Code);
}
return AddError(node, info.Code, info.Arguments);
}
return node;
}
#nullable disable
protected bool IsFeatureEnabled(MessageID feature)
{
return this.Options.IsFeatureEnabled(feature);
}
/// <summary>
/// Whenever parsing in a <c>while (true)</c> loop and a bug could prevent the loop from making progress,
/// this method can prevent the parsing from hanging.
/// Use as:
/// int tokenProgress = -1;
/// while (IsMakingProgress(ref tokenProgress))
/// It should be used as a guardrail, not as a crutch, so it asserts if no progress was made.
/// </summary>
protected bool IsMakingProgress(ref int lastTokenPosition, bool assertIfFalse = true)
{
var pos = CurrentTokenPosition;
if (pos > lastTokenPosition)
{
lastTokenPosition = pos;
return true;
}
Debug.Assert(!assertIfFalse);
return false;
}
private int CurrentTokenPosition => _firstToken + _tokenOffset;
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/Test2/Compilation/CompilationTests.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.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Namespace Microsoft.CodeAnalysis.Editor.Implementation.Compilation.UnitTests
<[UseExportProvider]>
Public Class CompilationTests
Private Shared Function GetProject(snapshot As Solution, assemblyName As String) As Project
Return snapshot.Projects.Single(Function(p) p.AssemblyName = assemblyName)
End Function
<Fact>
<WorkItem(1107492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107492")>
Public Async Function TestProjectThatDoesntSupportCompilations() As Tasks.Task
Dim workspaceDefinition =
<Workspace>
<Project Language="NoCompilation" AssemblyName="TestAssembly" CommonReferencesPortable="true">
<Document>
var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations
</Document>
</Project>
</Workspace>
Dim composition = EditorTestCompositions.EditorFeatures.AddParts(
GetType(NoCompilationContentTypeLanguageService),
GetType(NoCompilationContentTypeDefinitions))
Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition)
Dim project = GetProject(workspace.CurrentSolution, "TestAssembly")
Assert.Null(Await project.GetCompilationAsync())
Assert.Null(Await project.GetCompilationAsync())
Assert.False(Await project.ContainsSymbolsWithNameAsync(Function(dummy) True, SymbolFilter.TypeAndMember, CancellationToken.None))
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Namespace Microsoft.CodeAnalysis.Editor.Implementation.Compilation.UnitTests
<[UseExportProvider]>
Public Class CompilationTests
Private Shared Function GetProject(snapshot As Solution, assemblyName As String) As Project
Return snapshot.Projects.Single(Function(p) p.AssemblyName = assemblyName)
End Function
<Fact>
<WorkItem(1107492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107492")>
Public Async Function TestProjectThatDoesntSupportCompilations() As Tasks.Task
Dim workspaceDefinition =
<Workspace>
<Project Language="NoCompilation" AssemblyName="TestAssembly" CommonReferencesPortable="true">
<Document>
var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations
</Document>
</Project>
</Workspace>
Dim composition = EditorTestCompositions.EditorFeatures.AddParts(
GetType(NoCompilationContentTypeLanguageService),
GetType(NoCompilationContentTypeDefinitions))
Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition)
Dim project = GetProject(workspace.CurrentSolution, "TestAssembly")
Assert.Null(Await project.GetCompilationAsync())
Assert.Null(Await project.GetCompilationAsync())
End Using
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.InProcess.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal abstract partial class AbstractNavigateToSearchService
{
private static ImmutableArray<(PatternMatchKind roslynKind, NavigateToMatchKind vsKind)> s_kindPairs =
ImmutableArray.Create(
(PatternMatchKind.Exact, NavigateToMatchKind.Exact),
(PatternMatchKind.Prefix, NavigateToMatchKind.Prefix),
(PatternMatchKind.NonLowercaseSubstring, NavigateToMatchKind.Substring),
(PatternMatchKind.StartOfWordSubstring, NavigateToMatchKind.Substring),
(PatternMatchKind.CamelCaseExact, NavigateToMatchKind.CamelCaseExact),
(PatternMatchKind.CamelCasePrefix, NavigateToMatchKind.CamelCasePrefix),
(PatternMatchKind.CamelCaseNonContiguousPrefix, NavigateToMatchKind.CamelCaseNonContiguousPrefix),
(PatternMatchKind.CamelCaseSubstring, NavigateToMatchKind.CamelCaseSubstring),
(PatternMatchKind.CamelCaseNonContiguousSubstring, NavigateToMatchKind.CamelCaseNonContiguousSubstring),
(PatternMatchKind.Fuzzy, NavigateToMatchKind.Fuzzy),
// Map our value to 'Fuzzy' as that's the lower value the platform supports.
(PatternMatchKind.LowercaseSubstring, NavigateToMatchKind.Fuzzy));
public static Task SearchFullyLoadedProjectInCurrentProcessAsync(
Project project, ImmutableArray<Document> priorityDocuments, string searchPattern,
IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
return FindSearchResultsAsync(
project, priorityDocuments, searchDocument: null, pattern: searchPattern, kinds, onResultFound, cancellationToken);
}
public static Task SearchFullyLoadedDocumentInCurrentProcessAsync(
Document document, string searchPattern, IImmutableSet<string> kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
return FindSearchResultsAsync(
document.Project, priorityDocuments: ImmutableArray<Document>.Empty,
document, searchPattern, kinds, onResultFound, cancellationToken);
}
private static async Task FindSearchResultsAsync(
Project project, ImmutableArray<Document> priorityDocuments,
Document? searchDocument, string pattern, IImmutableSet<string> kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
// If the user created a dotted pattern then we'll grab the last part of the name
var (patternName, patternContainerOpt) = PatternMatcher.GetNameAndContainer(pattern);
var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds);
// Prioritize the active documents if we have any.
var highPriDocs = priorityDocuments.Where(d => project.ContainsDocument(d.Id)).ToSet();
await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, highPriDocs, cancellationToken).ConfigureAwait(false);
// Then process non-priority documents.
var lowPriDocs = project.Documents.Where(d => !highPriDocs.Contains(d)).ToSet();
await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, lowPriDocs, cancellationToken).ConfigureAwait(false);
// if the caller is only searching a single doc, and we already covered it above, don't bother computing
// source-generator docs.
if (searchDocument != null && (highPriDocs.Contains(searchDocument) || lowPriDocs.Contains(searchDocument)))
return;
// Finally, generate and process and source-generated docs. this may take some time, so we always want to
// do this after the other documents.
var generatedDocs = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false);
await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, generatedDocs.ToSet<Document>(), cancellationToken).ConfigureAwait(false);
}
private static async Task ProcessDocumentsAsync(
Document? searchDocument, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound, ISet<Document> documents, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task>.GetInstance(out var tasks);
foreach (var document in documents)
{
if (searchDocument != null && searchDocument != document)
continue;
cancellationToken.ThrowIfCancellationRequested();
tasks.Add(Task.Run(() =>
ProcessDocumentAsync(document, patternName, patternContainer, kinds, onResultFound, cancellationToken), cancellationToken));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
private static async Task ProcessDocumentAsync(
Document document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
var index = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false);
await ProcessIndexAsync(
document.Id, document, patternName, patternContainer, kinds, onResultFound, index, cancellationToken).ConfigureAwait(false);
}
public static async Task SearchCachedDocumentsInCurrentProcessAsync(
Workspace workspace,
ImmutableArray<DocumentKey> documentKeys,
ImmutableArray<DocumentKey> priorityDocumentKeys,
string searchPattern,
IImmutableSet<string> kinds,
Func<RoslynNavigateToItem, Task> onItemFound,
CancellationToken cancellationToken)
{
var stringTable = new StringTable();
var highPriDocsSet = priorityDocumentKeys.ToSet();
var lowPriDocs = documentKeys.WhereAsArray(d => !highPriDocsSet.Contains(d));
// If the user created a dotted pattern then we'll grab the last part of the name
var (patternName, patternContainer) = PatternMatcher.GetNameAndContainer(searchPattern);
var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds);
await SearchCachedDocumentsInCurrentProcessAsync(
workspace, priorityDocumentKeys, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false);
await SearchCachedDocumentsInCurrentProcessAsync(
workspace, lowPriDocs, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false);
}
private static async Task SearchCachedDocumentsInCurrentProcessAsync(
Workspace workspace,
ImmutableArray<DocumentKey> documentKeys,
string patternName,
string patternContainer,
DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onItemFound,
StringTable stringTable,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task>.GetInstance(out var tasks);
foreach (var documentKey in documentKeys)
{
tasks.Add(Task.Run(async () =>
{
var index = await SyntaxTreeIndex.LoadAsync(
workspace, documentKey, checksum: null, stringTable, cancellationToken).ConfigureAwait(false);
if (index == null)
return;
await ProcessIndexAsync(
documentKey.Id, document: null, patternName, patternContainer, kinds, onItemFound, index, cancellationToken).ConfigureAwait(false);
}, cancellationToken));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
private static async Task ProcessIndexAsync(
DocumentId documentId, Document? document,
string patternName, string? patternContainer,
DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound,
SyntaxTreeIndex index,
CancellationToken cancellationToken)
{
var containerMatcher = patternContainer != null
? PatternMatcher.CreateDotSeparatedContainerMatcher(patternContainer)
: null;
using var nameMatcher = PatternMatcher.CreatePatternMatcher(patternName, includeMatchedSpans: true, allowFuzzyMatching: true);
using var _1 = containerMatcher;
foreach (var declaredSymbolInfo in index.DeclaredSymbolInfos)
{
await AddResultIfMatchAsync(
documentId, document,
declaredSymbolInfo,
nameMatcher, containerMatcher,
kinds,
onResultFound, cancellationToken).ConfigureAwait(false);
}
}
private static async Task AddResultIfMatchAsync(
DocumentId documentId, Document? document,
DeclaredSymbolInfo declaredSymbolInfo,
PatternMatcher nameMatcher, PatternMatcher? containerMatcher,
DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
using var nameMatches = TemporaryArray<PatternMatch>.Empty;
using var containerMatches = TemporaryArray<PatternMatch>.Empty;
cancellationToken.ThrowIfCancellationRequested();
if (kinds.Contains(declaredSymbolInfo.Kind) &&
nameMatcher.AddMatches(declaredSymbolInfo.Name, ref nameMatches.AsRef()) &&
containerMatcher?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, ref containerMatches.AsRef()) != false)
{
// See if we have a match in a linked file. If so, see if we have the same match in
// other projects that this file is linked in. If so, include the full set of projects
// the match is in so we can display that well in the UI.
//
// We can only do this in the case where the solution is loaded and thus we can examine
// the relationship between this document and the other documents linked to it. In the
// case where the solution isn't fully loaded and we're just reading in cached data, we
// don't know what other files we're linked to and can't merge results in this fashion.
var additionalMatchingProjects = await GetAdditionalProjectsWithMatchAsync(
document, declaredSymbolInfo, cancellationToken).ConfigureAwait(false);
var result = ConvertResult(
documentId, document, declaredSymbolInfo, nameMatches, containerMatches, additionalMatchingProjects);
await onResultFound(result).ConfigureAwait(false);
}
}
private static RoslynNavigateToItem ConvertResult(
DocumentId documentId,
Document? document,
DeclaredSymbolInfo declaredSymbolInfo,
in TemporaryArray<PatternMatch> nameMatches,
in TemporaryArray<PatternMatch> containerMatches,
ImmutableArray<ProjectId> additionalMatchingProjects)
{
var matchKind = GetNavigateToMatchKind(nameMatches);
// A match is considered to be case sensitive if all its constituent pattern matches are
// case sensitive.
var isCaseSensitive = nameMatches.All(m => m.IsCaseSensitive) && containerMatches.All(m => m.IsCaseSensitive);
var kind = GetItemKind(declaredSymbolInfo);
using var matchedSpans = TemporaryArray<TextSpan>.Empty;
foreach (var match in nameMatches)
matchedSpans.AddRange(match.MatchedSpans);
// If we were not given a Document instance, then we're finding matches in cached data
// and thus could be 'stale'.
return new RoslynNavigateToItem(
isStale: document == null,
documentId,
additionalMatchingProjects,
declaredSymbolInfo,
kind,
matchKind,
isCaseSensitive,
matchedSpans.ToImmutableAndClear());
}
private static async ValueTask<ImmutableArray<ProjectId>> GetAdditionalProjectsWithMatchAsync(
Document? document, DeclaredSymbolInfo declaredSymbolInfo, CancellationToken cancellationToken)
{
if (document == null)
return ImmutableArray<ProjectId>.Empty;
using var _ = ArrayBuilder<ProjectId>.GetInstance(out var result);
var solution = document.Project.Solution;
var linkedDocumentIds = document.GetLinkedDocumentIds();
foreach (var linkedDocumentId in linkedDocumentIds)
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
var index = await SyntaxTreeIndex.GetRequiredIndexAsync(linkedDocument, cancellationToken).ConfigureAwait(false);
// See if the index for the other file also contains this same info. If so, merge the results so the
// user only sees them as a single hit in the UI.
if (index.DeclaredSymbolInfoSet.Contains(declaredSymbolInfo))
result.Add(linkedDocument.Project.Id);
}
result.RemoveDuplicates();
return result.ToImmutable();
}
private static string GetItemKind(DeclaredSymbolInfo declaredSymbolInfo)
{
switch (declaredSymbolInfo.Kind)
{
case DeclaredSymbolInfoKind.Class:
case DeclaredSymbolInfoKind.Record:
return NavigateToItemKind.Class;
case DeclaredSymbolInfoKind.RecordStruct:
return NavigateToItemKind.Structure;
case DeclaredSymbolInfoKind.Constant:
return NavigateToItemKind.Constant;
case DeclaredSymbolInfoKind.Delegate:
return NavigateToItemKind.Delegate;
case DeclaredSymbolInfoKind.Enum:
return NavigateToItemKind.Enum;
case DeclaredSymbolInfoKind.EnumMember:
return NavigateToItemKind.EnumItem;
case DeclaredSymbolInfoKind.Event:
return NavigateToItemKind.Event;
case DeclaredSymbolInfoKind.Field:
return NavigateToItemKind.Field;
case DeclaredSymbolInfoKind.Interface:
return NavigateToItemKind.Interface;
case DeclaredSymbolInfoKind.Constructor:
case DeclaredSymbolInfoKind.ExtensionMethod:
case DeclaredSymbolInfoKind.Method:
return NavigateToItemKind.Method;
case DeclaredSymbolInfoKind.Module:
return NavigateToItemKind.Module;
case DeclaredSymbolInfoKind.Indexer:
case DeclaredSymbolInfoKind.Property:
return NavigateToItemKind.Property;
case DeclaredSymbolInfoKind.Struct:
return NavigateToItemKind.Structure;
default:
throw ExceptionUtilities.UnexpectedValue(declaredSymbolInfo.Kind);
}
}
private static NavigateToMatchKind GetNavigateToMatchKind(in TemporaryArray<PatternMatch> nameMatches)
{
// work backwards through the match kinds. That way our result is as bad as our worst match part. For
// example, say the user searches for `Console.Write` and we find `Console.Write` (exact, exact), and
// `Console.WriteLine` (exact, prefix). We don't want the latter hit to be considered an `exact` match, and
// thus as good as `Console.Write`.
for (var i = s_kindPairs.Length - 1; i >= 0; i--)
{
var (roslynKind, vsKind) = s_kindPairs[i];
foreach (var match in nameMatches)
{
if (match.Kind == roslynKind)
return vsKind;
}
}
return NavigateToMatchKind.Regular;
}
private readonly struct DeclaredSymbolInfoKindSet
{
private readonly ImmutableArray<bool> _lookupTable;
public DeclaredSymbolInfoKindSet(IEnumerable<string> navigateToItemKinds)
{
// The 'Contains' method implementation assumes that the DeclaredSymbolInfoKind type is unsigned.
Debug.Assert(Enum.GetUnderlyingType(typeof(DeclaredSymbolInfoKind)) == typeof(byte));
var lookupTable = new bool[Enum.GetValues(typeof(DeclaredSymbolInfoKind)).Length];
foreach (var navigateToItemKind in navigateToItemKinds)
{
switch (navigateToItemKind)
{
case NavigateToItemKind.Class:
lookupTable[(int)DeclaredSymbolInfoKind.Class] = true;
lookupTable[(int)DeclaredSymbolInfoKind.Record] = true;
break;
case NavigateToItemKind.Constant:
lookupTable[(int)DeclaredSymbolInfoKind.Constant] = true;
break;
case NavigateToItemKind.Delegate:
lookupTable[(int)DeclaredSymbolInfoKind.Delegate] = true;
break;
case NavigateToItemKind.Enum:
lookupTable[(int)DeclaredSymbolInfoKind.Enum] = true;
break;
case NavigateToItemKind.EnumItem:
lookupTable[(int)DeclaredSymbolInfoKind.EnumMember] = true;
break;
case NavigateToItemKind.Event:
lookupTable[(int)DeclaredSymbolInfoKind.Event] = true;
break;
case NavigateToItemKind.Field:
lookupTable[(int)DeclaredSymbolInfoKind.Field] = true;
break;
case NavigateToItemKind.Interface:
lookupTable[(int)DeclaredSymbolInfoKind.Interface] = true;
break;
case NavigateToItemKind.Method:
lookupTable[(int)DeclaredSymbolInfoKind.Constructor] = true;
lookupTable[(int)DeclaredSymbolInfoKind.ExtensionMethod] = true;
lookupTable[(int)DeclaredSymbolInfoKind.Method] = true;
break;
case NavigateToItemKind.Module:
lookupTable[(int)DeclaredSymbolInfoKind.Module] = true;
break;
case NavigateToItemKind.Property:
lookupTable[(int)DeclaredSymbolInfoKind.Indexer] = true;
lookupTable[(int)DeclaredSymbolInfoKind.Property] = true;
break;
case NavigateToItemKind.Structure:
lookupTable[(int)DeclaredSymbolInfoKind.Struct] = true;
lookupTable[(int)DeclaredSymbolInfoKind.RecordStruct] = true;
break;
default:
// Not a recognized symbol info kind
break;
}
}
_lookupTable = ImmutableArray.CreateRange(lookupTable);
}
public bool Contains(DeclaredSymbolInfoKind item)
{
return (int)item < _lookupTable.Length
&& _lookupTable[(int)item];
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal abstract partial class AbstractNavigateToSearchService
{
private static ImmutableArray<(PatternMatchKind roslynKind, NavigateToMatchKind vsKind)> s_kindPairs =
ImmutableArray.Create(
(PatternMatchKind.Exact, NavigateToMatchKind.Exact),
(PatternMatchKind.Prefix, NavigateToMatchKind.Prefix),
(PatternMatchKind.NonLowercaseSubstring, NavigateToMatchKind.Substring),
(PatternMatchKind.StartOfWordSubstring, NavigateToMatchKind.Substring),
(PatternMatchKind.CamelCaseExact, NavigateToMatchKind.CamelCaseExact),
(PatternMatchKind.CamelCasePrefix, NavigateToMatchKind.CamelCasePrefix),
(PatternMatchKind.CamelCaseNonContiguousPrefix, NavigateToMatchKind.CamelCaseNonContiguousPrefix),
(PatternMatchKind.CamelCaseSubstring, NavigateToMatchKind.CamelCaseSubstring),
(PatternMatchKind.CamelCaseNonContiguousSubstring, NavigateToMatchKind.CamelCaseNonContiguousSubstring),
(PatternMatchKind.Fuzzy, NavigateToMatchKind.Fuzzy),
// Map our value to 'Fuzzy' as that's the lower value the platform supports.
(PatternMatchKind.LowercaseSubstring, NavigateToMatchKind.Fuzzy));
public static Task SearchFullyLoadedProjectInCurrentProcessAsync(
Project project, ImmutableArray<Document> priorityDocuments, string searchPattern,
IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
return FindSearchResultsAsync(
project, priorityDocuments, searchDocument: null, pattern: searchPattern, kinds, onResultFound, cancellationToken);
}
public static Task SearchFullyLoadedDocumentInCurrentProcessAsync(
Document document, string searchPattern, IImmutableSet<string> kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
return FindSearchResultsAsync(
document.Project, priorityDocuments: ImmutableArray<Document>.Empty,
document, searchPattern, kinds, onResultFound, cancellationToken);
}
private static async Task FindSearchResultsAsync(
Project project, ImmutableArray<Document> priorityDocuments,
Document? searchDocument, string pattern, IImmutableSet<string> kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
// If the user created a dotted pattern then we'll grab the last part of the name
var (patternName, patternContainerOpt) = PatternMatcher.GetNameAndContainer(pattern);
var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds);
// Prioritize the active documents if we have any.
var highPriDocs = priorityDocuments.Where(d => project.ContainsDocument(d.Id)).ToSet();
await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, highPriDocs, cancellationToken).ConfigureAwait(false);
// Then process non-priority documents.
var lowPriDocs = project.Documents.Where(d => !highPriDocs.Contains(d)).ToSet();
await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, lowPriDocs, cancellationToken).ConfigureAwait(false);
// if the caller is only searching a single doc, and we already covered it above, don't bother computing
// source-generator docs.
if (searchDocument != null && (highPriDocs.Contains(searchDocument) || lowPriDocs.Contains(searchDocument)))
return;
// Finally, generate and process and source-generated docs. this may take some time, so we always want to
// do this after the other documents.
var generatedDocs = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false);
await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, generatedDocs.ToSet<Document>(), cancellationToken).ConfigureAwait(false);
}
private static async Task ProcessDocumentsAsync(
Document? searchDocument, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound, ISet<Document> documents, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task>.GetInstance(out var tasks);
foreach (var document in documents)
{
if (searchDocument != null && searchDocument != document)
continue;
cancellationToken.ThrowIfCancellationRequested();
tasks.Add(Task.Run(() =>
ProcessDocumentAsync(document, patternName, patternContainer, kinds, onResultFound, cancellationToken), cancellationToken));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
private static async Task ProcessDocumentAsync(
Document document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
var index = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false);
await ProcessIndexAsync(
document.Id, document, patternName, patternContainer, kinds, onResultFound, index, cancellationToken).ConfigureAwait(false);
}
public static async Task SearchCachedDocumentsInCurrentProcessAsync(
Workspace workspace,
ImmutableArray<DocumentKey> documentKeys,
ImmutableArray<DocumentKey> priorityDocumentKeys,
string searchPattern,
IImmutableSet<string> kinds,
Func<RoslynNavigateToItem, Task> onItemFound,
CancellationToken cancellationToken)
{
var stringTable = new StringTable();
var highPriDocsSet = priorityDocumentKeys.ToSet();
var lowPriDocs = documentKeys.WhereAsArray(d => !highPriDocsSet.Contains(d));
// If the user created a dotted pattern then we'll grab the last part of the name
var (patternName, patternContainer) = PatternMatcher.GetNameAndContainer(searchPattern);
var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds);
await SearchCachedDocumentsInCurrentProcessAsync(
workspace, priorityDocumentKeys, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false);
await SearchCachedDocumentsInCurrentProcessAsync(
workspace, lowPriDocs, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false);
}
private static async Task SearchCachedDocumentsInCurrentProcessAsync(
Workspace workspace,
ImmutableArray<DocumentKey> documentKeys,
string patternName,
string patternContainer,
DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onItemFound,
StringTable stringTable,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task>.GetInstance(out var tasks);
foreach (var documentKey in documentKeys)
{
tasks.Add(Task.Run(async () =>
{
var index = await SyntaxTreeIndex.LoadAsync(
workspace, documentKey, checksum: null, stringTable, cancellationToken).ConfigureAwait(false);
if (index == null)
return;
await ProcessIndexAsync(
documentKey.Id, document: null, patternName, patternContainer, kinds, onItemFound, index, cancellationToken).ConfigureAwait(false);
}, cancellationToken));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
private static async Task ProcessIndexAsync(
DocumentId documentId, Document? document,
string patternName, string? patternContainer,
DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound,
SyntaxTreeIndex index,
CancellationToken cancellationToken)
{
var containerMatcher = patternContainer != null
? PatternMatcher.CreateDotSeparatedContainerMatcher(patternContainer)
: null;
using var nameMatcher = PatternMatcher.CreatePatternMatcher(patternName, includeMatchedSpans: true, allowFuzzyMatching: true);
using var _1 = containerMatcher;
foreach (var declaredSymbolInfo in index.DeclaredSymbolInfos)
{
// Namespaces are never returned in nav-to as they're too common and have too many locations.
if (declaredSymbolInfo.Kind == DeclaredSymbolInfoKind.Namespace)
continue;
await AddResultIfMatchAsync(
documentId, document,
declaredSymbolInfo,
nameMatcher, containerMatcher,
kinds,
onResultFound, cancellationToken).ConfigureAwait(false);
}
}
private static async Task AddResultIfMatchAsync(
DocumentId documentId, Document? document,
DeclaredSymbolInfo declaredSymbolInfo,
PatternMatcher nameMatcher, PatternMatcher? containerMatcher,
DeclaredSymbolInfoKindSet kinds,
Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken)
{
using var nameMatches = TemporaryArray<PatternMatch>.Empty;
using var containerMatches = TemporaryArray<PatternMatch>.Empty;
cancellationToken.ThrowIfCancellationRequested();
if (kinds.Contains(declaredSymbolInfo.Kind) &&
nameMatcher.AddMatches(declaredSymbolInfo.Name, ref nameMatches.AsRef()) &&
containerMatcher?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, ref containerMatches.AsRef()) != false)
{
// See if we have a match in a linked file. If so, see if we have the same match in
// other projects that this file is linked in. If so, include the full set of projects
// the match is in so we can display that well in the UI.
//
// We can only do this in the case where the solution is loaded and thus we can examine
// the relationship between this document and the other documents linked to it. In the
// case where the solution isn't fully loaded and we're just reading in cached data, we
// don't know what other files we're linked to and can't merge results in this fashion.
var additionalMatchingProjects = await GetAdditionalProjectsWithMatchAsync(
document, declaredSymbolInfo, cancellationToken).ConfigureAwait(false);
var result = ConvertResult(
documentId, document, declaredSymbolInfo, nameMatches, containerMatches, additionalMatchingProjects);
await onResultFound(result).ConfigureAwait(false);
}
}
private static RoslynNavigateToItem ConvertResult(
DocumentId documentId,
Document? document,
DeclaredSymbolInfo declaredSymbolInfo,
in TemporaryArray<PatternMatch> nameMatches,
in TemporaryArray<PatternMatch> containerMatches,
ImmutableArray<ProjectId> additionalMatchingProjects)
{
var matchKind = GetNavigateToMatchKind(nameMatches);
// A match is considered to be case sensitive if all its constituent pattern matches are
// case sensitive.
var isCaseSensitive = nameMatches.All(m => m.IsCaseSensitive) && containerMatches.All(m => m.IsCaseSensitive);
var kind = GetItemKind(declaredSymbolInfo);
using var matchedSpans = TemporaryArray<TextSpan>.Empty;
foreach (var match in nameMatches)
matchedSpans.AddRange(match.MatchedSpans);
// If we were not given a Document instance, then we're finding matches in cached data
// and thus could be 'stale'.
return new RoslynNavigateToItem(
isStale: document == null,
documentId,
additionalMatchingProjects,
declaredSymbolInfo,
kind,
matchKind,
isCaseSensitive,
matchedSpans.ToImmutableAndClear());
}
private static async ValueTask<ImmutableArray<ProjectId>> GetAdditionalProjectsWithMatchAsync(
Document? document, DeclaredSymbolInfo declaredSymbolInfo, CancellationToken cancellationToken)
{
if (document == null)
return ImmutableArray<ProjectId>.Empty;
using var _ = ArrayBuilder<ProjectId>.GetInstance(out var result);
var solution = document.Project.Solution;
var linkedDocumentIds = document.GetLinkedDocumentIds();
foreach (var linkedDocumentId in linkedDocumentIds)
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
var index = await SyntaxTreeIndex.GetRequiredIndexAsync(linkedDocument, cancellationToken).ConfigureAwait(false);
// See if the index for the other file also contains this same info. If so, merge the results so the
// user only sees them as a single hit in the UI.
if (index.DeclaredSymbolInfoSet.Contains(declaredSymbolInfo))
result.Add(linkedDocument.Project.Id);
}
result.RemoveDuplicates();
return result.ToImmutable();
}
private static string GetItemKind(DeclaredSymbolInfo declaredSymbolInfo)
{
switch (declaredSymbolInfo.Kind)
{
case DeclaredSymbolInfoKind.Class:
case DeclaredSymbolInfoKind.Record:
return NavigateToItemKind.Class;
case DeclaredSymbolInfoKind.RecordStruct:
return NavigateToItemKind.Structure;
case DeclaredSymbolInfoKind.Constant:
return NavigateToItemKind.Constant;
case DeclaredSymbolInfoKind.Delegate:
return NavigateToItemKind.Delegate;
case DeclaredSymbolInfoKind.Enum:
return NavigateToItemKind.Enum;
case DeclaredSymbolInfoKind.EnumMember:
return NavigateToItemKind.EnumItem;
case DeclaredSymbolInfoKind.Event:
return NavigateToItemKind.Event;
case DeclaredSymbolInfoKind.Field:
return NavigateToItemKind.Field;
case DeclaredSymbolInfoKind.Interface:
return NavigateToItemKind.Interface;
case DeclaredSymbolInfoKind.Constructor:
case DeclaredSymbolInfoKind.ExtensionMethod:
case DeclaredSymbolInfoKind.Method:
return NavigateToItemKind.Method;
case DeclaredSymbolInfoKind.Module:
return NavigateToItemKind.Module;
case DeclaredSymbolInfoKind.Indexer:
case DeclaredSymbolInfoKind.Property:
return NavigateToItemKind.Property;
case DeclaredSymbolInfoKind.Struct:
return NavigateToItemKind.Structure;
default:
throw ExceptionUtilities.UnexpectedValue(declaredSymbolInfo.Kind);
}
}
private static NavigateToMatchKind GetNavigateToMatchKind(in TemporaryArray<PatternMatch> nameMatches)
{
// work backwards through the match kinds. That way our result is as bad as our worst match part. For
// example, say the user searches for `Console.Write` and we find `Console.Write` (exact, exact), and
// `Console.WriteLine` (exact, prefix). We don't want the latter hit to be considered an `exact` match, and
// thus as good as `Console.Write`.
for (var i = s_kindPairs.Length - 1; i >= 0; i--)
{
var (roslynKind, vsKind) = s_kindPairs[i];
foreach (var match in nameMatches)
{
if (match.Kind == roslynKind)
return vsKind;
}
}
return NavigateToMatchKind.Regular;
}
private readonly struct DeclaredSymbolInfoKindSet
{
private readonly ImmutableArray<bool> _lookupTable;
public DeclaredSymbolInfoKindSet(IEnumerable<string> navigateToItemKinds)
{
// The 'Contains' method implementation assumes that the DeclaredSymbolInfoKind type is unsigned.
Debug.Assert(Enum.GetUnderlyingType(typeof(DeclaredSymbolInfoKind)) == typeof(byte));
var lookupTable = new bool[Enum.GetValues(typeof(DeclaredSymbolInfoKind)).Length];
foreach (var navigateToItemKind in navigateToItemKinds)
{
switch (navigateToItemKind)
{
case NavigateToItemKind.Class:
lookupTable[(int)DeclaredSymbolInfoKind.Class] = true;
lookupTable[(int)DeclaredSymbolInfoKind.Record] = true;
break;
case NavigateToItemKind.Constant:
lookupTable[(int)DeclaredSymbolInfoKind.Constant] = true;
break;
case NavigateToItemKind.Delegate:
lookupTable[(int)DeclaredSymbolInfoKind.Delegate] = true;
break;
case NavigateToItemKind.Enum:
lookupTable[(int)DeclaredSymbolInfoKind.Enum] = true;
break;
case NavigateToItemKind.EnumItem:
lookupTable[(int)DeclaredSymbolInfoKind.EnumMember] = true;
break;
case NavigateToItemKind.Event:
lookupTable[(int)DeclaredSymbolInfoKind.Event] = true;
break;
case NavigateToItemKind.Field:
lookupTable[(int)DeclaredSymbolInfoKind.Field] = true;
break;
case NavigateToItemKind.Interface:
lookupTable[(int)DeclaredSymbolInfoKind.Interface] = true;
break;
case NavigateToItemKind.Method:
lookupTable[(int)DeclaredSymbolInfoKind.Constructor] = true;
lookupTable[(int)DeclaredSymbolInfoKind.ExtensionMethod] = true;
lookupTable[(int)DeclaredSymbolInfoKind.Method] = true;
break;
case NavigateToItemKind.Module:
lookupTable[(int)DeclaredSymbolInfoKind.Module] = true;
break;
case NavigateToItemKind.Property:
lookupTable[(int)DeclaredSymbolInfoKind.Indexer] = true;
lookupTable[(int)DeclaredSymbolInfoKind.Property] = true;
break;
case NavigateToItemKind.Structure:
lookupTable[(int)DeclaredSymbolInfoKind.Struct] = true;
lookupTable[(int)DeclaredSymbolInfoKind.RecordStruct] = true;
break;
default:
// Not a recognized symbol info kind
break;
}
}
_lookupTable = ImmutableArray.CreateRange(lookupTable);
}
public bool Contains(DeclaredSymbolInfoKind item)
{
return (int)item < _lookupTable.Length
&& _lookupTable[(int)item];
}
}
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/CSharp/Portable/FindSymbols/CSharpDeclaredSymbolInfoFactoryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.FindSymbols
{
[ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared]
internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService<
CompilationUnitSyntax,
UsingDirectiveSyntax,
BaseNamespaceDeclarationSyntax,
TypeDeclarationSyntax,
EnumDeclarationSyntax,
MemberDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpDeclaredSymbolInfoFactoryService()
{
}
private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList)
{
if (baseList == null)
{
return ImmutableArray<string>.Empty;
}
var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count);
// It's not sufficient to just store the textual names we see in the inheritance list
// of a type. For example if we have:
//
// using Y = X;
// ...
// using Z = Y;
// ...
// class C : Z
//
// It's insufficient to just state that 'C' derives from 'Z'. If we search for derived
// types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing
// that occurs in containing scopes. Then, when we're adding an inheritance name we
// walk the alias maps and we also add any names that these names alias to. In the
// above example we'd put Z, Y, and X in the inheritance names list for 'C'.
// Each dictionary in this list is a mapping from alias name to the name of the thing
// it aliases. Then, each scope with alias mapping gets its own entry in this list.
// For the above example, we would produce: [{Z => Y}, {Y => X}]
var aliasMaps = AllocateAliasMapList();
try
{
AddAliasMaps(baseList, aliasMaps);
foreach (var baseType in baseList.Types)
{
AddInheritanceName(builder, baseType.Type, aliasMaps);
}
Intern(stringTable, builder);
return builder.ToImmutableAndFree();
}
finally
{
FreeAliasMapList(aliasMaps);
}
}
private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps)
{
for (var current = node; current != null; current = current.Parent)
{
if (current is BaseNamespaceDeclarationSyntax nsDecl)
{
ProcessUsings(aliasMaps, nsDecl.Usings);
}
else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit))
{
ProcessUsings(aliasMaps, compilationUnit.Usings);
}
}
}
private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings)
{
Dictionary<string, string> aliasMap = null;
foreach (var usingDecl in usings)
{
if (usingDecl.Alias != null)
{
var mappedName = GetTypeName(usingDecl.Name);
if (mappedName != null)
{
aliasMap ??= AllocateAliasMap();
// If we have: using X = Goo, then we store a mapping from X -> Goo
// here. That way if we see a class that inherits from X we also state
// that it inherits from Goo as well.
aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName;
}
}
}
if (aliasMap != null)
{
aliasMaps.Add(aliasMap);
}
}
private static void AddInheritanceName(
ArrayBuilder<string> builder, TypeSyntax type,
List<Dictionary<string, string>> aliasMaps)
{
var name = GetTypeName(type);
if (name != null)
{
// First, add the name that the typename that the type directly says it inherits from.
builder.Add(name);
// Now, walk the alias chain and add any names this alias may eventually map to.
var currentName = name;
foreach (var aliasMap in aliasMaps)
{
if (aliasMap.TryGetValue(currentName, out var mappedName))
{
// Looks like this could be an alias. Also include the name the alias points to
builder.Add(mappedName);
// Keep on searching. An alias in an inner namespcae can refer to an
// alias in an outer namespace.
currentName = mappedName;
}
}
}
}
protected override void AddDeclaredSymbolInfosWorker(
SyntaxNode container,
MemberDeclarationSyntax node,
StringTable stringTable,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, string> aliases,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
string containerDisplayName,
string fullyQualifiedContainerName,
CancellationToken cancellationToken)
{
// If this is a part of partial type that only contains nested types, then we don't make an info type for
// it. That's because we effectively think of this as just being a virtual container just to hold the nested
// types, and not something someone would want to explicitly navigate to itself. Similar to how we think of
// namespaces.
if (node is TypeDeclarationSyntax typeDeclaration &&
typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) &&
typeDeclaration.Members.Any() &&
typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax))
{
return;
}
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
var typeDecl = (TypeDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeDecl.Identifier.ValueText,
GetTypeParameterSuffix(typeDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
node.Kind() switch
{
SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class,
SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record,
SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface,
SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct,
SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct,
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
},
GetAccessibility(container, typeDecl.Modifiers),
typeDecl.Identifier.Span,
GetInheritanceNames(stringTable, typeDecl.BaseList),
IsNestedType(typeDecl)));
return;
case SyntaxKind.EnumDeclaration:
var enumDecl = (EnumDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumDecl.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Enum,
GetAccessibility(container, enumDecl.Modifiers),
enumDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty,
isNestedType: IsNestedType(enumDecl)));
return;
case SyntaxKind.ConstructorDeclaration:
var ctorDecl = (ConstructorDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
ctorDecl.Identifier.ValueText,
GetConstructorSuffix(ctorDecl),
containerDisplayName,
fullyQualifiedContainerName,
ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Constructor,
GetAccessibility(container, ctorDecl.Modifiers),
ctorDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty,
parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0));
return;
case SyntaxKind.DelegateDeclaration:
var delegateDecl = (DelegateDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
delegateDecl.Identifier.ValueText,
GetTypeParameterSuffix(delegateDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Delegate,
GetAccessibility(container, delegateDecl.Modifiers),
delegateDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.EnumMemberDeclaration:
var enumMember = (EnumMemberDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumMember.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
enumMember.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.EnumMember,
Accessibility.Public,
enumMember.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.EventDeclaration:
var eventDecl = (EventDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
eventDecl.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Event,
GetAccessibility(container, eventDecl.Modifiers),
eventDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.IndexerDeclaration:
var indexerDecl = (IndexerDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
"this", GetIndexerSuffix(indexerDecl),
containerDisplayName,
fullyQualifiedContainerName,
indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Indexer,
GetAccessibility(container, indexerDecl.Modifiers),
indexerDecl.ThisKeyword.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.MethodDeclaration:
var method = (MethodDeclarationSyntax)node;
var isExtensionMethod = IsExtensionMethod(method);
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
method.Identifier.ValueText, GetMethodSuffix(method),
containerDisplayName,
fullyQualifiedContainerName,
method.Modifiers.Any(SyntaxKind.PartialKeyword),
isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method,
GetAccessibility(container, method.Modifiers),
method.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty,
parameterCount: method.ParameterList?.Parameters.Count ?? 0,
typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0));
if (isExtensionMethod)
AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo);
return;
case SyntaxKind.PropertyDeclaration:
var property = (PropertyDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
property.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
property.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Property,
GetAccessibility(container, property.Modifiers),
property.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
var fieldDeclaration = (BaseFieldDeclarationSyntax)node;
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
{
var kind = fieldDeclaration is EventFieldDeclarationSyntax
? DeclaredSymbolInfoKind.Event
: fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword)
? DeclaredSymbolInfoKind.Constant
: DeclaredSymbolInfoKind.Field;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
variableDeclarator.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword),
kind,
GetAccessibility(container, fieldDeclaration.Modifiers),
variableDeclarator.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
}
return;
}
}
protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node)
=> node.Members;
protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node)
=> node.Members;
protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node)
=> node.Members;
protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node)
=> node.Members;
protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node)
=> node.Usings;
protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node)
=> node.Usings;
private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl)
=> typeDecl.Parent is BaseTypeDeclarationSyntax;
private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor)
=> constructor.Modifiers.Any(SyntaxKind.StaticKeyword)
? ".static " + constructor.Identifier + "()"
: GetSuffix('(', ')', constructor.ParameterList.Parameters);
private static string GetMethodSuffix(MethodDeclarationSyntax method)
=> GetTypeParameterSuffix(method.TypeParameterList) +
GetSuffix('(', ')', method.ParameterList.Parameters);
private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer)
=> GetSuffix('[', ']', indexer.ParameterList.Parameters);
private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList)
{
if (typeParameterList == null)
{
return null;
}
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append('<');
var first = true;
foreach (var parameter in typeParameterList.Parameters)
{
if (!first)
{
builder.Append(", ");
}
builder.Append(parameter.Identifier.Text);
first = false;
}
builder.Append('>');
return pooledBuilder.ToStringAndFree();
}
/// <summary>
/// Builds up the suffix to show for something with parameters in navigate-to.
/// While it would be nice to just use the compiler SymbolDisplay API for this,
/// it would be too expensive as it requires going back to Symbols (which requires
/// creating compilations, etc.) in a perf sensitive area.
///
/// So, instead, we just build a reasonable suffix using the pure syntax that a
/// user provided. That means that if they wrote "Method(System.Int32 i)" we'll
/// show that as "Method(System.Int32)" not "Method(int)". Given that this is
/// actually what the user wrote, and it saves us from ever having to go back to
/// symbols/compilations, this is well worth it, even if it does mean we have to
/// create our own 'symbol display' logic here.
/// </summary>
private static string GetSuffix(
char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append(openBrace);
AppendParameters(parameters, builder);
builder.Append(closeBrace);
return pooledBuilder.ToStringAndFree();
}
private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder)
{
var first = true;
foreach (var parameter in parameters)
{
if (!first)
{
builder.Append(", ");
}
foreach (var modifier in parameter.Modifiers)
{
builder.Append(modifier.Text);
builder.Append(' ');
}
if (parameter.Type != null)
{
AppendTokens(parameter.Type, builder);
}
else
{
builder.Append(parameter.Identifier.Text);
}
first = false;
}
}
protected override string GetContainerDisplayName(MemberDeclarationSyntax node)
=> CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters);
protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace)
=> CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces);
private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers)
{
var sawInternal = false;
foreach (var modifier in modifiers)
{
switch (modifier.Kind())
{
case SyntaxKind.PublicKeyword: return Accessibility.Public;
case SyntaxKind.PrivateKeyword: return Accessibility.Private;
case SyntaxKind.ProtectedKeyword: return Accessibility.Protected;
case SyntaxKind.InternalKeyword:
sawInternal = true;
continue;
}
}
if (sawInternal)
return Accessibility.Internal;
// No accessibility modifiers:
switch (container.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
// Anything without modifiers is private if it's in a class/struct declaration.
return Accessibility.Private;
case SyntaxKind.InterfaceDeclaration:
// Anything without modifiers is public if it's in an interface declaration.
return Accessibility.Public;
case SyntaxKind.CompilationUnit:
// Things are private by default in script
if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script)
return Accessibility.Private;
return Accessibility.Internal;
default:
// Otherwise it's internal
return Accessibility.Internal;
}
}
private static string GetTypeName(TypeSyntax type)
{
if (type is SimpleNameSyntax simpleName)
{
return GetSimpleTypeName(simpleName);
}
else if (type is QualifiedNameSyntax qualifiedName)
{
return GetSimpleTypeName(qualifiedName.Right);
}
else if (type is AliasQualifiedNameSyntax aliasName)
{
return GetSimpleTypeName(aliasName.Name);
}
return null;
}
private static string GetSimpleTypeName(SimpleNameSyntax name)
=> name.Identifier.ValueText;
private static bool IsExtensionMethod(MethodDeclarationSyntax method)
=> method.ParameterList.Parameters.Count > 0 &&
method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword);
// Root namespace is a VB only concept, which basically means root namespace is always global in C#.
protected override string GetRootNamespace(CompilationOptions compilationOptions)
=> string.Empty;
protected override bool TryGetAliasesFromUsingDirective(
UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases)
{
if (usingDirectiveNode.Alias != null)
{
if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) &&
TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _))
{
aliases = ImmutableArray.Create<(string, string)>((aliasName, name));
return true;
}
}
aliases = default;
return false;
}
protected override string GetReceiverTypeName(MemberDeclarationSyntax node)
{
var methodDeclaration = (MethodDeclarationSyntax)node;
Debug.Assert(IsExtensionMethod(methodDeclaration));
var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text);
TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray);
return CreateReceiverTypeString(targetTypeName, isArray);
}
private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray)
{
isArray = false;
if (node is TypeSyntax typeNode)
{
switch (typeNode)
{
case IdentifierNameSyntax identifierNameNode:
// We consider it a complex method if the receiver type is a type parameter.
var text = identifierNameNode.Identifier.Text;
simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text;
return simpleTypeName != null;
case ArrayTypeSyntax arrayTypeNode:
isArray = true;
return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _);
case GenericNameSyntax genericNameNode:
var name = genericNameNode.Identifier.Text;
var arity = genericNameNode.Arity;
simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity);
return true;
case PredefinedTypeSyntax predefinedTypeNode:
simpleTypeName = GetSpecialTypeName(predefinedTypeNode);
return simpleTypeName != null;
case AliasQualifiedNameSyntax aliasQualifiedNameNode:
return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _);
case QualifiedNameSyntax qualifiedNameNode:
// For an identifier to the right of a '.', it can't be a type parameter,
// so we don't need to check for it further.
return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _);
case NullableTypeSyntax nullableNode:
// Ignore nullability, becase nullable reference type might not be enabled universally.
// In the worst case we just include more methods to check in out filter.
return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray);
case TupleTypeSyntax tupleType:
simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count);
return true;
}
}
simpleTypeName = null;
return false;
}
private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode)
{
var kind = predefinedTypeNode.Keyword.Kind();
return kind switch
{
SyntaxKind.BoolKeyword => "Boolean",
SyntaxKind.ByteKeyword => "Byte",
SyntaxKind.SByteKeyword => "SByte",
SyntaxKind.ShortKeyword => "Int16",
SyntaxKind.UShortKeyword => "UInt16",
SyntaxKind.IntKeyword => "Int32",
SyntaxKind.UIntKeyword => "UInt32",
SyntaxKind.LongKeyword => "Int64",
SyntaxKind.ULongKeyword => "UInt64",
SyntaxKind.DoubleKeyword => "Double",
SyntaxKind.FloatKeyword => "Single",
SyntaxKind.DecimalKeyword => "Decimal",
SyntaxKind.StringKeyword => "String",
SyntaxKind.CharKeyword => "Char",
SyntaxKind.ObjectKeyword => "Object",
_ => null,
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.FindSymbols
{
[ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared]
internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService<
CompilationUnitSyntax,
UsingDirectiveSyntax,
BaseNamespaceDeclarationSyntax,
TypeDeclarationSyntax,
EnumDeclarationSyntax,
MemberDeclarationSyntax,
NameSyntax,
QualifiedNameSyntax,
IdentifierNameSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpDeclaredSymbolInfoFactoryService()
{
}
private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList)
{
if (baseList == null)
{
return ImmutableArray<string>.Empty;
}
var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count);
// It's not sufficient to just store the textual names we see in the inheritance list
// of a type. For example if we have:
//
// using Y = X;
// ...
// using Z = Y;
// ...
// class C : Z
//
// It's insufficient to just state that 'C' derives from 'Z'. If we search for derived
// types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing
// that occurs in containing scopes. Then, when we're adding an inheritance name we
// walk the alias maps and we also add any names that these names alias to. In the
// above example we'd put Z, Y, and X in the inheritance names list for 'C'.
// Each dictionary in this list is a mapping from alias name to the name of the thing
// it aliases. Then, each scope with alias mapping gets its own entry in this list.
// For the above example, we would produce: [{Z => Y}, {Y => X}]
var aliasMaps = AllocateAliasMapList();
try
{
AddAliasMaps(baseList, aliasMaps);
foreach (var baseType in baseList.Types)
{
AddInheritanceName(builder, baseType.Type, aliasMaps);
}
Intern(stringTable, builder);
return builder.ToImmutableAndFree();
}
finally
{
FreeAliasMapList(aliasMaps);
}
}
private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps)
{
for (var current = node; current != null; current = current.Parent)
{
if (current is BaseNamespaceDeclarationSyntax nsDecl)
{
ProcessUsings(aliasMaps, nsDecl.Usings);
}
else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit))
{
ProcessUsings(aliasMaps, compilationUnit.Usings);
}
}
}
private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings)
{
Dictionary<string, string> aliasMap = null;
foreach (var usingDecl in usings)
{
if (usingDecl.Alias != null)
{
var mappedName = GetTypeName(usingDecl.Name);
if (mappedName != null)
{
aliasMap ??= AllocateAliasMap();
// If we have: using X = Goo, then we store a mapping from X -> Goo
// here. That way if we see a class that inherits from X we also state
// that it inherits from Goo as well.
aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName;
}
}
}
if (aliasMap != null)
{
aliasMaps.Add(aliasMap);
}
}
private static void AddInheritanceName(
ArrayBuilder<string> builder, TypeSyntax type,
List<Dictionary<string, string>> aliasMaps)
{
var name = GetTypeName(type);
if (name != null)
{
// First, add the name that the typename that the type directly says it inherits from.
builder.Add(name);
// Now, walk the alias chain and add any names this alias may eventually map to.
var currentName = name;
foreach (var aliasMap in aliasMaps)
{
if (aliasMap.TryGetValue(currentName, out var mappedName))
{
// Looks like this could be an alias. Also include the name the alias points to
builder.Add(mappedName);
// Keep on searching. An alias in an inner namespcae can refer to an
// alias in an outer namespace.
currentName = mappedName;
}
}
}
}
protected override void AddDeclaredSymbolInfosWorker(
SyntaxNode container,
MemberDeclarationSyntax node,
StringTable stringTable,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, string> aliases,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
string containerDisplayName,
string fullyQualifiedContainerName,
CancellationToken cancellationToken)
{
// If this is a part of partial type that only contains nested types, then we don't make an info type for
// it. That's because we effectively think of this as just being a virtual container just to hold the nested
// types, and not something someone would want to explicitly navigate to itself. Similar to how we think of
// namespaces.
if (node is TypeDeclarationSyntax typeDeclaration &&
typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) &&
typeDeclaration.Members.Any() &&
typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax))
{
return;
}
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
var typeDecl = (TypeDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeDecl.Identifier.ValueText,
GetTypeParameterSuffix(typeDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
node.Kind() switch
{
SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class,
SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record,
SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface,
SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct,
SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct,
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
},
GetAccessibility(container, typeDecl.Modifiers),
typeDecl.Identifier.Span,
GetInheritanceNames(stringTable, typeDecl.BaseList),
IsNestedType(typeDecl)));
return;
case SyntaxKind.EnumDeclaration:
var enumDecl = (EnumDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumDecl.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Enum,
GetAccessibility(container, enumDecl.Modifiers),
enumDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty,
isNestedType: IsNestedType(enumDecl)));
return;
case SyntaxKind.ConstructorDeclaration:
var ctorDecl = (ConstructorDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
ctorDecl.Identifier.ValueText,
GetConstructorSuffix(ctorDecl),
containerDisplayName,
fullyQualifiedContainerName,
ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Constructor,
GetAccessibility(container, ctorDecl.Modifiers),
ctorDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty,
parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0));
return;
case SyntaxKind.DelegateDeclaration:
var delegateDecl = (DelegateDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
delegateDecl.Identifier.ValueText,
GetTypeParameterSuffix(delegateDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Delegate,
GetAccessibility(container, delegateDecl.Modifiers),
delegateDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.EnumMemberDeclaration:
var enumMember = (EnumMemberDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumMember.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
enumMember.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.EnumMember,
Accessibility.Public,
enumMember.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.EventDeclaration:
var eventDecl = (EventDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
eventDecl.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Event,
GetAccessibility(container, eventDecl.Modifiers),
eventDecl.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.IndexerDeclaration:
var indexerDecl = (IndexerDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
"this", GetIndexerSuffix(indexerDecl),
containerDisplayName,
fullyQualifiedContainerName,
indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Indexer,
GetAccessibility(container, indexerDecl.Modifiers),
indexerDecl.ThisKeyword.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.MethodDeclaration:
var method = (MethodDeclarationSyntax)node;
var isExtensionMethod = IsExtensionMethod(method);
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
method.Identifier.ValueText, GetMethodSuffix(method),
containerDisplayName,
fullyQualifiedContainerName,
method.Modifiers.Any(SyntaxKind.PartialKeyword),
isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method,
GetAccessibility(container, method.Modifiers),
method.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty,
parameterCount: method.ParameterList?.Parameters.Count ?? 0,
typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0));
if (isExtensionMethod)
AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo);
return;
case SyntaxKind.PropertyDeclaration:
var property = (PropertyDeclarationSyntax)node;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
property.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
property.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Property,
GetAccessibility(container, property.Modifiers),
property.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
var fieldDeclaration = (BaseFieldDeclarationSyntax)node;
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
{
var kind = fieldDeclaration is EventFieldDeclarationSyntax
? DeclaredSymbolInfoKind.Event
: fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword)
? DeclaredSymbolInfoKind.Constant
: DeclaredSymbolInfoKind.Field;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
variableDeclarator.Identifier.ValueText, null,
containerDisplayName,
fullyQualifiedContainerName,
fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword),
kind,
GetAccessibility(container, fieldDeclaration.Modifiers),
variableDeclarator.Identifier.Span,
inheritanceNames: ImmutableArray<string>.Empty));
}
return;
}
}
protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node)
=> node.Members;
protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node)
=> node.Members;
protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node)
=> node.Members;
protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node)
=> node.Members;
protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node)
=> node.Usings;
protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node)
=> node.Usings;
protected override NameSyntax GetName(BaseNamespaceDeclarationSyntax node)
=> node.Name;
protected override NameSyntax GetLeft(QualifiedNameSyntax node)
=> node.Left;
protected override NameSyntax GetRight(QualifiedNameSyntax node)
=> node.Right;
protected override SyntaxToken GetIdentifier(IdentifierNameSyntax node)
=> node.Identifier;
private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl)
=> typeDecl.Parent is BaseTypeDeclarationSyntax;
private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor)
=> constructor.Modifiers.Any(SyntaxKind.StaticKeyword)
? ".static " + constructor.Identifier + "()"
: GetSuffix('(', ')', constructor.ParameterList.Parameters);
private static string GetMethodSuffix(MethodDeclarationSyntax method)
=> GetTypeParameterSuffix(method.TypeParameterList) +
GetSuffix('(', ')', method.ParameterList.Parameters);
private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer)
=> GetSuffix('[', ']', indexer.ParameterList.Parameters);
private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList)
{
if (typeParameterList == null)
{
return null;
}
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append('<');
var first = true;
foreach (var parameter in typeParameterList.Parameters)
{
if (!first)
{
builder.Append(", ");
}
builder.Append(parameter.Identifier.Text);
first = false;
}
builder.Append('>');
return pooledBuilder.ToStringAndFree();
}
/// <summary>
/// Builds up the suffix to show for something with parameters in navigate-to.
/// While it would be nice to just use the compiler SymbolDisplay API for this,
/// it would be too expensive as it requires going back to Symbols (which requires
/// creating compilations, etc.) in a perf sensitive area.
///
/// So, instead, we just build a reasonable suffix using the pure syntax that a
/// user provided. That means that if they wrote "Method(System.Int32 i)" we'll
/// show that as "Method(System.Int32)" not "Method(int)". Given that this is
/// actually what the user wrote, and it saves us from ever having to go back to
/// symbols/compilations, this is well worth it, even if it does mean we have to
/// create our own 'symbol display' logic here.
/// </summary>
private static string GetSuffix(
char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append(openBrace);
AppendParameters(parameters, builder);
builder.Append(closeBrace);
return pooledBuilder.ToStringAndFree();
}
private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder)
{
var first = true;
foreach (var parameter in parameters)
{
if (!first)
{
builder.Append(", ");
}
foreach (var modifier in parameter.Modifiers)
{
builder.Append(modifier.Text);
builder.Append(' ');
}
if (parameter.Type != null)
{
AppendTokens(parameter.Type, builder);
}
else
{
builder.Append(parameter.Identifier.Text);
}
first = false;
}
}
protected override string GetContainerDisplayName(MemberDeclarationSyntax node)
=> CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters);
protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace)
=> CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces);
private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers)
{
var sawInternal = false;
foreach (var modifier in modifiers)
{
switch (modifier.Kind())
{
case SyntaxKind.PublicKeyword: return Accessibility.Public;
case SyntaxKind.PrivateKeyword: return Accessibility.Private;
case SyntaxKind.ProtectedKeyword: return Accessibility.Protected;
case SyntaxKind.InternalKeyword:
sawInternal = true;
continue;
}
}
if (sawInternal)
return Accessibility.Internal;
// No accessibility modifiers:
switch (container.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
// Anything without modifiers is private if it's in a class/struct declaration.
return Accessibility.Private;
case SyntaxKind.InterfaceDeclaration:
// Anything without modifiers is public if it's in an interface declaration.
return Accessibility.Public;
case SyntaxKind.CompilationUnit:
// Things are private by default in script
if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script)
return Accessibility.Private;
return Accessibility.Internal;
default:
// Otherwise it's internal
return Accessibility.Internal;
}
}
private static string GetTypeName(TypeSyntax type)
{
if (type is SimpleNameSyntax simpleName)
{
return GetSimpleTypeName(simpleName);
}
else if (type is QualifiedNameSyntax qualifiedName)
{
return GetSimpleTypeName(qualifiedName.Right);
}
else if (type is AliasQualifiedNameSyntax aliasName)
{
return GetSimpleTypeName(aliasName.Name);
}
return null;
}
private static string GetSimpleTypeName(SimpleNameSyntax name)
=> name.Identifier.ValueText;
private static bool IsExtensionMethod(MethodDeclarationSyntax method)
=> method.ParameterList.Parameters.Count > 0 &&
method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword);
// Root namespace is a VB only concept, which basically means root namespace is always global in C#.
protected override string GetRootNamespace(CompilationOptions compilationOptions)
=> string.Empty;
protected override bool TryGetAliasesFromUsingDirective(
UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases)
{
if (usingDirectiveNode.Alias != null)
{
if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) &&
TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _))
{
aliases = ImmutableArray.Create<(string, string)>((aliasName, name));
return true;
}
}
aliases = default;
return false;
}
protected override string GetReceiverTypeName(MemberDeclarationSyntax node)
{
var methodDeclaration = (MethodDeclarationSyntax)node;
Debug.Assert(IsExtensionMethod(methodDeclaration));
var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text);
TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray);
return CreateReceiverTypeString(targetTypeName, isArray);
}
private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray)
{
isArray = false;
if (node is TypeSyntax typeNode)
{
switch (typeNode)
{
case IdentifierNameSyntax identifierNameNode:
// We consider it a complex method if the receiver type is a type parameter.
var text = identifierNameNode.Identifier.Text;
simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text;
return simpleTypeName != null;
case ArrayTypeSyntax arrayTypeNode:
isArray = true;
return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _);
case GenericNameSyntax genericNameNode:
var name = genericNameNode.Identifier.Text;
var arity = genericNameNode.Arity;
simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity);
return true;
case PredefinedTypeSyntax predefinedTypeNode:
simpleTypeName = GetSpecialTypeName(predefinedTypeNode);
return simpleTypeName != null;
case AliasQualifiedNameSyntax aliasQualifiedNameNode:
return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _);
case QualifiedNameSyntax qualifiedNameNode:
// For an identifier to the right of a '.', it can't be a type parameter,
// so we don't need to check for it further.
return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _);
case NullableTypeSyntax nullableNode:
// Ignore nullability, becase nullable reference type might not be enabled universally.
// In the worst case we just include more methods to check in out filter.
return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray);
case TupleTypeSyntax tupleType:
simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count);
return true;
}
}
simpleTypeName = null;
return false;
}
private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode)
{
var kind = predefinedTypeNode.Keyword.Kind();
return kind switch
{
SyntaxKind.BoolKeyword => "Boolean",
SyntaxKind.ByteKeyword => "Byte",
SyntaxKind.SByteKeyword => "SByte",
SyntaxKind.ShortKeyword => "Int16",
SyntaxKind.UShortKeyword => "UInt16",
SyntaxKind.IntKeyword => "Int32",
SyntaxKind.UIntKeyword => "UInt32",
SyntaxKind.LongKeyword => "Int64",
SyntaxKind.ULongKeyword => "UInt64",
SyntaxKind.DoubleKeyword => "Double",
SyntaxKind.FloatKeyword => "Single",
SyntaxKind.DecimalKeyword => "Decimal",
SyntaxKind.StringKeyword => "String",
SyntaxKind.CharKeyword => "Char",
SyntaxKind.ObjectKeyword => "Object",
_ => null,
};
}
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/FindSymbols/Declarations/DeclarationFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal static partial class DeclarationFinder
{
private static Task AddCompilationDeclarationsWithNormalQueryAsync(
Project project, SearchQuery query, SymbolFilter filter,
ArrayBuilder<ISymbol> list, CancellationToken cancellationToken)
{
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
return AddCompilationDeclarationsWithNormalQueryAsync(
project, query, filter, list,
startingCompilation: null,
startingAssembly: null,
cancellationToken: cancellationToken);
}
private static async Task AddCompilationDeclarationsWithNormalQueryAsync(
Project project,
SearchQuery query,
SymbolFilter filter,
ArrayBuilder<ISymbol> list,
Compilation startingCompilation,
IAssemblySymbol startingAssembly,
CancellationToken cancellationToken)
{
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
using (Logger.LogBlock(FunctionId.SymbolFinder_Project_AddDeclarationsAsync, cancellationToken))
{
var syntaxFacts = project.LanguageServices.GetService<ISyntaxFactsService>();
// If this is an exact query, we can speed things up by just calling into the
// compilation entrypoints that take a string directly.
//
// the search is 'exact' if it's either an exact-case-sensitive search,
// or it's an exact-case-insensitive search and we're in a case-insensitive
// language.
var isExactNameSearch = query.Kind == SearchKind.Exact ||
(query.Kind == SearchKind.ExactIgnoreCase && !syntaxFacts.IsCaseSensitive);
// Note: we first call through the project. This has an optimization where it will
// use the DeclarationOnlyCompilation if we have one, avoiding needing to build the
// full compilation if we don't have that.
var containsSymbol = isExactNameSearch
? await project.ContainsSymbolsWithNameAsync(query.Name, filter, cancellationToken).ConfigureAwait(false)
: await project.ContainsSymbolsWithNameAsync(query.GetPredicate(), filter, cancellationToken).ConfigureAwait(false);
if (!containsSymbol)
{
return;
}
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var symbols = isExactNameSearch
? compilation.GetSymbolsWithName(query.Name, filter, cancellationToken)
: compilation.GetSymbolsWithName(query.GetPredicate(), filter, cancellationToken);
var symbolsWithName = symbols.ToImmutableArray();
if (startingCompilation != null && startingAssembly != null && !Equals(compilation.Assembly, startingAssembly))
{
// Return symbols from skeleton assembly in this case so that symbols have
// the same language as startingCompilation.
symbolsWithName = symbolsWithName.Select(s => s.GetSymbolKey(cancellationToken).Resolve(startingCompilation, cancellationToken: cancellationToken).Symbol)
.WhereNotNull()
.ToImmutableArray();
}
list.AddRange(FilterByCriteria(symbolsWithName, filter));
}
}
private static async Task AddMetadataDeclarationsWithNormalQueryAsync(
Project project, IAssemblySymbol assembly, PortableExecutableReference referenceOpt,
SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list,
CancellationToken cancellationToken)
{
// All entrypoints to this function are Find functions that are only searching
// for specific strings (i.e. they never do a custom search).
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
using (Logger.LogBlock(FunctionId.SymbolFinder_Assembly_AddDeclarationsAsync, cancellationToken))
{
if (referenceOpt != null)
{
var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync(
project.Solution, referenceOpt, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false);
var symbols = await info.FindAsync(
query, assembly, filter, cancellationToken).ConfigureAwait(false);
list.AddRange(symbols);
}
}
}
internal static ImmutableArray<ISymbol> FilterByCriteria(ImmutableArray<ISymbol> symbols, SymbolFilter criteria)
=> symbols.WhereAsArray(s => MeetCriteria(s, criteria));
private static bool MeetCriteria(ISymbol symbol, SymbolFilter filter)
{
if (!symbol.IsImplicitlyDeclared && !symbol.IsAccessor())
{
if (IsOn(filter, SymbolFilter.Namespace) && symbol.Kind == SymbolKind.Namespace)
{
return true;
}
if (IsOn(filter, SymbolFilter.Type) && symbol is ITypeSymbol)
{
return true;
}
if (IsOn(filter, SymbolFilter.Member) && IsNonTypeMember(symbol))
{
return true;
}
}
return false;
}
private static bool IsNonTypeMember(ISymbol symbol)
{
return symbol.Kind == SymbolKind.Method ||
symbol.Kind == SymbolKind.Property ||
symbol.Kind == SymbolKind.Event ||
symbol.Kind == SymbolKind.Field;
}
private static bool IsOn(SymbolFilter filter, SymbolFilter flag)
=> (filter & flag) == flag;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal static partial class DeclarationFinder
{
private static Task AddCompilationDeclarationsWithNormalQueryAsync(
Project project, SearchQuery query, SymbolFilter filter,
ArrayBuilder<ISymbol> list, CancellationToken cancellationToken)
{
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
return AddCompilationDeclarationsWithNormalQueryAsync(
project, query, filter, list,
startingCompilation: null,
startingAssembly: null,
cancellationToken: cancellationToken);
}
private static async Task AddCompilationDeclarationsWithNormalQueryAsync(
Project project,
SearchQuery query,
SymbolFilter filter,
ArrayBuilder<ISymbol> list,
Compilation startingCompilation,
IAssemblySymbol startingAssembly,
CancellationToken cancellationToken)
{
if (!project.SupportsCompilation)
return;
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
using (Logger.LogBlock(FunctionId.SymbolFinder_Project_AddDeclarationsAsync, cancellationToken))
{
var syntaxFacts = project.LanguageServices.GetService<ISyntaxFactsService>();
// If this is an exact query, we can speed things up by just calling into the
// compilation entrypoints that take a string directly.
//
// the search is 'exact' if it's either an exact-case-sensitive search,
// or it's an exact-case-insensitive search and we're in a case-insensitive
// language.
var isExactNameSearch = query.Kind == SearchKind.Exact ||
(query.Kind == SearchKind.ExactIgnoreCase && !syntaxFacts.IsCaseSensitive);
// Do a quick syntactic check first using our cheaply built indices. That will help us avoid creating
// a compilation here if it's not necessary. In the case of an exact name search we can call a special
// overload that quickly uses the direct bloom-filter identifier maps in the index. If it's nto an
// exact name search, then we will run the query's predicate over every DeclaredSymbolInfo stored in
// the doc.
var containsSymbol = isExactNameSearch
? await project.ContainsSymbolsWithNameAsync(query.Name, cancellationToken).ConfigureAwait(false)
: await project.ContainsSymbolsWithNameAsync(query.GetPredicate(), filter, cancellationToken).ConfigureAwait(false);
if (!containsSymbol)
return;
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var symbols = isExactNameSearch
? compilation.GetSymbolsWithName(query.Name, filter, cancellationToken)
: compilation.GetSymbolsWithName(query.GetPredicate(), filter, cancellationToken);
var symbolsWithName = symbols.ToImmutableArray();
if (startingCompilation != null && startingAssembly != null && !Equals(compilation.Assembly, startingAssembly))
{
// Return symbols from skeleton assembly in this case so that symbols have
// the same language as startingCompilation.
symbolsWithName = symbolsWithName.Select(s => s.GetSymbolKey(cancellationToken).Resolve(startingCompilation, cancellationToken: cancellationToken).Symbol)
.WhereNotNull()
.ToImmutableArray();
}
list.AddRange(FilterByCriteria(symbolsWithName, filter));
}
}
private static async Task AddMetadataDeclarationsWithNormalQueryAsync(
Project project, IAssemblySymbol assembly, PortableExecutableReference referenceOpt,
SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list,
CancellationToken cancellationToken)
{
// All entrypoints to this function are Find functions that are only searching
// for specific strings (i.e. they never do a custom search).
Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API");
using (Logger.LogBlock(FunctionId.SymbolFinder_Assembly_AddDeclarationsAsync, cancellationToken))
{
if (referenceOpt != null)
{
var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync(
project.Solution, referenceOpt, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false);
var symbols = await info.FindAsync(
query, assembly, filter, cancellationToken).ConfigureAwait(false);
list.AddRange(symbols);
}
}
}
internal static ImmutableArray<ISymbol> FilterByCriteria(ImmutableArray<ISymbol> symbols, SymbolFilter criteria)
=> symbols.WhereAsArray(s => MeetCriteria(s, criteria));
private static bool MeetCriteria(ISymbol symbol, SymbolFilter filter)
{
if (!symbol.IsImplicitlyDeclared && !symbol.IsAccessor())
{
if (IsOn(filter, SymbolFilter.Namespace) && symbol.Kind == SymbolKind.Namespace)
{
return true;
}
if (IsOn(filter, SymbolFilter.Type) && symbol is ITypeSymbol)
{
return true;
}
if (IsOn(filter, SymbolFilter.Member) && IsNonTypeMember(symbol))
{
return true;
}
}
return false;
}
private static bool IsNonTypeMember(ISymbol symbol)
{
return symbol.Kind == SymbolKind.Method ||
symbol.Kind == SymbolKind.Property ||
symbol.Kind == SymbolKind.Event ||
symbol.Kind == SymbolKind.Field;
}
private static bool IsOn(SymbolFilter filter, SymbolFilter flag)
=> (filter & flag) == flag;
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/FindSymbols/DeclaredSymbolInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeAnalysis;
using System.Runtime.Serialization;
using System.Threading;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal enum DeclaredSymbolInfoKind : byte
{
Class,
Constant,
Constructor,
Delegate,
Enum,
EnumMember,
Event,
ExtensionMethod,
Field,
Indexer,
Interface,
Method,
Module,
Property,
Record,
RecordStruct,
Struct,
}
[DataContract]
internal readonly struct DeclaredSymbolInfo : IEquatable<DeclaredSymbolInfo>
{
/// <summary>
/// The name to pattern match against, and to show in a final presentation layer.
/// </summary>
[DataMember(Order = 0)]
public readonly string Name;
/// <summary>
/// An optional suffix to be shown in a presentation layer appended to <see cref="Name"/>.
/// Can be null.
/// </summary>
[DataMember(Order = 1)]
public readonly string NameSuffix;
/// <summary>
/// Container of the symbol that can be shown in a final presentation layer.
/// For example, the container of a type "KeyValuePair" might be
/// "System.Collections.Generic.Dictionary<TKey, TValue>". This can
/// then be shown with something like "type System.Collections.Generic.Dictionary<TKey, TValue>"
/// to indicate where the symbol is located.
/// </summary>
[DataMember(Order = 2)]
public readonly string ContainerDisplayName;
/// <summary>
/// Dotted container name of the symbol, used for pattern matching. For example
/// The fully qualified container of a type "KeyValuePair" would be
/// "System.Collections.Generic.Dictionary" (note the lack of type parameters).
/// This way someone can search for "D.KVP" and have the "D" part of the pattern
/// match against this. This should not be shown in a presentation layer.
/// </summary>
[DataMember(Order = 3)]
public readonly string FullyQualifiedContainerName;
[DataMember(Order = 4)]
public readonly TextSpan Span;
/// <summary>
/// The names directly referenced in source that this type inherits from.
/// </summary>
[DataMember(Order = 5)]
public ImmutableArray<string> InheritanceNames { get; }
// Store the kind (5 bits), accessibility (4 bits), parameter-count (4 bits), and type-parameter-count (4 bits)
// in a single int.
[DataMember(Order = 6)]
private readonly uint _flags;
private const uint Lower4BitMask = 0b1111;
private const uint Lower5BitMask = 0b11111;
public DeclaredSymbolInfoKind Kind => GetKind(_flags);
public Accessibility Accessibility => GetAccessibility(_flags);
public byte ParameterCount => GetParameterCount(_flags);
public byte TypeParameterCount => GetTypeParameterCount(_flags);
public bool IsNestedType => GetIsNestedType(_flags);
public bool IsPartial => GetIsPartial(_flags);
[Obsolete("Do not call directly. Only around for serialization. Use Create instead")]
public DeclaredSymbolInfo(
string name,
string nameSuffix,
string containerDisplayName,
string fullyQualifiedContainerName,
TextSpan span,
ImmutableArray<string> inheritanceNames,
uint flags)
{
Name = name;
NameSuffix = nameSuffix;
ContainerDisplayName = containerDisplayName;
FullyQualifiedContainerName = fullyQualifiedContainerName;
Span = span;
InheritanceNames = inheritanceNames;
_flags = flags;
}
public static DeclaredSymbolInfo Create(
StringTable stringTable,
string name,
string nameSuffix,
string containerDisplayName,
string fullyQualifiedContainerName,
bool isPartial,
DeclaredSymbolInfoKind kind,
Accessibility accessibility,
TextSpan span,
ImmutableArray<string> inheritanceNames,
bool isNestedType = false, int parameterCount = 0, int typeParameterCount = 0)
{
const uint MaxFlagValue5 = 0b10000;
const uint MaxFlagValue4 = 0b1111;
Contract.ThrowIfTrue((uint)accessibility > MaxFlagValue4);
Contract.ThrowIfTrue((uint)kind > MaxFlagValue5);
parameterCount = Math.Min(parameterCount, (byte)MaxFlagValue4);
typeParameterCount = Math.Min(typeParameterCount, (byte)MaxFlagValue4);
var flags =
(uint)kind |
((uint)accessibility << 5) |
((uint)parameterCount << 9) |
((uint)typeParameterCount << 13) |
((isNestedType ? 1u : 0u) << 17) |
((isPartial ? 1u : 0u) << 18);
#pragma warning disable CS0618 // Type or member is obsolete
return new DeclaredSymbolInfo(
Intern(stringTable, name),
Intern(stringTable, nameSuffix),
Intern(stringTable, containerDisplayName),
Intern(stringTable, fullyQualifiedContainerName),
span,
inheritanceNames,
flags);
#pragma warning restore CS0618 // Type or member is obsolete
}
[return: NotNullIfNotNull("name")]
public static string? Intern(StringTable stringTable, string? name)
=> name == null ? null : stringTable.Add(name);
private static DeclaredSymbolInfoKind GetKind(uint flags)
=> (DeclaredSymbolInfoKind)(flags & Lower5BitMask);
private static Accessibility GetAccessibility(uint flags)
=> (Accessibility)((flags >> 5) & Lower4BitMask);
private static byte GetParameterCount(uint flags)
=> (byte)((flags >> 9) & Lower4BitMask);
private static byte GetTypeParameterCount(uint flags)
=> (byte)((flags >> 13) & Lower4BitMask);
private static bool GetIsNestedType(uint flags)
=> ((flags >> 17) & 1) == 1;
private static bool GetIsPartial(uint flags)
=> ((flags >> 18) & 1) == 1;
internal void WriteTo(ObjectWriter writer)
{
writer.WriteString(Name);
writer.WriteString(NameSuffix);
writer.WriteString(ContainerDisplayName);
writer.WriteString(FullyQualifiedContainerName);
writer.WriteUInt32(_flags);
writer.WriteInt32(Span.Start);
writer.WriteInt32(Span.Length);
writer.WriteInt32(InheritanceNames.Length);
foreach (var name in InheritanceNames)
writer.WriteString(name);
}
internal static DeclaredSymbolInfo ReadFrom_ThrowsOnFailure(StringTable stringTable, ObjectReader reader)
{
var name = reader.ReadString();
var nameSuffix = reader.ReadString();
var containerDisplayName = reader.ReadString();
var fullyQualifiedContainerName = reader.ReadString();
var flags = reader.ReadUInt32();
var spanStart = reader.ReadInt32();
var spanLength = reader.ReadInt32();
var inheritanceNamesLength = reader.ReadInt32();
var builder = ArrayBuilder<string>.GetInstance(inheritanceNamesLength);
for (var i = 0; i < inheritanceNamesLength; i++)
builder.Add(reader.ReadString());
var span = new TextSpan(spanStart, spanLength);
return Create(
stringTable,
name: name,
nameSuffix: nameSuffix,
containerDisplayName: containerDisplayName,
fullyQualifiedContainerName: fullyQualifiedContainerName,
isPartial: GetIsPartial(flags),
kind: GetKind(flags),
accessibility: GetAccessibility(flags),
span: span,
inheritanceNames: builder.ToImmutableAndFree(),
parameterCount: GetParameterCount(flags),
typeParameterCount: GetTypeParameterCount(flags));
}
public ISymbol? TryResolve(SemanticModel semanticModel, CancellationToken cancellationToken)
{
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
if (root.FullSpan.Contains(this.Span))
{
var node = root.FindNode(this.Span);
return semanticModel.GetDeclaredSymbol(node, cancellationToken);
}
else
{
var message =
$@"Invalid span in {nameof(DeclaredSymbolInfo)}.
{nameof(this.Span)} = {this.Span}
{nameof(root.FullSpan)} = {root.FullSpan}";
FatalError.ReportAndCatch(new InvalidOperationException(message));
return null;
}
}
public override bool Equals(object? obj)
=> obj is DeclaredSymbolInfo info && Equals(info);
public bool Equals(DeclaredSymbolInfo other)
=> Name == other.Name
&& NameSuffix == other.NameSuffix
&& ContainerDisplayName == other.ContainerDisplayName
&& FullyQualifiedContainerName == other.FullyQualifiedContainerName
&& Span.Equals(other.Span)
&& _flags == other._flags
&& InheritanceNames.SequenceEqual(other.InheritanceNames, arg: true, (s1, s2, _) => s1 == s2);
public override int GetHashCode()
=> Hash.Combine(Name,
Hash.Combine(NameSuffix,
Hash.Combine(ContainerDisplayName,
Hash.Combine(FullyQualifiedContainerName,
Hash.Combine(Span.GetHashCode(),
Hash.Combine((int)_flags,
Hash.CombineValues(InheritanceNames)))))));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeAnalysis;
using System.Runtime.Serialization;
using System.Threading;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal enum DeclaredSymbolInfoKind : byte
{
Class,
Constant,
Constructor,
Delegate,
Enum,
EnumMember,
Event,
ExtensionMethod,
Field,
Indexer,
Interface,
Method,
Module,
Namespace,
Property,
Record,
RecordStruct,
Struct,
}
[DataContract]
internal readonly struct DeclaredSymbolInfo : IEquatable<DeclaredSymbolInfo>
{
/// <summary>
/// The name to pattern match against, and to show in a final presentation layer.
/// </summary>
[DataMember(Order = 0)]
public readonly string Name;
/// <summary>
/// An optional suffix to be shown in a presentation layer appended to <see cref="Name"/>.
/// Can be null.
/// </summary>
[DataMember(Order = 1)]
public readonly string NameSuffix;
/// <summary>
/// Container of the symbol that can be shown in a final presentation layer.
/// For example, the container of a type "KeyValuePair" might be
/// "System.Collections.Generic.Dictionary<TKey, TValue>". This can
/// then be shown with something like "type System.Collections.Generic.Dictionary<TKey, TValue>"
/// to indicate where the symbol is located.
/// </summary>
[DataMember(Order = 2)]
public readonly string ContainerDisplayName;
/// <summary>
/// Dotted container name of the symbol, used for pattern matching. For example
/// The fully qualified container of a type "KeyValuePair" would be
/// "System.Collections.Generic.Dictionary" (note the lack of type parameters).
/// This way someone can search for "D.KVP" and have the "D" part of the pattern
/// match against this. This should not be shown in a presentation layer.
/// </summary>
[DataMember(Order = 3)]
public readonly string FullyQualifiedContainerName;
[DataMember(Order = 4)]
public readonly TextSpan Span;
/// <summary>
/// The names directly referenced in source that this type inherits from.
/// </summary>
[DataMember(Order = 5)]
public ImmutableArray<string> InheritanceNames { get; }
// Store the kind (5 bits), accessibility (4 bits), parameter-count (4 bits), and type-parameter-count (4 bits)
// in a single int.
[DataMember(Order = 6)]
private readonly uint _flags;
private const uint Lower4BitMask = 0b1111;
private const uint Lower5BitMask = 0b11111;
public DeclaredSymbolInfoKind Kind => GetKind(_flags);
public Accessibility Accessibility => GetAccessibility(_flags);
public byte ParameterCount => GetParameterCount(_flags);
public byte TypeParameterCount => GetTypeParameterCount(_flags);
public bool IsNestedType => GetIsNestedType(_flags);
public bool IsPartial => GetIsPartial(_flags);
[Obsolete("Do not call directly. Only around for serialization. Use Create instead")]
public DeclaredSymbolInfo(
string name,
string nameSuffix,
string containerDisplayName,
string fullyQualifiedContainerName,
TextSpan span,
ImmutableArray<string> inheritanceNames,
uint flags)
{
Name = name;
NameSuffix = nameSuffix;
ContainerDisplayName = containerDisplayName;
FullyQualifiedContainerName = fullyQualifiedContainerName;
Span = span;
InheritanceNames = inheritanceNames;
_flags = flags;
}
public static DeclaredSymbolInfo Create(
StringTable stringTable,
string name,
string nameSuffix,
string containerDisplayName,
string fullyQualifiedContainerName,
bool isPartial,
DeclaredSymbolInfoKind kind,
Accessibility accessibility,
TextSpan span,
ImmutableArray<string> inheritanceNames,
bool isNestedType = false,
int parameterCount = 0,
int typeParameterCount = 0)
{
// Max value that we can store depending on how many bits we have to store that particular value in.
const uint Max5BitValue = 0b11111;
const uint Max4BitValue = 0b1111;
Contract.ThrowIfTrue((uint)accessibility > Max4BitValue);
Contract.ThrowIfTrue((uint)kind > Max5BitValue);
parameterCount = Math.Min(parameterCount, (byte)Max4BitValue);
typeParameterCount = Math.Min(typeParameterCount, (byte)Max4BitValue);
var flags =
(uint)kind |
((uint)accessibility << 5) |
((uint)parameterCount << 9) |
((uint)typeParameterCount << 13) |
((isNestedType ? 1u : 0u) << 17) |
((isPartial ? 1u : 0u) << 18);
#pragma warning disable CS0618 // Type or member is obsolete
return new DeclaredSymbolInfo(
Intern(stringTable, name),
Intern(stringTable, nameSuffix),
Intern(stringTable, containerDisplayName),
Intern(stringTable, fullyQualifiedContainerName),
span,
inheritanceNames,
flags);
#pragma warning restore CS0618 // Type or member is obsolete
}
[return: NotNullIfNotNull("name")]
public static string? Intern(StringTable stringTable, string? name)
=> name == null ? null : stringTable.Add(name);
private static DeclaredSymbolInfoKind GetKind(uint flags)
=> (DeclaredSymbolInfoKind)(flags & Lower5BitMask);
private static Accessibility GetAccessibility(uint flags)
=> (Accessibility)((flags >> 5) & Lower4BitMask);
private static byte GetParameterCount(uint flags)
=> (byte)((flags >> 9) & Lower4BitMask);
private static byte GetTypeParameterCount(uint flags)
=> (byte)((flags >> 13) & Lower4BitMask);
private static bool GetIsNestedType(uint flags)
=> ((flags >> 17) & 1) == 1;
private static bool GetIsPartial(uint flags)
=> ((flags >> 18) & 1) == 1;
internal void WriteTo(ObjectWriter writer)
{
writer.WriteString(Name);
writer.WriteString(NameSuffix);
writer.WriteString(ContainerDisplayName);
writer.WriteString(FullyQualifiedContainerName);
writer.WriteUInt32(_flags);
writer.WriteInt32(Span.Start);
writer.WriteInt32(Span.Length);
writer.WriteInt32(InheritanceNames.Length);
foreach (var name in InheritanceNames)
writer.WriteString(name);
}
internal static DeclaredSymbolInfo ReadFrom_ThrowsOnFailure(StringTable stringTable, ObjectReader reader)
{
var name = reader.ReadString();
var nameSuffix = reader.ReadString();
var containerDisplayName = reader.ReadString();
var fullyQualifiedContainerName = reader.ReadString();
var flags = reader.ReadUInt32();
var spanStart = reader.ReadInt32();
var spanLength = reader.ReadInt32();
var inheritanceNamesLength = reader.ReadInt32();
var builder = ArrayBuilder<string>.GetInstance(inheritanceNamesLength);
for (var i = 0; i < inheritanceNamesLength; i++)
builder.Add(reader.ReadString());
var span = new TextSpan(spanStart, spanLength);
return Create(
stringTable,
name: name,
nameSuffix: nameSuffix,
containerDisplayName: containerDisplayName,
fullyQualifiedContainerName: fullyQualifiedContainerName,
isPartial: GetIsPartial(flags),
kind: GetKind(flags),
accessibility: GetAccessibility(flags),
span: span,
inheritanceNames: builder.ToImmutableAndFree(),
parameterCount: GetParameterCount(flags),
typeParameterCount: GetTypeParameterCount(flags));
}
public ISymbol? TryResolve(SemanticModel semanticModel, CancellationToken cancellationToken)
{
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
if (root.FullSpan.Contains(this.Span))
{
var node = root.FindNode(this.Span);
return semanticModel.GetDeclaredSymbol(node, cancellationToken);
}
else
{
var message =
$@"Invalid span in {nameof(DeclaredSymbolInfo)}.
{nameof(this.Span)} = {this.Span}
{nameof(root.FullSpan)} = {root.FullSpan}";
FatalError.ReportAndCatch(new InvalidOperationException(message));
return null;
}
}
public override bool Equals(object? obj)
=> obj is DeclaredSymbolInfo info && Equals(info);
public bool Equals(DeclaredSymbolInfo other)
=> Name == other.Name
&& NameSuffix == other.NameSuffix
&& ContainerDisplayName == other.ContainerDisplayName
&& FullyQualifiedContainerName == other.FullyQualifiedContainerName
&& Span.Equals(other.Span)
&& _flags == other._flags
&& InheritanceNames.SequenceEqual(other.InheritanceNames, arg: true, (s1, s2, _) => s1 == s2);
public override int GetHashCode()
=> Hash.Combine(Name,
Hash.Combine(NameSuffix,
Hash.Combine(ContainerDisplayName,
Hash.Combine(FullyQualifiedContainerName,
Hash.Combine(Span.GetHashCode(),
Hash.Combine((int)_flags,
Hash.CombineValues(InheritanceNames)))))));
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Persistence.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Host;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal sealed partial class SyntaxTreeIndex : IObjectWritable
{
private const string PersistenceName = "<SyntaxTreeIndex>";
private static readonly Checksum SerializationFormatChecksum = Checksum.Create("22");
public readonly Checksum? Checksum;
private static Task<SyntaxTreeIndex?> LoadAsync(Document document, Checksum checksum, CancellationToken cancellationToken)
=> LoadAsync(document.Project.Solution.Workspace, DocumentKey.ToDocumentKey(document), checksum, GetStringTable(document.Project), cancellationToken);
public static async Task<SyntaxTreeIndex?> LoadAsync(
Workspace workspace, DocumentKey documentKey, Checksum? checksum, StringTable stringTable, CancellationToken cancellationToken)
{
try
{
var persistentStorageService = (IChecksummedPersistentStorageService)workspace.Services.GetRequiredService<IPersistentStorageService>();
var storage = await persistentStorageService.GetStorageAsync(
workspace, documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
// attempt to load from persisted state
using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false);
using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken);
if (reader != null)
return ReadFrom(stringTable, reader, checksum);
}
catch (Exception e) when (IOUtilities.IsNormalIOException(e))
{
// Storage APIs can throw arbitrary exceptions.
}
return null;
}
public static async Task<Checksum> GetChecksumAsync(
Document document, CancellationToken cancellationToken)
{
// Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change
// any time the SyntaxTree could have changed. Right now, that can only happen if the
// text of the document changes, or the ParseOptions change. So we get the checksums
// for both of those, and merge them together to make the final checksum.
//
// We also want the checksum to change any time our serialization format changes. If
// the format has changed, all previous versions should be invalidated.
var project = document.Project;
var parseOptionsChecksum = project.State.GetParseOptionsChecksum();
var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false);
var textChecksum = documentChecksumState.Text;
return Checksum.Create(textChecksum, parseOptionsChecksum, SerializationFormatChecksum);
}
private async Task<bool> SaveAsync(
Document document, CancellationToken cancellationToken)
{
var solution = document.Project.Solution;
var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>();
try
{
var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken))
{
WriteTo(writer);
}
stream.Position = 0;
return await storage.WriteStreamAsync(document, PersistenceName, stream, this.Checksum, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (IOUtilities.IsNormalIOException(e))
{
// Storage APIs can throw arbitrary exceptions.
}
return false;
}
private static async Task<bool> PrecalculatedAsync(
Document document, Checksum checksum, CancellationToken cancellationToken)
{
var solution = document.Project.Solution;
var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>();
// check whether we already have info for this document
try
{
var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
// Check if we've already stored a checksum and it matches the checksum we
// expect. If so, we're already precalculated and don't have to recompute
// this index. Otherwise if we don't have a checksum, or the checksums don't
// match, go ahead and recompute it.
return await storage.ChecksumMatchesAsync(document, PersistenceName, checksum, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (IOUtilities.IsNormalIOException(e))
{
// Storage APIs can throw arbitrary exceptions.
}
return false;
}
bool IObjectWritable.ShouldReuseInSerialization => true;
public void WriteTo(ObjectWriter writer)
{
_literalInfo.WriteTo(writer);
_identifierInfo.WriteTo(writer);
_contextInfo.WriteTo(writer);
_declarationInfo.WriteTo(writer);
_extensionMethodInfo.WriteTo(writer);
}
private static SyntaxTreeIndex? ReadFrom(
StringTable stringTable, ObjectReader reader, Checksum? checksum)
{
var literalInfo = LiteralInfo.TryReadFrom(reader);
var identifierInfo = IdentifierInfo.TryReadFrom(reader);
var contextInfo = ContextInfo.TryReadFrom(reader);
var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader);
var extensionMethodInfo = ExtensionMethodInfo.TryReadFrom(reader);
if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null || extensionMethodInfo == null)
{
return null;
}
return new SyntaxTreeIndex(
checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value, extensionMethodInfo.Value);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal sealed partial class SyntaxTreeIndex : IObjectWritable
{
private const string PersistenceName = "<SyntaxTreeIndex>";
private static readonly Checksum SerializationFormatChecksum = Checksum.Create("23");
public readonly Checksum? Checksum;
private static Task<SyntaxTreeIndex?> LoadAsync(Document document, Checksum checksum, CancellationToken cancellationToken)
=> LoadAsync(document.Project.Solution.Workspace, DocumentKey.ToDocumentKey(document), checksum, GetStringTable(document.Project), cancellationToken);
public static async Task<SyntaxTreeIndex?> LoadAsync(
Workspace workspace, DocumentKey documentKey, Checksum? checksum, StringTable stringTable, CancellationToken cancellationToken)
{
try
{
var persistentStorageService = (IChecksummedPersistentStorageService)workspace.Services.GetRequiredService<IPersistentStorageService>();
var storage = await persistentStorageService.GetStorageAsync(
workspace, documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
// attempt to load from persisted state
using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false);
using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken);
if (reader != null)
return ReadFrom(stringTable, reader, checksum);
}
catch (Exception e) when (IOUtilities.IsNormalIOException(e))
{
// Storage APIs can throw arbitrary exceptions.
}
return null;
}
public static async Task<Checksum> GetChecksumAsync(
Document document, CancellationToken cancellationToken)
{
// Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change
// any time the SyntaxTree could have changed. Right now, that can only happen if the
// text of the document changes, or the ParseOptions change. So we get the checksums
// for both of those, and merge them together to make the final checksum.
//
// We also want the checksum to change any time our serialization format changes. If
// the format has changed, all previous versions should be invalidated.
var project = document.Project;
var parseOptionsChecksum = project.State.GetParseOptionsChecksum();
var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false);
var textChecksum = documentChecksumState.Text;
return Checksum.Create(textChecksum, parseOptionsChecksum, SerializationFormatChecksum);
}
private async Task<bool> SaveAsync(
Document document, CancellationToken cancellationToken)
{
var solution = document.Project.Solution;
var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>();
try
{
var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken))
{
WriteTo(writer);
}
stream.Position = 0;
return await storage.WriteStreamAsync(document, PersistenceName, stream, this.Checksum, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (IOUtilities.IsNormalIOException(e))
{
// Storage APIs can throw arbitrary exceptions.
}
return false;
}
private static async Task<bool> PrecalculatedAsync(
Document document, Checksum checksum, CancellationToken cancellationToken)
{
var solution = document.Project.Solution;
var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>();
// check whether we already have info for this document
try
{
var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
// Check if we've already stored a checksum and it matches the checksum we
// expect. If so, we're already precalculated and don't have to recompute
// this index. Otherwise if we don't have a checksum, or the checksums don't
// match, go ahead and recompute it.
return await storage.ChecksumMatchesAsync(document, PersistenceName, checksum, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (IOUtilities.IsNormalIOException(e))
{
// Storage APIs can throw arbitrary exceptions.
}
return false;
}
bool IObjectWritable.ShouldReuseInSerialization => true;
public void WriteTo(ObjectWriter writer)
{
_literalInfo.WriteTo(writer);
_identifierInfo.WriteTo(writer);
_contextInfo.WriteTo(writer);
_declarationInfo.WriteTo(writer);
_extensionMethodInfo.WriteTo(writer);
}
private static SyntaxTreeIndex? ReadFrom(
StringTable stringTable, ObjectReader reader, Checksum? checksum)
{
var literalInfo = LiteralInfo.TryReadFrom(reader);
var identifierInfo = IdentifierInfo.TryReadFrom(reader);
var contextInfo = ContextInfo.TryReadFrom(reader);
var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader);
var extensionMethodInfo = ExtensionMethodInfo.TryReadFrom(reader);
if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null || extensionMethodInfo == null)
{
return null;
}
return new SyntaxTreeIndex(
checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value, extensionMethodInfo.Value);
}
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/LanguageServices/DeclaredSymbolFactoryService/AbstractDeclaredSymbolInfoFactoryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractDeclaredSymbolInfoFactoryService<
TCompilationUnitSyntax,
TUsingDirectiveSyntax,
TNamespaceDeclarationSyntax,
TTypeDeclarationSyntax,
TEnumDeclarationSyntax,
TMemberDeclarationSyntax> : IDeclaredSymbolInfoFactoryService
where TCompilationUnitSyntax : SyntaxNode
where TUsingDirectiveSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax
where TTypeDeclarationSyntax : TMemberDeclarationSyntax
where TEnumDeclarationSyntax : TMemberDeclarationSyntax
where TMemberDeclarationSyntax : SyntaxNode
{
private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool
= SharedPools.Default<List<Dictionary<string, string>>>();
// Note: these names are stored case insensitively. That way the alias mapping works
// properly for VB. It will mean that our inheritance maps may store more links in them
// for C#. However, that's ok. It will be rare in practice, and all it means is that
// we'll end up examining slightly more types (likely 0) when doing operations like
// Find all references.
private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool
= SharedPools.StringIgnoreCaseDictionary<string>();
protected AbstractDeclaredSymbolInfoFactoryService()
{
}
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node);
protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node);
protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration);
protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace);
protected abstract void AddDeclaredSymbolInfosWorker(
SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken);
/// <summary>
/// Get the name of the target type of specified extension method declaration.
/// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()`
/// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`.
/// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>).
/// </summary>
protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node);
protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases);
protected abstract string GetRootNamespace(CompilationOptions compilationOptions);
protected static List<Dictionary<string, string>> AllocateAliasMapList()
=> s_aliasMapListPool.Allocate();
// We do not differentiate arrays of different kinds for simplicity.
// e.g. int[], int[][], int[,], etc. are all represented as int[] in the index.
protected static string CreateReceiverTypeString(string typeName, bool isArray)
{
if (string.IsNullOrEmpty(typeName))
{
return isArray
? FindSymbols.Extensions.ComplexArrayReceiverTypeName
: FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
return isArray
? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix
: typeName;
}
}
protected static string CreateValueTupleTypeString(int elementCount)
{
const string ValueTupleName = "ValueTuple";
if (elementCount == 0)
{
return ValueTupleName;
}
// A ValueTuple can have up to 8 type parameters.
return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount);
}
protected static void FreeAliasMapList(List<Dictionary<string, string>> list)
{
if (list != null)
{
foreach (var aliasMap in list)
{
FreeAliasMap(aliasMap);
}
s_aliasMapListPool.ClearAndFree(list);
}
}
protected static void FreeAliasMap(Dictionary<string, string> aliasMap)
{
if (aliasMap != null)
{
s_aliasMapPool.ClearAndFree(aliasMap);
}
}
protected static Dictionary<string, string> AllocateAliasMap()
=> s_aliasMapPool.Allocate();
protected static void AppendTokens(SyntaxNode node, StringBuilder builder)
{
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsToken)
{
builder.Append(child.AsToken().Text);
}
else
{
AppendTokens(child.AsNode(), builder);
}
}
}
protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder)
{
for (int i = 0, n = builder.Count; i < n; i++)
{
builder[i] = stringTable.Add(builder[i]);
}
}
public void AddDeclaredSymbolInfos(
Document document,
SyntaxNode root,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
CancellationToken cancellationToken)
{
var project = document.Project;
var stringTable = SyntaxTreeIndex.GetStringTable(project);
var rootNamespace = this.GetRootNamespace(project.CompilationOptions);
using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases);
foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren((TCompilationUnitSyntax)root))
AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken);
}
private void AddDeclaredSymbolInfos(
SyntaxNode container,
TMemberDeclarationSyntax memberDeclaration,
StringTable stringTable,
string rootNamespace,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, string> aliases,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
string containerDisplayName,
string fullyQualifiedContainerName,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var usingAlias in GetUsingAliases(namespaceDeclaration))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren(namespaceDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(baseTypeDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(enumDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
AddDeclaredSymbolInfosWorker(
container,
memberDeclaration,
stringTable,
declaredSymbolInfos,
aliases,
extensionMethodInfo,
containerDisplayName,
fullyQualifiedContainerName,
cancellationToken);
}
protected void AddExtensionMethodInfo(
TMemberDeclarationSyntax node,
Dictionary<string, string> aliases,
int declaredSymbolInfoIndex,
Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder)
{
var receiverTypeName = this.GetReceiverTypeName(node);
// Target type is an alias
if (aliases.TryGetValue(receiverTypeName, out var originalName))
{
// it is an alias of multiple with identical name,
// simply treat it as a complex method.
if (originalName == null)
{
receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
// replace the alias with its original name.
receiverTypeName = originalName;
}
}
if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder))
{
arrayBuilder = ArrayBuilder<int>.GetInstance();
extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder;
}
arrayBuilder.Add(declaredSymbolInfoIndex);
}
private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases)
{
foreach (var (aliasName, name) in aliases)
{
// In C#, it's valid to declare two alias with identical name,
// as long as they are in different containers.
//
// e.g.
// using X = System.String;
// namespace N
// {
// using X = System.Int32;
// }
//
// If we detect this, we will simply treat extension methods whose
// target type is this alias as complex method.
if (allAliases.ContainsKey(aliasName))
{
allAliases[aliasName] = null;
}
else
{
allAliases[aliasName] = name;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractDeclaredSymbolInfoFactoryService<
TCompilationUnitSyntax,
TUsingDirectiveSyntax,
TNamespaceDeclarationSyntax,
TTypeDeclarationSyntax,
TEnumDeclarationSyntax,
TMemberDeclarationSyntax,
TNameSyntax,
TQualifiedNameSyntax,
TIdentifierNameSyntax> : IDeclaredSymbolInfoFactoryService
where TCompilationUnitSyntax : SyntaxNode
where TUsingDirectiveSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax
where TTypeDeclarationSyntax : TMemberDeclarationSyntax
where TEnumDeclarationSyntax : TMemberDeclarationSyntax
where TMemberDeclarationSyntax : SyntaxNode
where TNameSyntax : SyntaxNode
where TQualifiedNameSyntax : TNameSyntax
where TIdentifierNameSyntax : TNameSyntax
{
private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool
= SharedPools.Default<List<Dictionary<string, string>>>();
// Note: these names are stored case insensitively. That way the alias mapping works
// properly for VB. It will mean that our inheritance maps may store more links in them
// for C#. However, that's ok. It will be rare in practice, and all it means is that
// we'll end up examining slightly more types (likely 0) when doing operations like
// Find all references.
private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool
= SharedPools.StringIgnoreCaseDictionary<string>();
protected AbstractDeclaredSymbolInfoFactoryService()
{
}
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node);
protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node);
protected abstract TNameSyntax GetName(TNamespaceDeclarationSyntax node);
protected abstract TNameSyntax GetLeft(TQualifiedNameSyntax node);
protected abstract TNameSyntax GetRight(TQualifiedNameSyntax node);
protected abstract SyntaxToken GetIdentifier(TIdentifierNameSyntax node);
protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration);
protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace);
protected abstract void AddDeclaredSymbolInfosWorker(
SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken);
/// <summary>
/// Get the name of the target type of specified extension method declaration.
/// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()`
/// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`.
/// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>).
/// </summary>
protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node);
protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases);
protected abstract string GetRootNamespace(CompilationOptions compilationOptions);
protected static List<Dictionary<string, string>> AllocateAliasMapList()
=> s_aliasMapListPool.Allocate();
// We do not differentiate arrays of different kinds for simplicity.
// e.g. int[], int[][], int[,], etc. are all represented as int[] in the index.
protected static string CreateReceiverTypeString(string typeName, bool isArray)
{
if (string.IsNullOrEmpty(typeName))
{
return isArray
? FindSymbols.Extensions.ComplexArrayReceiverTypeName
: FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
return isArray
? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix
: typeName;
}
}
protected static string CreateValueTupleTypeString(int elementCount)
{
const string ValueTupleName = "ValueTuple";
if (elementCount == 0)
{
return ValueTupleName;
}
// A ValueTuple can have up to 8 type parameters.
return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount);
}
protected static void FreeAliasMapList(List<Dictionary<string, string>> list)
{
if (list != null)
{
foreach (var aliasMap in list)
{
FreeAliasMap(aliasMap);
}
s_aliasMapListPool.ClearAndFree(list);
}
}
protected static void FreeAliasMap(Dictionary<string, string> aliasMap)
{
if (aliasMap != null)
{
s_aliasMapPool.ClearAndFree(aliasMap);
}
}
protected static Dictionary<string, string> AllocateAliasMap()
=> s_aliasMapPool.Allocate();
protected static void AppendTokens(SyntaxNode node, StringBuilder builder)
{
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsToken)
{
builder.Append(child.AsToken().Text);
}
else
{
AppendTokens(child.AsNode(), builder);
}
}
}
protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder)
{
for (int i = 0, n = builder.Count; i < n; i++)
{
builder[i] = stringTable.Add(builder[i]);
}
}
public void AddDeclaredSymbolInfos(
Document document,
SyntaxNode root,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
CancellationToken cancellationToken)
{
var project = document.Project;
var stringTable = SyntaxTreeIndex.GetStringTable(project);
var rootNamespace = this.GetRootNamespace(project.CompilationOptions);
using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases);
foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren((TCompilationUnitSyntax)root))
AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken);
}
private void AddDeclaredSymbolInfos(
SyntaxNode container,
TMemberDeclarationSyntax memberDeclaration,
StringTable stringTable,
string rootNamespace,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, string> aliases,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
string containerDisplayName,
string fullyQualifiedContainerName,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration)
{
AddNamespaceDeclaredSymbolInfos(GetName(namespaceDeclaration), fullyQualifiedContainerName);
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var usingAlias in GetUsingAliases(namespaceDeclaration))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren(namespaceDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(baseTypeDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(enumDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
AddDeclaredSymbolInfosWorker(
container,
memberDeclaration,
stringTable,
declaredSymbolInfos,
aliases,
extensionMethodInfo,
containerDisplayName,
fullyQualifiedContainerName,
cancellationToken);
return;
// Returns the new fully-qualified-container-name built from fullyQualifiedContainerName
// with all the pieces of 'name' added to the end of it.
string AddNamespaceDeclaredSymbolInfos(TNameSyntax name, string fullyQualifiedContainerName)
{
if (name is TQualifiedNameSyntax qualifiedName)
{
// Recurse down the left side of the qualified name. Build up the new fully qualified
// parent name for when going down the right side.
var parentQualifiedContainerName = AddNamespaceDeclaredSymbolInfos(GetLeft(qualifiedName), fullyQualifiedContainerName);
return AddNamespaceDeclaredSymbolInfos(GetRight(qualifiedName), parentQualifiedContainerName);
}
else if (name is TIdentifierNameSyntax nameSyntax)
{
var namespaceName = GetIdentifier(nameSyntax).ValueText;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
namespaceName,
nameSuffix: null,
containerDisplayName: null,
fullyQualifiedContainerName,
isPartial: true,
DeclaredSymbolInfoKind.Namespace,
Accessibility.Public,
nameSyntax.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return string.IsNullOrEmpty(fullyQualifiedContainerName)
? namespaceName
: fullyQualifiedContainerName + "." + namespaceName;
}
else
{
return fullyQualifiedContainerName;
}
}
}
protected void AddExtensionMethodInfo(
TMemberDeclarationSyntax node,
Dictionary<string, string> aliases,
int declaredSymbolInfoIndex,
Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder)
{
var receiverTypeName = this.GetReceiverTypeName(node);
// Target type is an alias
if (aliases.TryGetValue(receiverTypeName, out var originalName))
{
// it is an alias of multiple with identical name,
// simply treat it as a complex method.
if (originalName == null)
{
receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
// replace the alias with its original name.
receiverTypeName = originalName;
}
}
if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder))
{
arrayBuilder = ArrayBuilder<int>.GetInstance();
extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder;
}
arrayBuilder.Add(declaredSymbolInfoIndex);
}
private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases)
{
foreach (var (aliasName, name) in aliases)
{
// In C#, it's valid to declare two alias with identical name,
// as long as they are in different containers.
//
// e.g.
// using X = System.String;
// namespace N
// {
// using X = System.Int32;
// }
//
// If we detect this, we will simply treat extension methods whose
// target type is this alias as complex method.
if (allAliases.ContainsKey(aliasName))
{
allAliases[aliasName] = null;
}
else
{
allAliases[aliasName] = name;
}
}
}
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/Workspace/Solution/Project.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a project that is part of a <see cref="Solution"/>.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public partial class Project
{
private readonly Solution _solution;
private readonly ProjectState _projectState;
private ImmutableHashMap<DocumentId, Document> _idToDocumentMap = ImmutableHashMap<DocumentId, Document>.Empty;
private ImmutableHashMap<DocumentId, SourceGeneratedDocument> _idToSourceGeneratedDocumentMap = ImmutableHashMap<DocumentId, SourceGeneratedDocument>.Empty;
private ImmutableHashMap<DocumentId, AdditionalDocument> _idToAdditionalDocumentMap = ImmutableHashMap<DocumentId, AdditionalDocument>.Empty;
private ImmutableHashMap<DocumentId, AnalyzerConfigDocument> _idToAnalyzerConfigDocumentMap = ImmutableHashMap<DocumentId, AnalyzerConfigDocument>.Empty;
internal Project(Solution solution, ProjectState projectState)
{
Contract.ThrowIfNull(solution);
Contract.ThrowIfNull(projectState);
_solution = solution;
_projectState = projectState;
}
internal ProjectState State => _projectState;
/// <summary>
/// The solution this project is part of.
/// </summary>
public Solution Solution => _solution;
/// <summary>
/// The ID of the project. Multiple <see cref="Project"/> instances may share the same ID. However, only
/// one project may have this ID in any given solution.
/// </summary>
public ProjectId Id => _projectState.Id;
/// <summary>
/// The path to the project file or null if there is no project file.
/// </summary>
public string? FilePath => _projectState.FilePath;
/// <summary>
/// The path to the output file, or null if it is not known.
/// </summary>
public string? OutputFilePath => _projectState.OutputFilePath;
/// <summary>
/// The path to the reference assembly output file, or null if it is not known.
/// </summary>
public string? OutputRefFilePath => _projectState.OutputRefFilePath;
/// <summary>
/// Compilation output file paths.
/// </summary>
public CompilationOutputInfo CompilationOutputInfo => _projectState.CompilationOutputInfo;
/// <summary>
/// The default namespace of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
/// by assigning the value of the project's root namespace to it. So various feature can choose to
/// use it for their own purpose.
/// In the future, we might consider officially exposing "default namespace" for VB project
/// (e.g. through a "defaultnamespace" msbuild property)
/// </remarks>
public string? DefaultNamespace => _projectState.DefaultNamespace;
/// <summary>
/// <see langword="true"/> if this <see cref="Project"/> supports providing data through the
/// <see cref="GetCompilationAsync(CancellationToken)"/> method.
///
/// If <see langword="false"/> then <see cref="GetCompilationAsync(CancellationToken)"/> method will return <see langword="null"/> instead.
/// </summary>
public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null;
/// <summary>
/// The language services from the host environment associated with this project's language.
/// </summary>
public HostLanguageServices LanguageServices => _projectState.LanguageServices;
/// <summary>
/// The language associated with the project.
/// </summary>
public string Language => _projectState.Language;
/// <summary>
/// The name of the assembly this project represents.
/// </summary>
public string AssemblyName => _projectState.AssemblyName;
/// <summary>
/// The name of the project. This may be different than the assembly name.
/// </summary>
public string Name => _projectState.Name;
/// <summary>
/// The list of all other metadata sources (assemblies) that this project references.
/// </summary>
public IReadOnlyList<MetadataReference> MetadataReferences => _projectState.MetadataReferences;
/// <summary>
/// The list of all other projects within the same solution that this project references.
/// </summary>
public IEnumerable<ProjectReference> ProjectReferences => _projectState.ProjectReferences.Where(pr => this.Solution.ContainsProject(pr.ProjectId));
/// <summary>
/// The list of all other projects that this project references, including projects that
/// are not part of the solution.
/// </summary>
public IReadOnlyList<ProjectReference> AllProjectReferences => _projectState.ProjectReferences;
/// <summary>
/// The list of all the diagnostic analyzer references for this project.
/// </summary>
public IReadOnlyList<AnalyzerReference> AnalyzerReferences => _projectState.AnalyzerReferences;
/// <summary>
/// The options used by analyzers for this project.
/// </summary>
public AnalyzerOptions AnalyzerOptions => _projectState.AnalyzerOptions;
/// <summary>
/// The options used when building the compilation for this project.
/// </summary>
public CompilationOptions? CompilationOptions => _projectState.CompilationOptions;
/// <summary>
/// The options used when parsing documents for this project.
/// </summary>
public ParseOptions? ParseOptions => _projectState.ParseOptions;
/// <summary>
/// Returns true if this is a submission project.
/// </summary>
public bool IsSubmission => _projectState.IsSubmission;
/// <summary>
/// True if the project has any documents.
/// </summary>
public bool HasDocuments => !_projectState.DocumentStates.IsEmpty;
/// <summary>
/// All the document IDs associated with this project.
/// </summary>
public IReadOnlyList<DocumentId> DocumentIds => _projectState.DocumentStates.Ids;
/// <summary>
/// All the additional document IDs associated with this project.
/// </summary>
public IReadOnlyList<DocumentId> AdditionalDocumentIds => _projectState.AdditionalDocumentStates.Ids;
/// <summary>
/// All the additional document IDs associated with this project.
/// </summary>
internal IReadOnlyList<DocumentId> AnalyzerConfigDocumentIds => _projectState.AnalyzerConfigDocumentStates.Ids;
/// <summary>
/// All the regular documents associated with this project. Documents produced from source generators are returned by
/// <see cref="GetSourceGeneratedDocumentsAsync(CancellationToken)"/>.
/// </summary>
public IEnumerable<Document> Documents => DocumentIds.Select(GetDocument)!;
/// <summary>
/// All the additional documents associated with this project.
/// </summary>
public IEnumerable<TextDocument> AdditionalDocuments => AdditionalDocumentIds.Select(GetAdditionalDocument)!;
/// <summary>
/// All the <see cref="AnalyzerConfigDocument"/>s associated with this project.
/// </summary>
public IEnumerable<AnalyzerConfigDocument> AnalyzerConfigDocuments => AnalyzerConfigDocumentIds.Select(GetAnalyzerConfigDocument)!;
/// <summary>
/// True if the project contains a document with the specified ID.
/// </summary>
public bool ContainsDocument(DocumentId documentId)
=> _projectState.DocumentStates.Contains(documentId);
/// <summary>
/// True if the project contains an additional document with the specified ID.
/// </summary>
public bool ContainsAdditionalDocument(DocumentId documentId)
=> _projectState.AdditionalDocumentStates.Contains(documentId);
/// <summary>
/// True if the project contains an <see cref="AnalyzerConfigDocument"/> with the specified ID.
/// </summary>
public bool ContainsAnalyzerConfigDocument(DocumentId documentId)
=> _projectState.AnalyzerConfigDocumentStates.Contains(documentId);
/// <summary>
/// Get the documentId in this project with the specified syntax tree.
/// </summary>
public DocumentId? GetDocumentId(SyntaxTree? syntaxTree)
=> _solution.GetDocumentId(syntaxTree, this.Id);
/// <summary>
/// Get the document in this project with the specified syntax tree.
/// </summary>
public Document? GetDocument(SyntaxTree? syntaxTree)
=> _solution.GetDocument(syntaxTree, this.Id);
/// <summary>
/// Get the document in this project with the specified document Id.
/// </summary>
public Document? GetDocument(DocumentId documentId)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToDocumentMap, documentId, s_tryCreateDocumentFunction, this);
/// <summary>
/// Get the additional document in this project with the specified document Id.
/// </summary>
public TextDocument? GetAdditionalDocument(DocumentId documentId)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToAdditionalDocumentMap, documentId, s_tryCreateAdditionalDocumentFunction, this);
/// <summary>
/// Get the analyzer config document in this project with the specified document Id.
/// </summary>
public AnalyzerConfigDocument? GetAnalyzerConfigDocument(DocumentId documentId)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToAnalyzerConfigDocumentMap, documentId, s_tryCreateAnalyzerConfigDocumentFunction, this);
/// <summary>
/// Gets a document or a source generated document in this solution with the specified document ID.
/// </summary>
internal async ValueTask<Document?> GetDocumentAsync(DocumentId documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default)
{
var document = GetDocument(documentId);
if (document != null || !includeSourceGenerated)
{
return document;
}
return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID.
/// </summary>
internal async ValueTask<TextDocument?> GetTextDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default)
{
var document = GetDocument(documentId) ?? GetAdditionalDocument(documentId) ?? GetAnalyzerConfigDocument(documentId);
if (document != null)
{
return document;
}
return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all source generated documents in this project.
/// </summary>
public async ValueTask<IEnumerable<SourceGeneratedDocument>> GetSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default)
{
var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false);
// return an iterator to avoid eagerly allocating all the document instances
return generatedDocumentStates.States.Values.Select(state =>
ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this)))!;
}
internal async ValueTask<IEnumerable<Document>> GetAllRegularAndSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default)
{
return Documents.Concat(await GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false));
}
public async ValueTask<SourceGeneratedDocument?> GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default)
{
// Quick check first: if we already have created a SourceGeneratedDocument wrapper, we're good
if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var sourceGeneratedDocument))
{
return sourceGeneratedDocument;
}
// We'll have to run generators if we haven't already and now try to find it.
var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(State, cancellationToken).ConfigureAwait(false);
var generatedDocumentState = generatedDocumentStates.GetState(documentId);
if (generatedDocumentState != null)
{
return GetOrCreateSourceGeneratedDocument(generatedDocumentState);
}
return null;
}
internal SourceGeneratedDocument GetOrCreateSourceGeneratedDocument(SourceGeneratedDocumentState state)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this))!;
/// <summary>
/// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed.
/// </summary>
/// <remarks>
/// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been
/// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something
/// similarly tricky like that.
/// </remarks>
internal SourceGeneratedDocument? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId)
{
// Easy case: do we already have the SourceGeneratedDocument created?
if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var document))
{
return document;
}
// Trickier case now: it's possible we generated this, but we don't actually have the SourceGeneratedDocument for it, so let's go
// try to fetch the state.
var documentState = _solution.State.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId);
if (documentState == null)
{
return null;
}
return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, documentId, s_createSourceGeneratedDocumentFunction, (documentState, this));
}
internal async Task<bool> ContainsSymbolsWithNameAsync(string name, SymbolFilter filter, CancellationToken cancellationToken)
{
return this.SupportsCompilation &&
await _solution.State.ContainsSymbolsWithNameAsync(Id, name, filter, cancellationToken).ConfigureAwait(false);
}
internal async Task<bool> ContainsSymbolsWithNameAsync(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken)
{
return this.SupportsCompilation &&
await _solution.State.ContainsSymbolsWithNameAsync(Id, predicate, filter, cancellationToken).ConfigureAwait(false);
}
private static readonly Func<DocumentId, Project, Document?> s_tryCreateDocumentFunction =
(documentId, project) => project._projectState.DocumentStates.TryGetState(documentId, out var state) ? new Document(project, state) : null;
private static readonly Func<DocumentId, Project, AdditionalDocument?> s_tryCreateAdditionalDocumentFunction =
(documentId, project) => project._projectState.AdditionalDocumentStates.TryGetState(documentId, out var state) ? new AdditionalDocument(project, state) : null;
private static readonly Func<DocumentId, Project, AnalyzerConfigDocument?> s_tryCreateAnalyzerConfigDocumentFunction =
(documentId, project) => project._projectState.AnalyzerConfigDocumentStates.TryGetState(documentId, out var state) ? new AnalyzerConfigDocument(project, state) : null;
private static readonly Func<DocumentId, (SourceGeneratedDocumentState state, Project project), SourceGeneratedDocument> s_createSourceGeneratedDocumentFunction =
(documentId, stateAndProject) => new SourceGeneratedDocument(stateAndProject.project, stateAndProject.state);
/// <summary>
/// Tries to get the cached <see cref="Compilation"/> for this project if it has already been created and is still cached. In almost all
/// cases you should call <see cref="GetCompilationAsync"/> which will either return the cached <see cref="Compilation"/>
/// or create a new one otherwise.
/// </summary>
public bool TryGetCompilation([NotNullWhen(returnValue: true)] out Compilation? compilation)
=> _solution.State.TryGetCompilation(this.Id, out compilation);
/// <summary>
/// Get the <see cref="Compilation"/> for this project asynchronously.
/// </summary>
/// <returns>
/// Returns the produced <see cref="Compilation"/>, or <see langword="null"/> if <see
/// cref="SupportsCompilation"/> returns <see langword="false"/>. This function will
/// return the same value if called multiple times.
/// </returns>
public Task<Compilation?> GetCompilationAsync(CancellationToken cancellationToken = default)
=> _solution.State.GetCompilationAsync(_projectState, cancellationToken);
/// <summary>
/// Determines if the compilation returned by <see cref="GetCompilationAsync"/> and all its referenced compilation are from fully loaded projects.
/// </summary>
// TODO: make this public
internal Task<bool> HasSuccessfullyLoadedAsync(CancellationToken cancellationToken = default)
=> _solution.State.HasSuccessfullyLoadedAsync(_projectState, cancellationToken);
/// <summary>
/// Gets an object that lists the added, changed and removed documents between this project and the specified project.
/// </summary>
public ProjectChanges GetChanges(Project oldProject)
{
if (oldProject == null)
{
throw new ArgumentNullException(nameof(oldProject));
}
return new ProjectChanges(this, oldProject);
}
/// <summary>
/// The project version. This equates to the version of the project file.
/// </summary>
public VersionStamp Version => _projectState.Version;
/// <summary>
/// The version of the most recently modified document.
/// </summary>
public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken = default)
=> _projectState.GetLatestDocumentVersionAsync(cancellationToken);
/// <summary>
/// The most recent version of the project, its documents and all dependent projects and documents.
/// </summary>
public Task<VersionStamp> GetDependentVersionAsync(CancellationToken cancellationToken = default)
=> _solution.State.GetDependentVersionAsync(this.Id, cancellationToken);
/// <summary>
/// The semantic version of this project including the semantics of referenced projects.
/// This version changes whenever the consumable declarations of this project and/or projects it depends on change.
/// </summary>
public Task<VersionStamp> GetDependentSemanticVersionAsync(CancellationToken cancellationToken = default)
=> _solution.State.GetDependentSemanticVersionAsync(this.Id, cancellationToken);
/// <summary>
/// The semantic version of this project not including the semantics of referenced projects.
/// This version changes only when the consumable declarations of this project change.
/// </summary>
public Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default)
=> _projectState.GetSemanticVersionAsync(cancellationToken);
/// <summary>
/// Creates a new instance of this project updated to have the new assembly name.
/// </summary>
public Project WithAssemblyName(string assemblyName)
=> this.Solution.WithProjectAssemblyName(this.Id, assemblyName).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to have the new default namespace.
/// </summary>
public Project WithDefaultNamespace(string defaultNamespace)
=> this.Solution.WithProjectDefaultNamespace(this.Id, defaultNamespace).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to have the specified compilation options.
/// </summary>
public Project WithCompilationOptions(CompilationOptions options)
=> this.Solution.WithProjectCompilationOptions(this.Id, options).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to have the specified parse options.
/// </summary>
public Project WithParseOptions(ParseOptions options)
=> this.Solution.WithProjectParseOptions(this.Id, options).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified project reference
/// in addition to already existing ones.
/// </summary>
public Project AddProjectReference(ProjectReference projectReference)
=> this.Solution.AddProjectReference(this.Id, projectReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified project references
/// in addition to already existing ones.
/// </summary>
public Project AddProjectReferences(IEnumerable<ProjectReference> projectReferences)
=> this.Solution.AddProjectReferences(this.Id, projectReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified project reference.
/// </summary>
public Project RemoveProjectReference(ProjectReference projectReference)
=> this.Solution.RemoveProjectReference(this.Id, projectReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to replace existing project references
/// with the specified ones.
/// </summary>
public Project WithProjectReferences(IEnumerable<ProjectReference> projectReferences)
=> this.Solution.WithProjectReferences(this.Id, projectReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified metadata reference
/// in addition to already existing ones.
/// </summary>
public Project AddMetadataReference(MetadataReference metadataReference)
=> this.Solution.AddMetadataReference(this.Id, metadataReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified metadata references
/// in addition to already existing ones.
/// </summary>
public Project AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences)
=> this.Solution.AddMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified metadata reference.
/// </summary>
public Project RemoveMetadataReference(MetadataReference metadataReference)
=> this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to replace existing metadata reference
/// with the specified ones.
/// </summary>
public Project WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences)
=> this.Solution.WithProjectMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified analyzer reference
/// in addition to already existing ones.
/// </summary>
public Project AddAnalyzerReference(AnalyzerReference analyzerReference)
=> this.Solution.AddAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified analyzer references
/// in addition to already existing ones.
/// </summary>
public Project AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences)
=> this.Solution.AddAnalyzerReferences(this.Id, analyzerReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified analyzer reference.
/// </summary>
public Project RemoveAnalyzerReference(AnalyzerReference analyzerReference)
=> this.Solution.RemoveAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to replace existing analyzer references
/// with the specified ones.
/// </summary>
public Project WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferencs)
=> this.Solution.WithProjectAnalyzerReferences(this.Id, analyzerReferencs).GetProject(this.Id)!;
/// <summary>
/// Creates a new document in a new instance of this project.
/// </summary>
public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
// use preserve identity for forked solution directly from syntax node.
// this lets us not serialize temporary tree unnecessarily
return this.Solution.AddDocument(id, name, syntaxRoot, folders, filePath, preservationMode: PreservationMode.PreserveIdentity).GetDocument(id)!;
}
/// <summary>
/// Creates a new document in a new instance of this project.
/// </summary>
public Document AddDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!;
}
/// <summary>
/// Creates a new document in a new instance of this project.
/// </summary>
public Document AddDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id, debugName: name);
return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!;
}
/// <summary>
/// Creates a new additional document in a new instance of this project.
/// </summary>
public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!;
}
/// <summary>
/// Creates a new additional document in a new instance of this project.
/// </summary>
public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!;
}
/// <summary>
/// Creates a new analyzer config document in a new instance of this project.
/// </summary>
public TextDocument AddAnalyzerConfigDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddAnalyzerConfigDocument(id, name, text, folders, filePath).GetAnalyzerConfigDocument(id)!;
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified document.
/// </summary>
public Project RemoveDocument(DocumentId documentId)
{
// NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change.
// https://github.com/dotnet/roslyn/issues/41211 tracks this investigation.
return this.Solution.RemoveDocument(documentId).GetProject(this.Id)!;
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified documents.
/// </summary>
public Project RemoveDocuments(ImmutableArray<DocumentId> documentIds)
{
CheckIdsContainedInProject(documentIds);
return this.Solution.RemoveDocuments(documentIds).GetRequiredProject(this.Id);
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified additional document.
/// </summary>
public Project RemoveAdditionalDocument(DocumentId documentId)
// NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change.
// https://github.com/dotnet/roslyn/issues/41211 tracks this investigation.
=> this.Solution.RemoveAdditionalDocument(documentId).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified additional documents.
/// </summary>
public Project RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds)
{
CheckIdsContainedInProject(documentIds);
return this.Solution.RemoveAdditionalDocuments(documentIds).GetRequiredProject(this.Id);
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified analyzer config document.
/// </summary>
public Project RemoveAnalyzerConfigDocument(DocumentId documentId)
// NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change.
// https://github.com/dotnet/roslyn/issues/41211 tracks this investigation.
=> this.Solution.RemoveAnalyzerConfigDocument(documentId).GetProject(this.Id)!;
/// <summary>
/// Creates a new solution instance that no longer includes the specified <see cref="AnalyzerConfigDocument"/>s.
/// </summary>
public Project RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds)
{
CheckIdsContainedInProject(documentIds);
return this.Solution.RemoveAnalyzerConfigDocuments(documentIds).GetRequiredProject(this.Id);
}
private void CheckIdsContainedInProject(ImmutableArray<DocumentId> documentIds)
{
foreach (var documentId in documentIds)
{
// Dealing with nulls is handled by the caller of this
if (documentId?.ProjectId != this.Id)
{
throw new ArgumentException(string.Format(WorkspacesResources._0_is_in_a_different_project, documentId));
}
}
}
internal AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions()
=> _projectState.GetAnalyzerConfigOptions();
private string GetDebuggerDisplay()
=> this.Name;
internal SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(DiagnosticAnalyzerInfoCache infoCache)
=> Solution.State.Analyzers.GetSkippedAnalyzersInfo(this, infoCache);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a project that is part of a <see cref="Solution"/>.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public partial class Project
{
private readonly Solution _solution;
private readonly ProjectState _projectState;
private ImmutableHashMap<DocumentId, Document> _idToDocumentMap = ImmutableHashMap<DocumentId, Document>.Empty;
private ImmutableHashMap<DocumentId, SourceGeneratedDocument> _idToSourceGeneratedDocumentMap = ImmutableHashMap<DocumentId, SourceGeneratedDocument>.Empty;
private ImmutableHashMap<DocumentId, AdditionalDocument> _idToAdditionalDocumentMap = ImmutableHashMap<DocumentId, AdditionalDocument>.Empty;
private ImmutableHashMap<DocumentId, AnalyzerConfigDocument> _idToAnalyzerConfigDocumentMap = ImmutableHashMap<DocumentId, AnalyzerConfigDocument>.Empty;
internal Project(Solution solution, ProjectState projectState)
{
Contract.ThrowIfNull(solution);
Contract.ThrowIfNull(projectState);
_solution = solution;
_projectState = projectState;
}
internal ProjectState State => _projectState;
/// <summary>
/// The solution this project is part of.
/// </summary>
public Solution Solution => _solution;
/// <summary>
/// The ID of the project. Multiple <see cref="Project"/> instances may share the same ID. However, only
/// one project may have this ID in any given solution.
/// </summary>
public ProjectId Id => _projectState.Id;
/// <summary>
/// The path to the project file or null if there is no project file.
/// </summary>
public string? FilePath => _projectState.FilePath;
/// <summary>
/// The path to the output file, or null if it is not known.
/// </summary>
public string? OutputFilePath => _projectState.OutputFilePath;
/// <summary>
/// The path to the reference assembly output file, or null if it is not known.
/// </summary>
public string? OutputRefFilePath => _projectState.OutputRefFilePath;
/// <summary>
/// Compilation output file paths.
/// </summary>
public CompilationOutputInfo CompilationOutputInfo => _projectState.CompilationOutputInfo;
/// <summary>
/// The default namespace of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
/// by assigning the value of the project's root namespace to it. So various feature can choose to
/// use it for their own purpose.
/// In the future, we might consider officially exposing "default namespace" for VB project
/// (e.g. through a "defaultnamespace" msbuild property)
/// </remarks>
public string? DefaultNamespace => _projectState.DefaultNamespace;
/// <summary>
/// <see langword="true"/> if this <see cref="Project"/> supports providing data through the
/// <see cref="GetCompilationAsync(CancellationToken)"/> method.
///
/// If <see langword="false"/> then <see cref="GetCompilationAsync(CancellationToken)"/> method will return <see langword="null"/> instead.
/// </summary>
public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null;
/// <summary>
/// The language services from the host environment associated with this project's language.
/// </summary>
public HostLanguageServices LanguageServices => _projectState.LanguageServices;
/// <summary>
/// The language associated with the project.
/// </summary>
public string Language => _projectState.Language;
/// <summary>
/// The name of the assembly this project represents.
/// </summary>
public string AssemblyName => _projectState.AssemblyName;
/// <summary>
/// The name of the project. This may be different than the assembly name.
/// </summary>
public string Name => _projectState.Name;
/// <summary>
/// The list of all other metadata sources (assemblies) that this project references.
/// </summary>
public IReadOnlyList<MetadataReference> MetadataReferences => _projectState.MetadataReferences;
/// <summary>
/// The list of all other projects within the same solution that this project references.
/// </summary>
public IEnumerable<ProjectReference> ProjectReferences => _projectState.ProjectReferences.Where(pr => this.Solution.ContainsProject(pr.ProjectId));
/// <summary>
/// The list of all other projects that this project references, including projects that
/// are not part of the solution.
/// </summary>
public IReadOnlyList<ProjectReference> AllProjectReferences => _projectState.ProjectReferences;
/// <summary>
/// The list of all the diagnostic analyzer references for this project.
/// </summary>
public IReadOnlyList<AnalyzerReference> AnalyzerReferences => _projectState.AnalyzerReferences;
/// <summary>
/// The options used by analyzers for this project.
/// </summary>
public AnalyzerOptions AnalyzerOptions => _projectState.AnalyzerOptions;
/// <summary>
/// The options used when building the compilation for this project.
/// </summary>
public CompilationOptions? CompilationOptions => _projectState.CompilationOptions;
/// <summary>
/// The options used when parsing documents for this project.
/// </summary>
public ParseOptions? ParseOptions => _projectState.ParseOptions;
/// <summary>
/// Returns true if this is a submission project.
/// </summary>
public bool IsSubmission => _projectState.IsSubmission;
/// <summary>
/// True if the project has any documents.
/// </summary>
public bool HasDocuments => !_projectState.DocumentStates.IsEmpty;
/// <summary>
/// All the document IDs associated with this project.
/// </summary>
public IReadOnlyList<DocumentId> DocumentIds => _projectState.DocumentStates.Ids;
/// <summary>
/// All the additional document IDs associated with this project.
/// </summary>
public IReadOnlyList<DocumentId> AdditionalDocumentIds => _projectState.AdditionalDocumentStates.Ids;
/// <summary>
/// All the additional document IDs associated with this project.
/// </summary>
internal IReadOnlyList<DocumentId> AnalyzerConfigDocumentIds => _projectState.AnalyzerConfigDocumentStates.Ids;
/// <summary>
/// All the regular documents associated with this project. Documents produced from source generators are returned by
/// <see cref="GetSourceGeneratedDocumentsAsync(CancellationToken)"/>.
/// </summary>
public IEnumerable<Document> Documents => DocumentIds.Select(GetDocument)!;
/// <summary>
/// All the additional documents associated with this project.
/// </summary>
public IEnumerable<TextDocument> AdditionalDocuments => AdditionalDocumentIds.Select(GetAdditionalDocument)!;
/// <summary>
/// All the <see cref="AnalyzerConfigDocument"/>s associated with this project.
/// </summary>
public IEnumerable<AnalyzerConfigDocument> AnalyzerConfigDocuments => AnalyzerConfigDocumentIds.Select(GetAnalyzerConfigDocument)!;
/// <summary>
/// True if the project contains a document with the specified ID.
/// </summary>
public bool ContainsDocument(DocumentId documentId)
=> _projectState.DocumentStates.Contains(documentId);
/// <summary>
/// True if the project contains an additional document with the specified ID.
/// </summary>
public bool ContainsAdditionalDocument(DocumentId documentId)
=> _projectState.AdditionalDocumentStates.Contains(documentId);
/// <summary>
/// True if the project contains an <see cref="AnalyzerConfigDocument"/> with the specified ID.
/// </summary>
public bool ContainsAnalyzerConfigDocument(DocumentId documentId)
=> _projectState.AnalyzerConfigDocumentStates.Contains(documentId);
/// <summary>
/// Get the documentId in this project with the specified syntax tree.
/// </summary>
public DocumentId? GetDocumentId(SyntaxTree? syntaxTree)
=> _solution.GetDocumentId(syntaxTree, this.Id);
/// <summary>
/// Get the document in this project with the specified syntax tree.
/// </summary>
public Document? GetDocument(SyntaxTree? syntaxTree)
=> _solution.GetDocument(syntaxTree, this.Id);
/// <summary>
/// Get the document in this project with the specified document Id.
/// </summary>
public Document? GetDocument(DocumentId documentId)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToDocumentMap, documentId, s_tryCreateDocumentFunction, this);
/// <summary>
/// Get the additional document in this project with the specified document Id.
/// </summary>
public TextDocument? GetAdditionalDocument(DocumentId documentId)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToAdditionalDocumentMap, documentId, s_tryCreateAdditionalDocumentFunction, this);
/// <summary>
/// Get the analyzer config document in this project with the specified document Id.
/// </summary>
public AnalyzerConfigDocument? GetAnalyzerConfigDocument(DocumentId documentId)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToAnalyzerConfigDocumentMap, documentId, s_tryCreateAnalyzerConfigDocumentFunction, this);
/// <summary>
/// Gets a document or a source generated document in this solution with the specified document ID.
/// </summary>
internal async ValueTask<Document?> GetDocumentAsync(DocumentId documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default)
{
var document = GetDocument(documentId);
if (document != null || !includeSourceGenerated)
{
return document;
}
return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID.
/// </summary>
internal async ValueTask<TextDocument?> GetTextDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default)
{
var document = GetDocument(documentId) ?? GetAdditionalDocument(documentId) ?? GetAnalyzerConfigDocument(documentId);
if (document != null)
{
return document;
}
return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all source generated documents in this project.
/// </summary>
public async ValueTask<IEnumerable<SourceGeneratedDocument>> GetSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default)
{
var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false);
// return an iterator to avoid eagerly allocating all the document instances
return generatedDocumentStates.States.Values.Select(state =>
ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this)))!;
}
internal async ValueTask<IEnumerable<Document>> GetAllRegularAndSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default)
{
return Documents.Concat(await GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false));
}
public async ValueTask<SourceGeneratedDocument?> GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default)
{
// Quick check first: if we already have created a SourceGeneratedDocument wrapper, we're good
if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var sourceGeneratedDocument))
{
return sourceGeneratedDocument;
}
// We'll have to run generators if we haven't already and now try to find it.
var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(State, cancellationToken).ConfigureAwait(false);
var generatedDocumentState = generatedDocumentStates.GetState(documentId);
if (generatedDocumentState != null)
{
return GetOrCreateSourceGeneratedDocument(generatedDocumentState);
}
return null;
}
internal SourceGeneratedDocument GetOrCreateSourceGeneratedDocument(SourceGeneratedDocumentState state)
=> ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this))!;
/// <summary>
/// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed.
/// </summary>
/// <remarks>
/// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been
/// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something
/// similarly tricky like that.
/// </remarks>
internal SourceGeneratedDocument? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId)
{
// Easy case: do we already have the SourceGeneratedDocument created?
if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var document))
{
return document;
}
// Trickier case now: it's possible we generated this, but we don't actually have the SourceGeneratedDocument for it, so let's go
// try to fetch the state.
var documentState = _solution.State.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId);
if (documentState == null)
{
return null;
}
return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, documentId, s_createSourceGeneratedDocumentFunction, (documentState, this));
}
internal Task<bool> ContainsSymbolsWithNameAsync(
string name, CancellationToken cancellationToken)
{
return ContainsSymbolsAsync(
(index, cancellationToken) => index.ProbablyContainsIdentifier(name) || index.ProbablyContainsEscapedIdentifier(name),
cancellationToken);
}
internal Task<bool> ContainsSymbolsWithNameAsync(
Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken)
{
return ContainsSymbolsAsync(
(index, cancellationToken) =>
{
foreach (var info in index.DeclaredSymbolInfos)
{
if (FilterMatches(info, filter) && predicate(info.Name))
return true;
}
return false;
},
cancellationToken);
static bool FilterMatches(DeclaredSymbolInfo info, SymbolFilter filter)
{
switch (info.Kind)
{
case DeclaredSymbolInfoKind.Namespace:
return (filter & SymbolFilter.Namespace) != 0;
case DeclaredSymbolInfoKind.Class:
case DeclaredSymbolInfoKind.Delegate:
case DeclaredSymbolInfoKind.Enum:
case DeclaredSymbolInfoKind.Interface:
case DeclaredSymbolInfoKind.Module:
case DeclaredSymbolInfoKind.Record:
case DeclaredSymbolInfoKind.RecordStruct:
case DeclaredSymbolInfoKind.Struct:
return (filter & SymbolFilter.Type) != 0;
case DeclaredSymbolInfoKind.Constant:
case DeclaredSymbolInfoKind.Constructor:
case DeclaredSymbolInfoKind.EnumMember:
case DeclaredSymbolInfoKind.Event:
case DeclaredSymbolInfoKind.ExtensionMethod:
case DeclaredSymbolInfoKind.Field:
case DeclaredSymbolInfoKind.Indexer:
case DeclaredSymbolInfoKind.Method:
case DeclaredSymbolInfoKind.Property:
return (filter & SymbolFilter.Member) != 0;
default:
throw ExceptionUtilities.UnexpectedValue(info.Kind);
}
}
}
private async Task<bool> ContainsSymbolsAsync(
Func<SyntaxTreeIndex, CancellationToken, bool> predicate, CancellationToken cancellationToken)
{
if (!this.SupportsCompilation)
return false;
var tasks = this.Documents.Select(async d =>
{
var index = await SyntaxTreeIndex.GetRequiredIndexAsync(d, cancellationToken).ConfigureAwait(false);
return predicate(index, cancellationToken);
});
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
return results.Any(b => b);
}
private static readonly Func<DocumentId, Project, Document?> s_tryCreateDocumentFunction =
(documentId, project) => project._projectState.DocumentStates.TryGetState(documentId, out var state) ? new Document(project, state) : null;
private static readonly Func<DocumentId, Project, AdditionalDocument?> s_tryCreateAdditionalDocumentFunction =
(documentId, project) => project._projectState.AdditionalDocumentStates.TryGetState(documentId, out var state) ? new AdditionalDocument(project, state) : null;
private static readonly Func<DocumentId, Project, AnalyzerConfigDocument?> s_tryCreateAnalyzerConfigDocumentFunction =
(documentId, project) => project._projectState.AnalyzerConfigDocumentStates.TryGetState(documentId, out var state) ? new AnalyzerConfigDocument(project, state) : null;
private static readonly Func<DocumentId, (SourceGeneratedDocumentState state, Project project), SourceGeneratedDocument> s_createSourceGeneratedDocumentFunction =
(documentId, stateAndProject) => new SourceGeneratedDocument(stateAndProject.project, stateAndProject.state);
/// <summary>
/// Tries to get the cached <see cref="Compilation"/> for this project if it has already been created and is still cached. In almost all
/// cases you should call <see cref="GetCompilationAsync"/> which will either return the cached <see cref="Compilation"/>
/// or create a new one otherwise.
/// </summary>
public bool TryGetCompilation([NotNullWhen(returnValue: true)] out Compilation? compilation)
=> _solution.State.TryGetCompilation(this.Id, out compilation);
/// <summary>
/// Get the <see cref="Compilation"/> for this project asynchronously.
/// </summary>
/// <returns>
/// Returns the produced <see cref="Compilation"/>, or <see langword="null"/> if <see
/// cref="SupportsCompilation"/> returns <see langword="false"/>. This function will
/// return the same value if called multiple times.
/// </returns>
public Task<Compilation?> GetCompilationAsync(CancellationToken cancellationToken = default)
=> _solution.State.GetCompilationAsync(_projectState, cancellationToken);
/// <summary>
/// Determines if the compilation returned by <see cref="GetCompilationAsync"/> and all its referenced compilation are from fully loaded projects.
/// </summary>
// TODO: make this public
internal Task<bool> HasSuccessfullyLoadedAsync(CancellationToken cancellationToken = default)
=> _solution.State.HasSuccessfullyLoadedAsync(_projectState, cancellationToken);
/// <summary>
/// Gets an object that lists the added, changed and removed documents between this project and the specified project.
/// </summary>
public ProjectChanges GetChanges(Project oldProject)
{
if (oldProject == null)
{
throw new ArgumentNullException(nameof(oldProject));
}
return new ProjectChanges(this, oldProject);
}
/// <summary>
/// The project version. This equates to the version of the project file.
/// </summary>
public VersionStamp Version => _projectState.Version;
/// <summary>
/// The version of the most recently modified document.
/// </summary>
public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken = default)
=> _projectState.GetLatestDocumentVersionAsync(cancellationToken);
/// <summary>
/// The most recent version of the project, its documents and all dependent projects and documents.
/// </summary>
public Task<VersionStamp> GetDependentVersionAsync(CancellationToken cancellationToken = default)
=> _solution.State.GetDependentVersionAsync(this.Id, cancellationToken);
/// <summary>
/// The semantic version of this project including the semantics of referenced projects.
/// This version changes whenever the consumable declarations of this project and/or projects it depends on change.
/// </summary>
public Task<VersionStamp> GetDependentSemanticVersionAsync(CancellationToken cancellationToken = default)
=> _solution.State.GetDependentSemanticVersionAsync(this.Id, cancellationToken);
/// <summary>
/// The semantic version of this project not including the semantics of referenced projects.
/// This version changes only when the consumable declarations of this project change.
/// </summary>
public Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default)
=> _projectState.GetSemanticVersionAsync(cancellationToken);
/// <summary>
/// Creates a new instance of this project updated to have the new assembly name.
/// </summary>
public Project WithAssemblyName(string assemblyName)
=> this.Solution.WithProjectAssemblyName(this.Id, assemblyName).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to have the new default namespace.
/// </summary>
public Project WithDefaultNamespace(string defaultNamespace)
=> this.Solution.WithProjectDefaultNamespace(this.Id, defaultNamespace).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to have the specified compilation options.
/// </summary>
public Project WithCompilationOptions(CompilationOptions options)
=> this.Solution.WithProjectCompilationOptions(this.Id, options).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to have the specified parse options.
/// </summary>
public Project WithParseOptions(ParseOptions options)
=> this.Solution.WithProjectParseOptions(this.Id, options).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified project reference
/// in addition to already existing ones.
/// </summary>
public Project AddProjectReference(ProjectReference projectReference)
=> this.Solution.AddProjectReference(this.Id, projectReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified project references
/// in addition to already existing ones.
/// </summary>
public Project AddProjectReferences(IEnumerable<ProjectReference> projectReferences)
=> this.Solution.AddProjectReferences(this.Id, projectReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified project reference.
/// </summary>
public Project RemoveProjectReference(ProjectReference projectReference)
=> this.Solution.RemoveProjectReference(this.Id, projectReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to replace existing project references
/// with the specified ones.
/// </summary>
public Project WithProjectReferences(IEnumerable<ProjectReference> projectReferences)
=> this.Solution.WithProjectReferences(this.Id, projectReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified metadata reference
/// in addition to already existing ones.
/// </summary>
public Project AddMetadataReference(MetadataReference metadataReference)
=> this.Solution.AddMetadataReference(this.Id, metadataReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified metadata references
/// in addition to already existing ones.
/// </summary>
public Project AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences)
=> this.Solution.AddMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified metadata reference.
/// </summary>
public Project RemoveMetadataReference(MetadataReference metadataReference)
=> this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to replace existing metadata reference
/// with the specified ones.
/// </summary>
public Project WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences)
=> this.Solution.WithProjectMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified analyzer reference
/// in addition to already existing ones.
/// </summary>
public Project AddAnalyzerReference(AnalyzerReference analyzerReference)
=> this.Solution.AddAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to include the specified analyzer references
/// in addition to already existing ones.
/// </summary>
public Project AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences)
=> this.Solution.AddAnalyzerReferences(this.Id, analyzerReferences).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified analyzer reference.
/// </summary>
public Project RemoveAnalyzerReference(AnalyzerReference analyzerReference)
=> this.Solution.RemoveAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to replace existing analyzer references
/// with the specified ones.
/// </summary>
public Project WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferencs)
=> this.Solution.WithProjectAnalyzerReferences(this.Id, analyzerReferencs).GetProject(this.Id)!;
/// <summary>
/// Creates a new document in a new instance of this project.
/// </summary>
public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
// use preserve identity for forked solution directly from syntax node.
// this lets us not serialize temporary tree unnecessarily
return this.Solution.AddDocument(id, name, syntaxRoot, folders, filePath, preservationMode: PreservationMode.PreserveIdentity).GetDocument(id)!;
}
/// <summary>
/// Creates a new document in a new instance of this project.
/// </summary>
public Document AddDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!;
}
/// <summary>
/// Creates a new document in a new instance of this project.
/// </summary>
public Document AddDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id, debugName: name);
return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!;
}
/// <summary>
/// Creates a new additional document in a new instance of this project.
/// </summary>
public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!;
}
/// <summary>
/// Creates a new additional document in a new instance of this project.
/// </summary>
public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!;
}
/// <summary>
/// Creates a new analyzer config document in a new instance of this project.
/// </summary>
public TextDocument AddAnalyzerConfigDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
{
var id = DocumentId.CreateNewId(this.Id);
return this.Solution.AddAnalyzerConfigDocument(id, name, text, folders, filePath).GetAnalyzerConfigDocument(id)!;
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified document.
/// </summary>
public Project RemoveDocument(DocumentId documentId)
{
// NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change.
// https://github.com/dotnet/roslyn/issues/41211 tracks this investigation.
return this.Solution.RemoveDocument(documentId).GetProject(this.Id)!;
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified documents.
/// </summary>
public Project RemoveDocuments(ImmutableArray<DocumentId> documentIds)
{
CheckIdsContainedInProject(documentIds);
return this.Solution.RemoveDocuments(documentIds).GetRequiredProject(this.Id);
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified additional document.
/// </summary>
public Project RemoveAdditionalDocument(DocumentId documentId)
// NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change.
// https://github.com/dotnet/roslyn/issues/41211 tracks this investigation.
=> this.Solution.RemoveAdditionalDocument(documentId).GetProject(this.Id)!;
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified additional documents.
/// </summary>
public Project RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds)
{
CheckIdsContainedInProject(documentIds);
return this.Solution.RemoveAdditionalDocuments(documentIds).GetRequiredProject(this.Id);
}
/// <summary>
/// Creates a new instance of this project updated to no longer include the specified analyzer config document.
/// </summary>
public Project RemoveAnalyzerConfigDocument(DocumentId documentId)
// NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change.
// https://github.com/dotnet/roslyn/issues/41211 tracks this investigation.
=> this.Solution.RemoveAnalyzerConfigDocument(documentId).GetProject(this.Id)!;
/// <summary>
/// Creates a new solution instance that no longer includes the specified <see cref="AnalyzerConfigDocument"/>s.
/// </summary>
public Project RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds)
{
CheckIdsContainedInProject(documentIds);
return this.Solution.RemoveAnalyzerConfigDocuments(documentIds).GetRequiredProject(this.Id);
}
private void CheckIdsContainedInProject(ImmutableArray<DocumentId> documentIds)
{
foreach (var documentId in documentIds)
{
// Dealing with nulls is handled by the caller of this
if (documentId?.ProjectId != this.Id)
{
throw new ArgumentException(string.Format(WorkspacesResources._0_is_in_a_different_project, documentId));
}
}
}
internal AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions()
=> _projectState.GetAnalyzerConfigOptions();
private string GetDebuggerDisplay()
=> this.Name;
internal SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(DiagnosticAnalyzerInfoCache infoCache)
=> Solution.State.Analyzers.GetSkippedAnalyzersInfo(this, infoCache);
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Logging;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
/// <summary>
/// Tracks the changes made to a project and provides the facility to get a lazily built
/// compilation for that project. As the compilation is being built, the partial results are
/// stored as well so that they can be used in the 'in progress' workspace snapshot.
/// </summary>
private partial class CompilationTracker : ICompilationTracker
{
private static readonly Func<ProjectState, string> s_logBuildCompilationAsync =
state => string.Join(",", state.AssemblyName, state.DocumentStates.Count);
public ProjectState ProjectState { get; }
/// <summary>
/// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods.
/// </summary>
private State _stateDoNotAccessDirectly;
// guarantees only one thread is building at a time
private readonly SemaphoreSlim _buildLock = new(initialCount: 1);
private CompilationTracker(
ProjectState project,
State state)
{
Contract.ThrowIfNull(project);
this.ProjectState = project;
_stateDoNotAccessDirectly = state;
}
/// <summary>
/// Creates a tracker for the provided project. The tracker will be in the 'empty' state
/// and will have no extra information beyond the project itself.
/// </summary>
public CompilationTracker(ProjectState project)
: this(project, State.Empty)
{
}
private State ReadState()
=> Volatile.Read(ref _stateDoNotAccessDirectly);
private void WriteState(State state, SolutionServices solutionServices)
{
if (solutionServices.SupportsCachingRecoverableObjects)
{
// Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have
// and hold onto that.
var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull();
solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache);
}
Volatile.Write(ref _stateDoNotAccessDirectly, state);
}
public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary)
{
Debug.Assert(symbol.Kind == SymbolKind.Assembly ||
symbol.Kind == SymbolKind.NetModule ||
symbol.Kind == SymbolKind.DynamicType);
var state = this.ReadState();
var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet;
if (unrootedSymbolSet == null)
{
// this was not a tracker that has handed out a compilation (all compilations handed out must be
// owned by a 'FinalState'). So this symbol could not be from us.
return false;
}
return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary);
}
/// <summary>
/// Creates a new instance of the compilation info, retaining any already built
/// compilation state as the now 'old' state
/// </summary>
public ICompilationTracker Fork(
ProjectState newProject,
CompilationAndGeneratorDriverTranslationAction? translate = null,
CancellationToken cancellationToken = default)
{
var state = ReadState();
var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (baseCompilation != null)
{
var intermediateProjects = state is InProgressState inProgressState
? inProgressState.IntermediateProjects
: ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>();
if (translate is not null)
{
// We have a translation action; are we able to merge it with the prior one?
var merged = false;
if (intermediateProjects.Any())
{
var (priorState, priorAction) = intermediateProjects.Last();
var mergedTranslation = translate.TryMergeWithPrior(priorAction);
if (mergedTranslation != null)
{
// We can replace the prior action with this new one
intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1,
(oldState: priorState, mergedTranslation));
merged = true;
}
}
if (!merged)
{
// Just add it to the end
intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate));
}
}
var newState = State.Create(baseCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects);
return new CompilationTracker(newProject, newState);
}
var declarationOnlyCompilation = state.DeclarationOnlyCompilation;
if (declarationOnlyCompilation != null)
{
if (translate != null)
{
var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate));
return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, compilationWithGeneratedDocuments: state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects));
}
return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false));
}
// We have nothing. Just make a tracker that only points to the new project. We'll have
// to rebuild its compilation from scratch if anyone asks for it.
return new CompilationTracker(newProject);
}
public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken)
{
GetPartialCompilationState(
solution, docState.Id,
out var inProgressProject, out var inProgressCompilation,
out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken);
if (!inProgressCompilation.SyntaxTrees.Contains(tree))
{
var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath);
if (existingTree != null)
{
inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree);
inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false);
}
else
{
inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree);
Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id));
inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState));
}
}
// The user is asking for an in progress snap. We don't want to create it and then
// have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource.
// As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees.
var finalState = FinalState.Create(
new ConstantValueSource<Optional<Compilation>>(inProgressCompilation),
new ConstantValueSource<Optional<Compilation>>(inProgressCompilation),
inProgressCompilation,
hasSuccessfullyLoaded: false,
sourceGeneratedDocuments,
generatorDriver,
inProgressCompilation,
this.ProjectState.Id,
metadataReferenceToProjectId);
return new CompilationTracker(inProgressProject, finalState);
}
/// <summary>
/// Tries to get the latest snapshot of the compilation without waiting for it to be
/// fully built. This method takes advantage of the progress side-effect produced during
/// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>.
/// It will either return the already built compilation, any
/// in-progress compilation or any known old compilation in that order of preference.
/// The compilation state that is returned will have a compilation that is retained so
/// that it cannot disappear.
/// </summary>
/// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param>
private void GetPartialCompilationState(
SolutionState solution,
DocumentId id,
out ProjectState inProgressProject,
out Compilation inProgressCompilation,
out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments,
out GeneratorDriver? generatorDriver,
out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId,
CancellationToken cancellationToken)
{
var state = ReadState();
var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
// check whether we can bail out quickly for typing case
var inProgressState = state as InProgressState;
sourceGeneratedDocuments = state.GeneratedDocuments;
generatorDriver = state.GeneratorDriver;
// all changes left for this document is modifying the given document.
// we can use current state as it is since we will replace the document with latest document anyway.
if (inProgressState != null &&
compilationWithoutGeneratedDocuments != null &&
inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id)))
{
inProgressProject = ProjectState;
// We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes
// being made to the project, but it's the best we have so we'll use it.
inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken)));
// This is likely a bug. It seems possible to pass out a partial compilation state that we don't
// properly record assembly symbols for.
metadataReferenceToProjectId = null;
SolutionLogger.UseExistingPartialProjectState();
return;
}
inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState;
// if we already have a final compilation we are done.
if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState)
{
var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken);
if (finalCompilation != null)
{
inProgressCompilation = finalCompilation;
// This should hopefully be safe to return as null. Because we already reached the 'FinalState'
// before, we should have already recorded the assembly symbols for it. So not recording them
// again is likely ok (as long as compilations continue to return the same IAssemblySymbols for
// the same references across source edits).
metadataReferenceToProjectId = null;
SolutionLogger.UseExistingFullProjectState();
return;
}
}
// 1) if we have an in-progress compilation use it.
// 2) If we don't, then create a simple empty compilation/project.
// 3) then, make sure that all it's p2p refs and whatnot are correct.
if (compilationWithoutGeneratedDocuments == null)
{
inProgressProject = inProgressProject.RemoveAllDocuments();
inProgressCompilation = CreateEmptyCompilation();
}
else
{
inProgressCompilation = compilationWithoutGeneratedDocuments;
}
inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken)));
// Now add in back a consistent set of project references. For project references
// try to get either a CompilationReference or a SkeletonReference. This ensures
// that the in-progress project only reports a reference to another project if it
// could actually get a reference to that project's metadata.
var metadataReferences = new List<MetadataReference>();
var newProjectReferences = new List<ProjectReference>();
metadataReferences.AddRange(this.ProjectState.MetadataReferences);
metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>();
foreach (var projectReference in this.ProjectState.ProjectReferences)
{
var referencedProject = solution.GetProjectState(projectReference.ProjectId);
if (referencedProject != null)
{
if (referencedProject.IsSubmission)
{
var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken);
// previous submission project must support compilation:
RoslynDebug.Assert(previousScriptCompilation != null);
inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation));
}
else
{
// get the latest metadata for the partial compilation of the referenced project.
var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState);
if (metadata == null)
{
// if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead.
var inProgressCompilationNotRef = inProgressCompilation;
metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault(
r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId);
}
if (metadata != null)
{
newProjectReferences.Add(projectReference);
metadataReferences.Add(metadata);
metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId);
}
}
}
}
inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences);
if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences))
{
inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences);
}
SolutionLogger.CreatePartialProjectState();
}
private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id)
=> action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction &&
touchDocumentAction.DocumentId == id;
/// <summary>
/// Gets the final compilation if it is available.
/// </summary>
public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation)
{
var state = ReadState();
if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue)
{
compilation = compilationOpt.Value;
return true;
}
compilation = null;
return false;
}
public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken)
{
if (this.TryGetCompilation(out var compilation))
{
// PERF: This is a hot code path and Task<TResult> isn't cheap,
// so cache the completed tasks to reduce allocations. We also
// need to avoid keeping a strong reference to the Compilation,
// so use a ConditionalWeakTable.
return SpecializedTasks.FromResult(compilation);
}
else
{
return GetCompilationSlowAsync(solution, cancellationToken);
}
}
private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken)
{
var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return compilationInfo.Compilation;
}
private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
var state = ReadState();
// we are already in the final stage. just return it.
var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (compilation != null)
{
return compilation;
}
compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (compilation == null)
{
// let's see whether we have declaration only compilation
if (state.DeclarationOnlyCompilation != null)
{
// okay, move to full declaration state. do this so that declaration only compilation never
// realize symbols.
var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone();
WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal), solutionServices);
return declarationOnlyCompilation;
}
// We've got nothing. Build it from scratch :(
return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false);
}
if (state is FullDeclarationState or FinalState)
{
// we have full declaration, just use it.
return compilation;
}
(compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false);
// We must have an in progress compilation. Build off of that.
return compilation;
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync(
SolutionState solution,
bool lockGate,
CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync,
s_logBuildCompilationAsync, ProjectState, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var state = ReadState();
// Try to get the built compilation. If it exists, then we can just return that.
var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (finalCompilation != null)
{
RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue);
return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments);
}
// Otherwise, we actually have to build it. Ensure that only one thread is trying to
// build this compilation at a time.
if (lockGate)
{
using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false);
}
}
else
{
return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false);
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Builds the compilation matching the project state. In the process of building, also
/// produce in progress snapshots that can be accessed from other threads.
/// </summary>
private Task<CompilationInfo> BuildCompilationInfoAsync(
SolutionState solution,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var state = ReadState();
// if we already have a compilation, we must be already done! This can happen if two
// threads were waiting to build, and we came in after the other succeeded.
var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (compilation != null)
{
RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue);
return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments));
}
compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
// If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents
// so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise
// we'd be reparsing trees which could result in generated documents changing identity.
var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null;
var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments;
var generatorDriver = state.GeneratorDriver;
if (compilation == null)
{
// this can happen if compilation is already kicked out from the cache.
// check whether the state we have support declaration only compilation
if (state.DeclarationOnlyCompilation != null)
{
// we have declaration only compilation. build final one from it.
return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken);
}
// We've got nothing. Build it from scratch :(
return BuildCompilationInfoFromScratchAsync(solution, cancellationToken);
}
if (state is FullDeclarationState or FinalState)
{
// We have a declaration compilation, use it to reconstruct the final compilation
return FinalizeCompilationAsync(
solution,
compilation,
authoritativeGeneratedDocuments,
nonAuthoritativeGeneratedDocuments,
compilationWithStaleGeneratedTrees: null,
generatorDriver,
cancellationToken);
}
else
{
// We must have an in progress compilation. Build off of that.
return BuildFinalStateFromInProgressStateAsync(solution, (InProgressState)state, compilation, cancellationToken);
}
}
private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync(
SolutionState solution, CancellationToken cancellationToken)
{
try
{
var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false);
return await FinalizeCompilationAsync(
solution, compilation,
authoritativeGeneratedDocuments: null,
nonAuthoritativeGeneratedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty,
compilationWithStaleGeneratedTrees: null,
generatorDriver: null,
cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/23582",
Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")]
private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync(
SolutionServices solutionServices, CancellationToken cancellationToken)
{
try
{
var compilation = CreateEmptyCompilation();
var trees = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count);
foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder())
{
cancellationToken.ThrowIfCancellationRequested();
// Include the tree even if the content of the document failed to load.
trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false));
}
compilation = compilation.AddSyntaxTrees(trees);
trees.Free();
WriteState(new FullDeclarationState(compilation, TextDocumentStates<SourceGeneratedDocumentState>.Empty, generatorDriver: null, generatedDocumentsAreFinal: false), solutionServices);
return compilation;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private Compilation CreateEmptyCompilation()
{
var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>();
if (this.ProjectState.IsSubmission)
{
return compilationFactory.CreateSubmissionCompilation(
this.ProjectState.AssemblyName,
this.ProjectState.CompilationOptions!,
this.ProjectState.HostObjectType);
}
else
{
return compilationFactory.CreateCompilation(
this.ProjectState.AssemblyName,
this.ProjectState.CompilationOptions!);
}
}
private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync(
SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken)
{
try
{
var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false);
return await FinalizeCompilationAsync(
solution,
compilationWithoutGenerators,
authoritativeGeneratedDocuments: null,
nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments,
compilationWithGenerators,
generatorDriver,
cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync(
SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken)
{
try
{
var compilationWithGenerators = state.CompilationWithGeneratedDocuments;
var generatorDriver = state.GeneratorDriver;
// If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators
// didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any
// transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try
// to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return
// null for compilationWithGenerators in the end, so there's no harm there.
if (compilationWithGenerators == compilationWithoutGenerators)
{
compilationWithGenerators = null;
}
var intermediateProjects = state.IntermediateProjects;
while (intermediateProjects.Length > 0)
{
cancellationToken.ThrowIfCancellationRequested();
// We have a list of transformations to get to our final compilation; take the first transformation and apply it.
var intermediateProject = intermediateProjects[0];
compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false);
if (compilationWithGenerators != null)
{
// Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with
// the generated documents, or if don't have any source generators in the first place.
if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput &&
intermediateProject.oldState.SourceGenerators.Any())
{
compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false);
}
else
{
compilationWithGenerators = null;
}
}
if (generatorDriver != null)
{
generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver);
}
// We have updated state, so store this new result; this allows us to drop the intermediate state we already processed
// even if we were to get cancelled at a later point.
intermediateProjects = intermediateProjects.RemoveAt(0);
this.WriteState(State.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices);
}
return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private readonly struct CompilationInfo
{
public Compilation Compilation { get; }
public bool HasSuccessfullyLoaded { get; }
public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; }
public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments)
{
Compilation = compilation;
HasSuccessfullyLoaded = hasSuccessfullyLoaded;
GeneratedDocuments = generatedDocuments;
}
}
/// <summary>
/// Add all appropriate references to the compilation and set it as our final compilation
/// state.
/// </summary>
/// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already
/// known to be correct for the given state. This would be non-null in cases where we had computed everything and
/// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we
/// still had the prior generated result available.</param>
/// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may
/// or may not be correct for the current compilation. These states may be used to access cached results, if
/// and when applicable for the current compilation.</param>
/// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which
/// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces
/// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other
/// changes to references, we can then use this compilation instead of re-adding source generated files again to the
/// <paramref name="compilationWithoutGenerators"/>.</param>
/// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param>
private async Task<CompilationInfo> FinalizeCompilationAsync(
SolutionState solution,
Compilation compilationWithoutGenerators,
TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments,
TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments,
Compilation? compilationWithStaleGeneratedTrees,
GeneratorDriver? generatorDriver,
CancellationToken cancellationToken)
{
try
{
// if HasAllInformation is false, then this project is always not completed.
var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation;
var newReferences = new List<MetadataReference>();
var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>();
newReferences.AddRange(this.ProjectState.MetadataReferences);
foreach (var projectReference in this.ProjectState.ProjectReferences)
{
var referencedProject = solution.GetProjectState(projectReference.ProjectId);
// Even though we're creating a final compilation (vs. an in progress compilation),
// it's possible that the target project has been removed.
if (referencedProject != null)
{
// If both projects are submissions, we'll count this as a previous submission link
// instead of a regular metadata reference
if (referencedProject.IsSubmission)
{
// if the referenced project is a submission project must be a submission as well:
Debug.Assert(this.ProjectState.IsSubmission);
// We now need to (potentially) update the prior submission compilation. That Compilation is held in the
// ScriptCompilationInfo that we need to replace as a unit.
var previousSubmissionCompilation =
await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false);
if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation)
{
compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo(
compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!));
compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo(
compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!));
}
}
else
{
var metadataReference = await solution.GetMetadataReferenceAsync(
projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false);
// A reference can fail to be created if a skeleton assembly could not be constructed.
if (metadataReference != null)
{
newReferences.Add(metadataReference);
metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId);
}
else
{
hasSuccessfullyLoaded = false;
}
}
}
}
// Now that we know the set of references this compilation should have, update them if they're not already.
// Generators cannot add references, so we can use the same set of references both for the compilation
// that doesn't have generated files, and the one we're trying to reuse that has generated files.
// Since we updated both of these compilations together in response to edits, we only have to check one
// for a potential mismatch.
if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences))
{
compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences);
compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences);
}
// We will finalize the compilation by adding full contents here.
// TODO: allow finalize compilation to incrementally update a prior version
// https://github.com/dotnet/roslyn/issues/46418
Compilation compilationWithGenerators;
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments;
if (authoritativeGeneratedDocuments.HasValue)
{
generatedDocuments = authoritativeGeneratedDocuments.Value;
compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees(
await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false));
}
else
{
using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>();
if (ProjectState.SourceGenerators.Any())
{
// If we don't already have a generator driver, we'll have to create one from scratch
if (generatorDriver == null)
{
var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText);
var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>();
generatorDriver = compilationFactory.CreateGeneratorDriver(
this.ProjectState.ParseOptions!,
ProjectState.SourceGenerators,
this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider,
additionalTexts);
}
generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken);
var runResult = generatorDriver.GetRunResult();
// We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null
// to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees
// if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree
// content is identical to the prior generation run; if we find a match each time, then the set of the generated trees
// and the prior generated trees are identical.
if (compilationWithStaleGeneratedTrees != null)
{
if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length))
{
compilationWithStaleGeneratedTrees = null;
}
}
foreach (var generatorResult in runResult.Results)
{
foreach (var generatedSource in generatorResult.GeneratedSources)
{
var existing = FindExistingGeneratedDocumentState(
nonAuthoritativeGeneratedDocuments,
generatorResult.Generator,
generatedSource.HintName);
if (existing != null)
{
var newDocument = existing.WithUpdatedGeneratedContent(
generatedSource.SourceText,
this.ProjectState.ParseOptions!);
generatedDocumentsBuilder.Add(newDocument);
if (newDocument != existing)
compilationWithStaleGeneratedTrees = null;
}
else
{
// NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK,
// since the tree is a lazy tree and that won't trigger the parse.
var identity = SourceGeneratedDocumentIdentity.Generate(
ProjectState.Id,
generatedSource.HintName,
generatorResult.Generator,
generatedSource.SyntaxTree.FilePath);
generatedDocumentsBuilder.Add(
SourceGeneratedDocumentState.Create(
identity,
generatedSource.SourceText,
generatedSource.SyntaxTree.Options,
this.ProjectState.LanguageServices,
solution.Services));
// The count of trees was the same, but something didn't match up. Since we're here, at least one tree
// was added, and an equal number must have been removed. Rather than trying to incrementally update
// this compilation, we'll just toss this and re-add all the trees.
compilationWithStaleGeneratedTrees = null;
}
}
}
}
// If we didn't null out this compilation, it means we can actually use it
if (compilationWithStaleGeneratedTrees != null)
{
generatedDocuments = nonAuthoritativeGeneratedDocuments;
compilationWithGenerators = compilationWithStaleGeneratedTrees;
}
else
{
generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear());
compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees(
await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false));
}
}
var finalState = FinalState.Create(
State.CreateValueSource(compilationWithGenerators, solution.Services),
State.CreateValueSource(compilationWithoutGenerators, solution.Services),
compilationWithoutGenerators,
hasSuccessfullyLoaded,
generatedDocuments,
generatorDriver,
compilationWithGenerators,
this.ProjectState.Id,
metadataReferenceToProjectId);
this.WriteState(finalState, solution.Services);
return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
// Local functions
static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState(
TextDocumentStates<SourceGeneratedDocumentState> states,
ISourceGenerator generator,
string hintName)
{
var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator);
var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator);
foreach (var (_, state) in states.States)
{
if (state.SourceGeneratorAssemblyName != generatorAssemblyName)
continue;
if (state.SourceGeneratorTypeName != generatorTypeName)
continue;
if (state.HintName != hintName)
continue;
return state;
}
return null;
}
}
public async Task<MetadataReference> GetMetadataReferenceAsync(
SolutionState solution,
ProjectState fromProject,
ProjectReference projectReference,
CancellationToken cancellationToken)
{
try
{
// if we already have the compilation and its right kind then use it.
if (this.ProjectState.LanguageServices == fromProject.LanguageServices
&& this.TryGetCompilation(out var compilation))
{
return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
}
// If same language then we can wrap the other project's compilation into a compilation reference
if (this.ProjectState.LanguageServices == fromProject.LanguageServices)
{
// otherwise, base it off the compilation by building it first.
compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false);
return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
}
else
{
// otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it.
return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Attempts to get (without waiting) a metadata reference to a possibly in progress
/// compilation. Only actual compilation references are returned. Could potentially
/// return null if nothing can be provided.
/// </summary>
public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference)
{
var state = ReadState();
// get compilation in any state it happens to be in right now.
if (state.CompilationWithoutGeneratedDocuments != null &&
state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) &&
compilationOpt.HasValue &&
ProjectState.LanguageServices == fromProject.LanguageServices)
{
// if we have a compilation and its the correct language, use a simple compilation reference
return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
}
return null;
}
/// <summary>
/// Gets a metadata reference to the metadata-only-image corresponding to the compilation.
/// </summary>
private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync(
SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken))
{
var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false);
// get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment
var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false);
solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock...");
if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference))
{
// using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation.
using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}...");
// okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly
var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false);
reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken);
}
}
else
{
solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}");
}
return reference;
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// check whether the compilation contains any declaration symbol from syntax trees with
/// given name
/// </summary>
public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken)
{
// DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation.
var state = this.ReadState();
return state.DeclarationOnlyCompilation == null
? (bool?)null
: state.DeclarationOnlyCompilation.ContainsSymbolsWithName(name, filter, cancellationToken);
}
/// <summary>
/// check whether the compilation contains any declaration symbol from syntax trees with given name
/// </summary>
public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken)
{
// DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation.
var state = this.ReadState();
return state.DeclarationOnlyCompilation == null
? (bool?)null
: state.DeclarationOnlyCompilation.ContainsSymbolsWithName(predicate, filter, cancellationToken);
}
public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken)
{
var state = this.ReadState();
if (state.HasSuccessfullyLoaded.HasValue)
{
return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False;
}
else
{
return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken);
}
}
private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken)
{
var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return compilationInfo.HasSuccessfullyLoaded;
}
public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken)
{
// If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely.
if (!this.ProjectState.SourceGenerators.Any())
{
return TextDocumentStates<SourceGeneratedDocumentState>.Empty;
}
var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return compilationInfo.GeneratedDocuments;
}
public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId)
{
var state = ReadState();
// If we are in FinalState, then we have correctly ran generators and then know the final contents of the
// Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be
// correct and can be re-ran later.
return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null;
}
#region Versions
// Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs.
private AsyncLazy<VersionStamp>? _lazyDependentVersion;
private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion;
public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
if (_lazyDependentVersion == null)
{
var tmp = solution; // temp. local to avoid a closure allocation for the fast path
// note: solution is captured here, but it will go away once GetValueAsync executes.
Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null);
}
return _lazyDependentVersion.GetValueAsync(cancellationToken);
}
private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
var projectState = this.ProjectState;
var projVersion = projectState.Version;
var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false);
var version = docVersion.GetNewerVersion(projVersion);
foreach (var dependentProjectReference in projectState.ProjectReferences)
{
cancellationToken.ThrowIfCancellationRequested();
if (solution.ContainsProject(dependentProjectReference.ProjectId))
{
var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false);
version = dependentProjectVersion.GetNewerVersion(version);
}
}
return version;
}
public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
if (_lazyDependentSemanticVersion == null)
{
var tmp = solution; // temp. local to avoid a closure allocation for the fast path
// note: solution is captured here, but it will go away once GetValueAsync executes.
Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null);
}
return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken);
}
private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
var projectState = this.ProjectState;
var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
foreach (var dependentProjectReference in projectState.ProjectReferences)
{
cancellationToken.ThrowIfCancellationRequested();
if (solution.ContainsProject(dependentProjectReference.ProjectId))
{
var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false);
version = dependentProjectVersion.GetNewerVersion(version);
}
}
return version;
}
#endregion
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Logging;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
/// <summary>
/// Tracks the changes made to a project and provides the facility to get a lazily built
/// compilation for that project. As the compilation is being built, the partial results are
/// stored as well so that they can be used in the 'in progress' workspace snapshot.
/// </summary>
private partial class CompilationTracker : ICompilationTracker
{
private static readonly Func<ProjectState, string> s_logBuildCompilationAsync =
state => string.Join(",", state.AssemblyName, state.DocumentStates.Count);
public ProjectState ProjectState { get; }
/// <summary>
/// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods.
/// </summary>
private CompilationTrackerState _stateDoNotAccessDirectly;
// guarantees only one thread is building at a time
private readonly SemaphoreSlim _buildLock = new(initialCount: 1);
private CompilationTracker(
ProjectState project,
CompilationTrackerState state)
{
Contract.ThrowIfNull(project);
this.ProjectState = project;
_stateDoNotAccessDirectly = state;
}
/// <summary>
/// Creates a tracker for the provided project. The tracker will be in the 'empty' state
/// and will have no extra information beyond the project itself.
/// </summary>
public CompilationTracker(ProjectState project)
: this(project, CompilationTrackerState.Empty)
{
}
private CompilationTrackerState ReadState()
=> Volatile.Read(ref _stateDoNotAccessDirectly);
private void WriteState(CompilationTrackerState state, SolutionServices solutionServices)
{
if (solutionServices.SupportsCachingRecoverableObjects)
{
// Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have
// and hold onto that.
var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull();
solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache);
}
Volatile.Write(ref _stateDoNotAccessDirectly, state);
}
public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary)
{
Debug.Assert(symbol.Kind == SymbolKind.Assembly ||
symbol.Kind == SymbolKind.NetModule ||
symbol.Kind == SymbolKind.DynamicType);
var state = this.ReadState();
var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet;
if (unrootedSymbolSet == null)
{
// this was not a tracker that has handed out a compilation (all compilations handed out must be
// owned by a 'FinalState'). So this symbol could not be from us.
return false;
}
return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary);
}
/// <summary>
/// Creates a new instance of the compilation info, retaining any already built
/// compilation state as the now 'old' state
/// </summary>
public ICompilationTracker Fork(
ProjectState newProject,
CompilationAndGeneratorDriverTranslationAction? translate = null,
CancellationToken cancellationToken = default)
{
var state = ReadState();
var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (baseCompilation != null)
{
var intermediateProjects = state is InProgressState inProgressState
? inProgressState.IntermediateProjects
: ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>();
if (translate is not null)
{
// We have a translation action; are we able to merge it with the prior one?
var merged = false;
if (intermediateProjects.Any())
{
var (priorState, priorAction) = intermediateProjects.Last();
var mergedTranslation = translate.TryMergeWithPrior(priorAction);
if (mergedTranslation != null)
{
// We can replace the prior action with this new one
intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1,
(oldState: priorState, mergedTranslation));
merged = true;
}
}
if (!merged)
{
// Just add it to the end
intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate));
}
}
var newState = CompilationTrackerState.Create(baseCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects);
return new CompilationTracker(newProject, newState);
}
else
{
// We have no compilation, but we might have information about generated docs.
var newState = new NoCompilationState(state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false);
return new CompilationTracker(newProject, newState);
}
}
public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken)
{
GetPartialCompilationState(
solution, docState.Id,
out var inProgressProject,
out var inProgressCompilation,
out var sourceGeneratedDocuments,
out var generatorDriver,
out var metadataReferenceToProjectId,
cancellationToken);
if (!inProgressCompilation.SyntaxTrees.Contains(tree))
{
var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath);
if (existingTree != null)
{
inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree);
inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false);
}
else
{
inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree);
Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id));
inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState));
}
}
// The user is asking for an in progress snap. We don't want to create it and then
// have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource.
// As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees.
var finalState = FinalState.Create(
new ConstantValueSource<Optional<Compilation>>(inProgressCompilation),
new ConstantValueSource<Optional<Compilation>>(inProgressCompilation),
inProgressCompilation,
hasSuccessfullyLoaded: false,
sourceGeneratedDocuments,
generatorDriver,
inProgressCompilation,
this.ProjectState.Id,
metadataReferenceToProjectId);
return new CompilationTracker(inProgressProject, finalState);
}
/// <summary>
/// Tries to get the latest snapshot of the compilation without waiting for it to be
/// fully built. This method takes advantage of the progress side-effect produced during
/// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>.
/// It will either return the already built compilation, any
/// in-progress compilation or any known old compilation in that order of preference.
/// The compilation state that is returned will have a compilation that is retained so
/// that it cannot disappear.
/// </summary>
/// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param>
private void GetPartialCompilationState(
SolutionState solution,
DocumentId id,
out ProjectState inProgressProject,
out Compilation inProgressCompilation,
out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments,
out GeneratorDriver? generatorDriver,
out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId,
CancellationToken cancellationToken)
{
var state = ReadState();
var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
// check whether we can bail out quickly for typing case
var inProgressState = state as InProgressState;
sourceGeneratedDocuments = state.GeneratedDocuments;
generatorDriver = state.GeneratorDriver;
// all changes left for this document is modifying the given document.
// we can use current state as it is since we will replace the document with latest document anyway.
if (inProgressState != null &&
compilationWithoutGeneratedDocuments != null &&
inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id)))
{
inProgressProject = ProjectState;
// We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes
// being made to the project, but it's the best we have so we'll use it.
inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken)));
// This is likely a bug. It seems possible to pass out a partial compilation state that we don't
// properly record assembly symbols for.
metadataReferenceToProjectId = null;
SolutionLogger.UseExistingPartialProjectState();
return;
}
inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState;
// if we already have a final compilation we are done.
if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState)
{
var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken);
if (finalCompilation != null)
{
inProgressCompilation = finalCompilation;
// This should hopefully be safe to return as null. Because we already reached the 'FinalState'
// before, we should have already recorded the assembly symbols for it. So not recording them
// again is likely ok (as long as compilations continue to return the same IAssemblySymbols for
// the same references across source edits).
metadataReferenceToProjectId = null;
SolutionLogger.UseExistingFullProjectState();
return;
}
}
// 1) if we have an in-progress compilation use it.
// 2) If we don't, then create a simple empty compilation/project.
// 3) then, make sure that all it's p2p refs and whatnot are correct.
if (compilationWithoutGeneratedDocuments == null)
{
inProgressProject = inProgressProject.RemoveAllDocuments();
inProgressCompilation = CreateEmptyCompilation();
}
else
{
inProgressCompilation = compilationWithoutGeneratedDocuments;
}
inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken)));
// Now add in back a consistent set of project references. For project references
// try to get either a CompilationReference or a SkeletonReference. This ensures
// that the in-progress project only reports a reference to another project if it
// could actually get a reference to that project's metadata.
var metadataReferences = new List<MetadataReference>();
var newProjectReferences = new List<ProjectReference>();
metadataReferences.AddRange(this.ProjectState.MetadataReferences);
metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>();
foreach (var projectReference in this.ProjectState.ProjectReferences)
{
var referencedProject = solution.GetProjectState(projectReference.ProjectId);
if (referencedProject != null)
{
if (referencedProject.IsSubmission)
{
var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken);
// previous submission project must support compilation:
RoslynDebug.Assert(previousScriptCompilation != null);
inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation));
}
else
{
// get the latest metadata for the partial compilation of the referenced project.
var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState);
if (metadata == null)
{
// if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead.
var inProgressCompilationNotRef = inProgressCompilation;
metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault(
r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId);
}
if (metadata != null)
{
newProjectReferences.Add(projectReference);
metadataReferences.Add(metadata);
metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId);
}
}
}
}
inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences);
if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences))
{
inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences);
}
SolutionLogger.CreatePartialProjectState();
}
private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id)
=> action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction &&
touchDocumentAction.DocumentId == id;
/// <summary>
/// Gets the final compilation if it is available.
/// </summary>
public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation)
{
var state = ReadState();
if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue)
{
compilation = compilationOpt.Value;
return true;
}
compilation = null;
return false;
}
public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken)
{
if (this.TryGetCompilation(out var compilation))
{
// PERF: This is a hot code path and Task<TResult> isn't cheap,
// so cache the completed tasks to reduce allocations. We also
// need to avoid keeping a strong reference to the Compilation,
// so use a ConditionalWeakTable.
return SpecializedTasks.FromResult(compilation);
}
else
{
return GetCompilationSlowAsync(solution, cancellationToken);
}
}
private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken)
{
var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return compilationInfo.Compilation;
}
private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
var state = ReadState();
// we are already in the final stage. just return it.
var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (compilation != null)
{
return compilation;
}
compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (compilation == null)
{
// We've got nothing. Build it from scratch :(
return await BuildDeclarationCompilationFromScratchAsync(
solutionServices,
state.GeneratedDocuments,
state.GeneratorDriver,
state.GeneratedDocumentsAreFinal,
cancellationToken).ConfigureAwait(false);
}
if (state is AllSyntaxTreesParsedState or FinalState)
{
// we have full declaration, just use it.
return compilation;
}
(compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false);
// We must have an in progress compilation. Build off of that.
return compilation;
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync(
SolutionState solution,
bool lockGate,
CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync,
s_logBuildCompilationAsync, ProjectState, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var state = ReadState();
// Try to get the built compilation. If it exists, then we can just return that.
var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (finalCompilation != null)
{
RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue);
return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments);
}
// Otherwise, we actually have to build it. Ensure that only one thread is trying to
// build this compilation at a time.
if (lockGate)
{
using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false);
}
}
else
{
return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false);
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Builds the compilation matching the project state. In the process of building, also
/// produce in progress snapshots that can be accessed from other threads.
/// </summary>
private async Task<CompilationInfo> BuildCompilationInfoAsync(
SolutionState solution,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var state = ReadState();
// if we already have a compilation, we must be already done! This can happen if two
// threads were waiting to build, and we came in after the other succeeded.
var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken);
if (compilation != null)
{
RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue);
return new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments);
}
compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken);
// If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents
// so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise
// we'd be reparsing trees which could result in generated documents changing identity.
var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null;
var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments;
var generatorDriver = state.GeneratorDriver;
if (compilation == null)
{
// We've got nothing. Build it from scratch :(
return await BuildCompilationInfoFromScratchAsync(
solution,
authoritativeGeneratedDocuments,
nonAuthoritativeGeneratedDocuments,
generatorDriver,
cancellationToken).ConfigureAwait(false);
}
if (state is AllSyntaxTreesParsedState or FinalState)
{
// We have a declaration compilation, use it to reconstruct the final compilation
return await FinalizeCompilationAsync(
solution,
compilation,
authoritativeGeneratedDocuments,
nonAuthoritativeGeneratedDocuments,
compilationWithStaleGeneratedTrees: null,
generatorDriver,
cancellationToken).ConfigureAwait(false);
}
else
{
// We must have an in progress compilation. Build off of that.
return await BuildFinalStateFromInProgressStateAsync(
solution, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false);
}
}
private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync(
SolutionState solution,
TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments,
TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments,
GeneratorDriver? generatorDriver,
CancellationToken cancellationToken)
{
try
{
var compilation = await BuildDeclarationCompilationFromScratchAsync(
solution.Services,
nonAuthoritativeGeneratedDocuments,
generatorDriver,
generatedDocumentsAreFinal: false,
cancellationToken).ConfigureAwait(false);
return await FinalizeCompilationAsync(
solution,
compilation,
authoritativeGeneratedDocuments,
nonAuthoritativeGeneratedDocuments,
compilationWithStaleGeneratedTrees: null,
generatorDriver,
cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/23582",
Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")]
private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync(
SolutionServices solutionServices,
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments,
GeneratorDriver? generatorDriver,
bool generatedDocumentsAreFinal,
CancellationToken cancellationToken)
{
try
{
var compilation = CreateEmptyCompilation();
using var _ = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count, out var trees);
foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder())
{
cancellationToken.ThrowIfCancellationRequested();
// Include the tree even if the content of the document failed to load.
trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false));
}
compilation = compilation.AddSyntaxTrees(trees);
WriteState(new AllSyntaxTreesParsedState(compilation, generatedDocuments, generatorDriver, generatedDocumentsAreFinal), solutionServices);
return compilation;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private Compilation CreateEmptyCompilation()
{
var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>();
if (this.ProjectState.IsSubmission)
{
return compilationFactory.CreateSubmissionCompilation(
this.ProjectState.AssemblyName,
this.ProjectState.CompilationOptions!,
this.ProjectState.HostObjectType);
}
else
{
return compilationFactory.CreateCompilation(
this.ProjectState.AssemblyName,
this.ProjectState.CompilationOptions!);
}
}
private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync(
SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken)
{
try
{
var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false);
return await FinalizeCompilationAsync(
solution,
compilationWithoutGenerators,
authoritativeGeneratedDocuments: null,
nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments,
compilationWithGenerators,
generatorDriver,
cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync(
SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken)
{
try
{
var compilationWithGenerators = state.CompilationWithGeneratedDocuments;
var generatorDriver = state.GeneratorDriver;
// If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators
// didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any
// transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try
// to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return
// null for compilationWithGenerators in the end, so there's no harm there.
if (compilationWithGenerators == compilationWithoutGenerators)
{
compilationWithGenerators = null;
}
var intermediateProjects = state.IntermediateProjects;
while (intermediateProjects.Length > 0)
{
cancellationToken.ThrowIfCancellationRequested();
// We have a list of transformations to get to our final compilation; take the first transformation and apply it.
var intermediateProject = intermediateProjects[0];
compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false);
if (compilationWithGenerators != null)
{
// Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with
// the generated documents, or if don't have any source generators in the first place.
if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput &&
intermediateProject.oldState.SourceGenerators.Any())
{
compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false);
}
else
{
compilationWithGenerators = null;
}
}
if (generatorDriver != null)
{
generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver);
}
// We have updated state, so store this new result; this allows us to drop the intermediate state we already processed
// even if we were to get cancelled at a later point.
intermediateProjects = intermediateProjects.RemoveAt(0);
this.WriteState(CompilationTrackerState.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices);
}
return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private readonly struct CompilationInfo
{
public Compilation Compilation { get; }
public bool HasSuccessfullyLoaded { get; }
public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; }
public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments)
{
Compilation = compilation;
HasSuccessfullyLoaded = hasSuccessfullyLoaded;
GeneratedDocuments = generatedDocuments;
}
}
/// <summary>
/// Add all appropriate references to the compilation and set it as our final compilation
/// state.
/// </summary>
/// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already
/// known to be correct for the given state. This would be non-null in cases where we had computed everything and
/// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we
/// still had the prior generated result available.</param>
/// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may
/// or may not be correct for the current compilation. These states may be used to access cached results, if
/// and when applicable for the current compilation.</param>
/// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which
/// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces
/// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other
/// changes to references, we can then use this compilation instead of re-adding source generated files again to the
/// <paramref name="compilationWithoutGenerators"/>.</param>
/// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param>
private async Task<CompilationInfo> FinalizeCompilationAsync(
SolutionState solution,
Compilation compilationWithoutGenerators,
TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments,
TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments,
Compilation? compilationWithStaleGeneratedTrees,
GeneratorDriver? generatorDriver,
CancellationToken cancellationToken)
{
try
{
// if HasAllInformation is false, then this project is always not completed.
var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation;
var newReferences = new List<MetadataReference>();
var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>();
newReferences.AddRange(this.ProjectState.MetadataReferences);
foreach (var projectReference in this.ProjectState.ProjectReferences)
{
var referencedProject = solution.GetProjectState(projectReference.ProjectId);
// Even though we're creating a final compilation (vs. an in progress compilation),
// it's possible that the target project has been removed.
if (referencedProject != null)
{
// If both projects are submissions, we'll count this as a previous submission link
// instead of a regular metadata reference
if (referencedProject.IsSubmission)
{
// if the referenced project is a submission project must be a submission as well:
Debug.Assert(this.ProjectState.IsSubmission);
// We now need to (potentially) update the prior submission compilation. That Compilation is held in the
// ScriptCompilationInfo that we need to replace as a unit.
var previousSubmissionCompilation =
await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false);
if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation)
{
compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo(
compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!));
compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo(
compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!));
}
}
else
{
var metadataReference = await solution.GetMetadataReferenceAsync(
projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false);
// A reference can fail to be created if a skeleton assembly could not be constructed.
if (metadataReference != null)
{
newReferences.Add(metadataReference);
metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId);
}
else
{
hasSuccessfullyLoaded = false;
}
}
}
}
// Now that we know the set of references this compilation should have, update them if they're not already.
// Generators cannot add references, so we can use the same set of references both for the compilation
// that doesn't have generated files, and the one we're trying to reuse that has generated files.
// Since we updated both of these compilations together in response to edits, we only have to check one
// for a potential mismatch.
if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences))
{
compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences);
compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences);
}
// We will finalize the compilation by adding full contents here.
// TODO: allow finalize compilation to incrementally update a prior version
// https://github.com/dotnet/roslyn/issues/46418
Compilation compilationWithGenerators;
TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments;
if (authoritativeGeneratedDocuments.HasValue)
{
generatedDocuments = authoritativeGeneratedDocuments.Value;
compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees(
await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false));
}
else
{
using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>();
if (ProjectState.SourceGenerators.Any())
{
// If we don't already have a generator driver, we'll have to create one from scratch
if (generatorDriver == null)
{
var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText);
var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>();
generatorDriver = compilationFactory.CreateGeneratorDriver(
this.ProjectState.ParseOptions!,
ProjectState.SourceGenerators,
this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider,
additionalTexts);
}
generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken);
var runResult = generatorDriver.GetRunResult();
// We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null
// to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees
// if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree
// content is identical to the prior generation run; if we find a match each time, then the set of the generated trees
// and the prior generated trees are identical.
if (compilationWithStaleGeneratedTrees != null)
{
if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length))
{
compilationWithStaleGeneratedTrees = null;
}
}
foreach (var generatorResult in runResult.Results)
{
foreach (var generatedSource in generatorResult.GeneratedSources)
{
var existing = FindExistingGeneratedDocumentState(
nonAuthoritativeGeneratedDocuments,
generatorResult.Generator,
generatedSource.HintName);
if (existing != null)
{
var newDocument = existing.WithUpdatedGeneratedContent(
generatedSource.SourceText,
this.ProjectState.ParseOptions!);
generatedDocumentsBuilder.Add(newDocument);
if (newDocument != existing)
compilationWithStaleGeneratedTrees = null;
}
else
{
// NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK,
// since the tree is a lazy tree and that won't trigger the parse.
var identity = SourceGeneratedDocumentIdentity.Generate(
ProjectState.Id,
generatedSource.HintName,
generatorResult.Generator,
generatedSource.SyntaxTree.FilePath);
generatedDocumentsBuilder.Add(
SourceGeneratedDocumentState.Create(
identity,
generatedSource.SourceText,
generatedSource.SyntaxTree.Options,
this.ProjectState.LanguageServices,
solution.Services));
// The count of trees was the same, but something didn't match up. Since we're here, at least one tree
// was added, and an equal number must have been removed. Rather than trying to incrementally update
// this compilation, we'll just toss this and re-add all the trees.
compilationWithStaleGeneratedTrees = null;
}
}
}
}
// If we didn't null out this compilation, it means we can actually use it
if (compilationWithStaleGeneratedTrees != null)
{
generatedDocuments = nonAuthoritativeGeneratedDocuments;
compilationWithGenerators = compilationWithStaleGeneratedTrees;
}
else
{
generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear());
compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees(
await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false));
}
}
var finalState = FinalState.Create(
CompilationTrackerState.CreateValueSource(compilationWithGenerators, solution.Services),
CompilationTrackerState.CreateValueSource(compilationWithoutGenerators, solution.Services),
compilationWithoutGenerators,
hasSuccessfullyLoaded,
generatedDocuments,
generatorDriver,
compilationWithGenerators,
this.ProjectState.Id,
metadataReferenceToProjectId);
this.WriteState(finalState, solution.Services);
return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
// Local functions
static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState(
TextDocumentStates<SourceGeneratedDocumentState> states,
ISourceGenerator generator,
string hintName)
{
var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator);
var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator);
foreach (var (_, state) in states.States)
{
if (state.SourceGeneratorAssemblyName != generatorAssemblyName)
continue;
if (state.SourceGeneratorTypeName != generatorTypeName)
continue;
if (state.HintName != hintName)
continue;
return state;
}
return null;
}
}
public async Task<MetadataReference> GetMetadataReferenceAsync(
SolutionState solution,
ProjectState fromProject,
ProjectReference projectReference,
CancellationToken cancellationToken)
{
try
{
// if we already have the compilation and its right kind then use it.
if (this.ProjectState.LanguageServices == fromProject.LanguageServices
&& this.TryGetCompilation(out var compilation))
{
return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
}
// If same language then we can wrap the other project's compilation into a compilation reference
if (this.ProjectState.LanguageServices == fromProject.LanguageServices)
{
// otherwise, base it off the compilation by building it first.
compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false);
return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
}
else
{
// otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it.
return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Attempts to get (without waiting) a metadata reference to a possibly in progress
/// compilation. Only actual compilation references are returned. Could potentially
/// return null if nothing can be provided.
/// </summary>
public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference)
{
var state = ReadState();
// get compilation in any state it happens to be in right now.
if (state.CompilationWithoutGeneratedDocuments != null &&
state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) &&
compilationOpt.HasValue &&
ProjectState.LanguageServices == fromProject.LanguageServices)
{
// if we have a compilation and its the correct language, use a simple compilation reference
return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
}
return null;
}
/// <summary>
/// Gets a metadata reference to the metadata-only-image corresponding to the compilation.
/// </summary>
private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync(
SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken))
{
var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false);
// get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment
var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false);
solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock...");
if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference))
{
// using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation.
using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}...");
// okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly
var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false);
reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken);
}
}
else
{
solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}");
}
return reference;
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken)
{
var state = this.ReadState();
if (state.HasSuccessfullyLoaded.HasValue)
{
return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False;
}
else
{
return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken);
}
}
private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken)
{
var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return compilationInfo.HasSuccessfullyLoaded;
}
public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken)
{
// If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely.
if (!this.ProjectState.SourceGenerators.Any())
{
return TextDocumentStates<SourceGeneratedDocumentState>.Empty;
}
var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return compilationInfo.GeneratedDocuments;
}
public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId)
{
var state = ReadState();
// If we are in FinalState, then we have correctly ran generators and then know the final contents of the
// Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be
// correct and can be re-ran later.
return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null;
}
#region Versions
// Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs.
private AsyncLazy<VersionStamp>? _lazyDependentVersion;
private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion;
public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
if (_lazyDependentVersion == null)
{
var tmp = solution; // temp. local to avoid a closure allocation for the fast path
// note: solution is captured here, but it will go away once GetValueAsync executes.
Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null);
}
return _lazyDependentVersion.GetValueAsync(cancellationToken);
}
private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
var projectState = this.ProjectState;
var projVersion = projectState.Version;
var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false);
var version = docVersion.GetNewerVersion(projVersion);
foreach (var dependentProjectReference in projectState.ProjectReferences)
{
cancellationToken.ThrowIfCancellationRequested();
if (solution.ContainsProject(dependentProjectReference.ProjectId))
{
var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false);
version = dependentProjectVersion.GetNewerVersion(version);
}
}
return version;
}
public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
if (_lazyDependentSemanticVersion == null)
{
var tmp = solution; // temp. local to avoid a closure allocation for the fast path
// note: solution is captured here, but it will go away once GetValueAsync executes.
Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null);
}
return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken);
}
private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken)
{
var projectState = this.ProjectState;
var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
foreach (var dependentProjectReference in projectState.ProjectReferences)
{
cancellationToken.ThrowIfCancellationRequested();
if (solution.ContainsProject(dependentProjectReference.ProjectId))
{
var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false);
version = dependentProjectVersion.GetNewerVersion(version);
}
}
return version;
}
#endregion
}
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.ICompilationTracker.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
private interface ICompilationTracker
{
ProjectState ProjectState { get; }
/// <summary>
/// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the
/// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see
/// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>.
/// </summary>
/// <remarks>
/// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered
/// when answering this question. In other words, if <paramref name="symbol"/> is an <see
/// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only
/// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is
/// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any
/// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for
/// any of the references of the <see cref="Compilation.References"/>.
/// </remarks>
bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary);
bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken);
bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken);
ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default);
ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken);
Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken);
/// <summary>
/// Get a metadata reference to this compilation info's compilation with respect to
/// another project. For cross language references produce a skeletal assembly. If the
/// compilation is not available, it is built. If a skeletal assembly reference is
/// needed and does not exist, it is also built.
/// </summary>
Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken);
CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference);
ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken);
Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken);
bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation);
SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
private interface ICompilationTracker
{
ProjectState ProjectState { get; }
/// <summary>
/// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the
/// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see
/// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>.
/// </summary>
/// <remarks>
/// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered
/// when answering this question. In other words, if <paramref name="symbol"/> is an <see
/// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only
/// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is
/// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any
/// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for
/// any of the references of the <see cref="Compilation.References"/>.
/// </remarks>
bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary);
ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default);
ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken);
Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken);
/// <summary>
/// Get a metadata reference to this compilation info's compilation with respect to
/// another project. For cross language references produce a skeletal assembly. If the
/// compilation is not available, it is built. If a skeletal assembly reference is
/// needed and does not exist, it is also built.
/// </summary>
Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken);
CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference);
ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken);
Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken);
bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation);
SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId);
}
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Logging;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a set of projects and their source code documents.
///
/// this is a green node of Solution like ProjectState/DocumentState are for
/// Project and Document.
/// </summary>
internal partial class SolutionState
{
// branch id for this solution
private readonly BranchId _branchId;
// the version of the workspace this solution is from
private readonly int _workspaceVersion;
private readonly SolutionInfo.SolutionAttributes _solutionAttributes;
private readonly SolutionServices _solutionServices;
private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap;
private readonly ImmutableHashSet<string> _remoteSupportedLanguages;
private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap;
private readonly ProjectDependencyGraph _dependencyGraph;
public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences;
// Values for all these are created on demand.
private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap;
// Checksums for this solution state
private readonly ValueSource<SolutionStateChecksums> _lazyChecksums;
/// <summary>
/// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over
/// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset
/// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined
/// for the entire solution). Lock this specific field before reading/writing to it.
/// </summary>
private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new();
// holds on data calculated based on the AnalyzerReferences list
private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers;
/// <summary>
/// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project
/// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the
/// question quickly after computing for the first one. Created on demand.
/// </summary>
private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId;
private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>();
private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState;
private SolutionState(
BranchId branchId,
int workspaceVersion,
SolutionServices solutionServices,
SolutionInfo.SolutionAttributes solutionAttributes,
IReadOnlyList<ProjectId> projectIds,
SerializableOptionSet options,
IReadOnlyList<AnalyzerReference> analyzerReferences,
ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
ImmutableHashSet<string> remoteSupportedLanguages,
ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap,
ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap,
ProjectDependencyGraph dependencyGraph,
Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers,
SourceGeneratedDocumentState? frozenSourceGeneratedDocument)
{
_branchId = branchId;
_workspaceVersion = workspaceVersion;
_solutionAttributes = solutionAttributes;
_solutionServices = solutionServices;
ProjectIds = projectIds;
Options = options;
AnalyzerReferences = analyzerReferences;
_projectIdToProjectStateMap = idToProjectStateMap;
_remoteSupportedLanguages = remoteSupportedLanguages;
_projectIdToTrackerMap = projectIdToTrackerMap;
_filePathToDocumentIdsMap = filePathToDocumentIdsMap;
_dependencyGraph = dependencyGraph;
_lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences);
_frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument;
// when solution state is changed, we recalculate its checksum
_lazyChecksums = new AsyncLazy<SolutionStateChecksums>(
c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true);
CheckInvariants();
// make sure we don't accidentally capture any state but the list of references:
static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences)
=> new(() => new HostDiagnosticAnalyzers(analyzerReferences));
}
public SolutionState(
BranchId primaryBranchId,
SolutionServices solutionServices,
SolutionInfo.SolutionAttributes solutionAttributes,
SerializableOptionSet options,
IReadOnlyList<AnalyzerReference> analyzerReferences)
: this(
primaryBranchId,
workspaceVersion: 0,
solutionServices,
solutionAttributes,
projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(),
options,
analyzerReferences,
idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty,
remoteSupportedLanguages: ImmutableHashSet<string>.Empty,
projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty,
filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase),
dependencyGraph: ProjectDependencyGraph.Empty,
lazyAnalyzers: null,
frozenSourceGeneratedDocument: null)
{
}
public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion)
{
var services = workspace != _solutionServices.Workspace
? new SolutionServices(workspace)
: _solutionServices;
// Note: this will potentially have problems if the workspace services are different, as some services
// get locked-in by document states and project states when first constructed.
return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services);
}
public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value;
public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes;
public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState;
public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap;
public int WorkspaceVersion => _workspaceVersion;
public SolutionServices Services => _solutionServices;
public SerializableOptionSet Options { get; }
/// <summary>
/// branch id of this solution
///
/// currently, it only supports one level of branching. there is a primary branch of a workspace and all other
/// branches that are branched from the primary branch.
///
/// one still can create multiple forked solutions from an already branched solution, but versions among those
/// can't be reliably used and compared.
///
/// version only has a meaning between primary solution and branched one or between solutions from same branch.
/// </summary>
public BranchId BranchId => _branchId;
/// <summary>
/// The Workspace this solution is associated with.
/// </summary>
public Workspace Workspace => _solutionServices.Workspace;
/// <summary>
/// The Id of the solution. Multiple solution instances may share the same Id.
/// </summary>
public SolutionId Id => _solutionAttributes.Id;
/// <summary>
/// The path to the solution file or null if there is no solution file.
/// </summary>
public string? FilePath => _solutionAttributes.FilePath;
/// <summary>
/// The solution version. This equates to the solution file's version.
/// </summary>
public VersionStamp Version => _solutionAttributes.Version;
/// <summary>
/// A list of all the ids for all the projects contained by the solution.
/// </summary>
public IReadOnlyList<ProjectId> ProjectIds { get; }
// Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them.
[Conditional("DEBUG")]
private void CheckInvariants()
{
Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count);
Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count);
// An id shouldn't point at a tracker for a different project.
Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id));
// project ids must be the same:
Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds));
Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds));
Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap)));
}
private SolutionState Branch(
SolutionInfo.SolutionAttributes? solutionAttributes = null,
IReadOnlyList<ProjectId>? projectIds = null,
SerializableOptionSet? options = null,
IReadOnlyList<AnalyzerReference>? analyzerReferences = null,
ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null,
ImmutableHashSet<string>? remoteSupportedProjectLanguages = null,
ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null,
ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null,
ProjectDependencyGraph? dependencyGraph = null,
Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default)
{
var branchId = GetBranchId();
if (idToProjectStateMap is not null)
{
Contract.ThrowIfNull(remoteSupportedProjectLanguages);
}
solutionAttributes ??= _solutionAttributes;
projectIds ??= ProjectIds;
idToProjectStateMap ??= _projectIdToProjectStateMap;
remoteSupportedProjectLanguages ??= _remoteSupportedLanguages;
Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap)));
options ??= Options.WithLanguages(remoteSupportedProjectLanguages);
analyzerReferences ??= AnalyzerReferences;
projectIdToTrackerMap ??= _projectIdToTrackerMap;
filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap;
dependencyGraph ??= _dependencyGraph;
var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState;
var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences);
if (branchId == _branchId &&
solutionAttributes == _solutionAttributes &&
projectIds == ProjectIds &&
options == Options &&
analyzerReferencesEqual &&
idToProjectStateMap == _projectIdToProjectStateMap &&
projectIdToTrackerMap == _projectIdToTrackerMap &&
filePathToDocumentIdsMap == _filePathToDocumentIdsMap &&
dependencyGraph == _dependencyGraph &&
newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState)
{
return this;
}
return new SolutionState(
branchId,
_workspaceVersion,
_solutionServices,
solutionAttributes,
projectIds,
options,
analyzerReferences,
idToProjectStateMap,
remoteSupportedProjectLanguages,
projectIdToTrackerMap,
filePathToDocumentIdsMap,
dependencyGraph,
analyzerReferencesEqual ? _lazyAnalyzers : null,
newFrozenSourceGeneratedDocumentState);
}
private SolutionState CreatePrimarySolution(
BranchId branchId,
int workspaceVersion,
SolutionServices services)
{
if (branchId == _branchId &&
workspaceVersion == _workspaceVersion &&
services == _solutionServices)
{
return this;
}
return new SolutionState(
branchId,
workspaceVersion,
services,
_solutionAttributes,
ProjectIds,
Options,
AnalyzerReferences,
_projectIdToProjectStateMap,
_remoteSupportedLanguages,
_projectIdToTrackerMap,
_filePathToDocumentIdsMap,
_dependencyGraph,
_lazyAnalyzers,
frozenSourceGeneratedDocument: null);
}
private BranchId GetBranchId()
{
// currently we only support one level branching.
// my reasonings are
// 1. it seems there is no-one who needs sub branches.
// 2. this lets us to branch without explicit branch API
return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId;
}
/// <summary>
/// The version of the most recently modified project.
/// </summary>
public VersionStamp GetLatestProjectVersion()
{
// this may produce a version that is out of sync with the actual Document versions.
var latestVersion = VersionStamp.Default;
foreach (var project in this.ProjectStates.Values)
{
latestVersion = project.Version.GetNewerVersion(latestVersion);
}
return latestVersion;
}
/// <summary>
/// True if the solution contains a project with the specified project ID.
/// </summary>
public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId)
=> projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId);
/// <summary>
/// True if the solution contains the document in one of its projects
/// </summary>
public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId)
{
return
documentId != null &&
this.ContainsProject(documentId.ProjectId) &&
this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId);
}
/// <summary>
/// True if the solution contains the additional document in one of its projects
/// </summary>
public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId)
{
return
documentId != null &&
this.ContainsProject(documentId.ProjectId) &&
this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId);
}
/// <summary>
/// True if the solution contains the analyzer config document in one of its projects
/// </summary>
public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId)
{
return
documentId != null &&
this.ContainsProject(documentId.ProjectId) &&
this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId);
}
private DocumentState GetRequiredDocumentState(DocumentId documentId)
=> GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId);
private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId)
=> GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId);
private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId)
=> GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId);
internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId)
{
if (syntaxTree != null)
{
// is this tree known to be associated with a document?
var documentId = DocumentState.GetDocumentIdForTree(syntaxTree);
if (documentId != null && (projectId == null || documentId.ProjectId == projectId))
{
// does this solution even have the document?
var projectState = GetProjectState(documentId.ProjectId);
if (projectState != null)
{
var document = projectState.DocumentStates.GetState(documentId);
if (document != null)
{
// does this document really have the syntax tree?
if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
{
return document;
}
}
else
{
var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId);
if (generatedDocument != null)
{
// does this document really have the syntax tree?
if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
{
return generatedDocument;
}
}
}
}
}
}
return null;
}
public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken)
=> this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken);
public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken)
=> this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken);
public ProjectState? GetProjectState(ProjectId projectId)
{
_projectIdToProjectStateMap.TryGetValue(projectId, out var state);
return state;
}
public ProjectState GetRequiredProjectState(ProjectId projectId)
{
var result = GetProjectState(projectId);
Contract.ThrowIfNull(result);
return result;
}
/// <summary>
/// Gets the <see cref="Project"/> associated with an assembly symbol.
/// </summary>
public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol)
{
if (assemblySymbol == null)
return null;
s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id);
return id == null ? null : this.GetProjectState(id);
}
private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker)
=> _projectIdToTrackerMap.TryGetValue(projectId, out tracker);
private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker;
private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution)
{
var projectState = solution.GetProjectState(projectId);
Contract.ThrowIfNull(projectState);
return new CompilationTracker(projectState);
}
private ICompilationTracker GetCompilationTracker(ProjectId projectId)
{
if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker))
{
tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this);
}
return tracker;
}
private SolutionState AddProject(ProjectId projectId, ProjectState projectState)
{
// changed project list so, increment version.
var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion());
var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId);
var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState);
var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language)
? _remoteSupportedLanguages.Add(projectState.Language)
: _remoteSupportedLanguages;
var newDependencyGraph = _dependencyGraph
.WithAdditionalProject(projectId)
.WithAdditionalProjectReferences(projectId, projectState.ProjectReferences);
// It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow
// dangling references like that. If so, we'll need to link those in too.
foreach (var newState in newStateMap)
{
foreach (var projectReference in newState.Value.ProjectReferences)
{
if (projectReference.ProjectId == projectId)
{
newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences(
newState.Key,
SpecializedCollections.SingletonReadOnlyList(projectReference));
break;
}
}
}
var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph);
var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId]));
return Branch(
solutionAttributes: newSolutionAttributes,
projectIds: newProjectIds,
idToProjectStateMap: newStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newTrackerMap,
filePathToDocumentIdsMap: newFilePathToDocumentIdsMap,
dependencyGraph: newDependencyGraph);
}
/// <summary>
/// Create a new solution instance that includes a project with the specified project information.
/// </summary>
public SolutionState AddProject(ProjectInfo projectInfo)
{
if (projectInfo == null)
{
throw new ArgumentNullException(nameof(projectInfo));
}
var projectId = projectInfo.Id;
var language = projectInfo.Language;
if (language == null)
{
throw new ArgumentNullException(nameof(language));
}
var displayName = projectInfo.Name;
if (displayName == null)
{
throw new ArgumentNullException(nameof(displayName));
}
CheckNotContainsProject(projectId);
var languageServices = this.Workspace.Services.GetLanguageServices(language);
if (languageServices == null)
{
throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language));
}
var newProject = new ProjectState(projectInfo, languageServices, _solutionServices);
return this.AddProject(newProject.Id, newProject);
}
private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates)
{
var builder = _filePathToDocumentIdsMap.ToBuilder();
foreach (var documentState in documentStates)
{
var filePath = documentState.FilePath;
if (RoslynString.IsNullOrEmpty(filePath))
{
continue;
}
builder.MultiAdd(filePath, documentState.Id);
}
return builder.ToImmutable();
}
private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState)
=> projectState.DocumentStates.States.Values
.Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values)
.Concat(projectState.AnalyzerConfigDocumentStates.States.Values);
/// <summary>
/// Create a new solution instance without the project specified.
/// </summary>
public SolutionState RemoveProject(ProjectId projectId)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
CheckContainsProject(projectId);
// changed project list so, increment version.
var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion());
var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId);
var newStateMap = _projectIdToProjectStateMap.Remove(projectId);
// Remote supported languages only changes if the removed project is the last project of a supported language.
var newLanguages = _remoteSupportedLanguages;
if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState)
&& RemoteSupportedLanguages.IsSupported(projectState.Language))
{
var stillSupportsLanguage = false;
foreach (var (id, state) in _projectIdToProjectStateMap)
{
if (id == projectId)
continue;
if (state.Language == projectState.Language)
{
stillSupportsLanguage = true;
break;
}
}
if (!stillSupportsLanguage)
{
newLanguages = newLanguages.Remove(projectState.Language);
}
}
var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId);
var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph);
var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId]));
return this.Branch(
solutionAttributes: newSolutionAttributes,
projectIds: newProjectIds,
idToProjectStateMap: newStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newTrackerMap.Remove(projectId),
filePathToDocumentIdsMap: newFilePathToDocumentIdsMap,
dependencyGraph: newDependencyGraph);
}
private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates)
{
var builder = _filePathToDocumentIdsMap.ToBuilder();
foreach (var documentState in documentStates)
{
var filePath = documentState.FilePath;
if (RoslynString.IsNullOrEmpty(filePath))
{
continue;
}
if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id))
{
throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'.");
}
builder.MultiRemove(filePath, documentState.Id);
}
return builder.ToImmutable();
}
private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath)
{
if (oldFilePath == newFilePath)
{
return _filePathToDocumentIdsMap;
}
var builder = _filePathToDocumentIdsMap.ToBuilder();
if (!RoslynString.IsNullOrEmpty(oldFilePath))
{
builder.MultiRemove(oldFilePath, documentId);
}
if (!RoslynString.IsNullOrEmpty(newFilePath))
{
builder.MultiAdd(newFilePath, documentId);
}
return builder.ToImmutable();
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the new
/// assembly name.
/// </summary>
public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithAssemblyName(assemblyName);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName));
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the output file path.
/// </summary>
public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithOutputFilePath(outputFilePath);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the output file path.
/// </summary>
public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the compiler output file path.
/// </summary>
public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithCompilationOutputInfo(info);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the default namespace.
/// </summary>
public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithDefaultNamespace(defaultNamespace);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the name.
/// </summary>
public SolutionState WithProjectName(ProjectId projectId, string name)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithName(name);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the project file path.
/// </summary>
public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithFilePath(filePath);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified compilation options.
/// </summary>
public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithCompilationOptions(options);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false));
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified parse options.
/// </summary>
public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithParseOptions(options);
if (oldProject == newProject)
{
return this;
}
if (Workspace.PartialSemanticsEnabled)
{
// don't fork tracker with queued action since access via partial semantics can become inconsistent (throw).
// Since changing options is rare event, it is okay to start compilation building from scratch.
return ForkProject(newProject, forkTracker: false);
}
else
{
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true));
}
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified hasAllInformation.
/// </summary>
public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithHasAllInformation(hasAllInformation);
if (oldProject == newProject)
{
return this;
}
// fork without any change on compilation.
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified runAnalyzers.
/// </summary>
public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithRunAnalyzers(runAnalyzers);
if (oldProject == newProject)
{
return this;
}
// fork without any change on compilation.
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include
/// the specified project references.
/// </summary>
public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences)
{
if (projectReferences.Count == 0)
{
return this;
}
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.ProjectReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(projectReferences);
var newProject = oldProject.WithProjectReferences(newReferences);
var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences);
return ForkProject(newProject, newDependencyGraph: newDependencyGraph);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer
/// include the specified project reference.
/// </summary>
public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference)
{
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.ProjectReferences.ToImmutableArray();
// Note: uses ProjectReference equality to compare references.
var newReferences = oldReferences.Remove(projectReference);
if (oldReferences == newReferences)
{
return this;
}
var newProject = oldProject.WithProjectReferences(newReferences);
ProjectDependencyGraph newDependencyGraph;
if (newProject.ContainsReferenceToProject(projectReference.ProjectId) ||
!_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId))
{
// Two cases:
// 1) The project contained multiple non-equivalent references to the project,
// and not all of them were removed. The dependency graph doesn't change.
// Note that there might be two references to the same project, one with
// extern alias and the other without. These are not considered duplicates.
// 2) The referenced project is not part of the solution and hence not included
// in the dependency graph.
newDependencyGraph = _dependencyGraph;
}
else
{
newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId);
}
return ForkProject(newProject, newDependencyGraph: newDependencyGraph);
}
/// <summary>
/// Create a new solution instance with the project specified updated to contain
/// the specified list of project references.
/// </summary>
public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithProjectReferences(projectReferences);
if (oldProject == newProject)
{
return this;
}
var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences);
return ForkProject(newProject, newDependencyGraph: newDependencyGraph);
}
/// <summary>
/// Creates a new solution instance with the project documents in the order by the specified document ids.
/// The specified document ids must be the same as what is already in the project; no adding or removing is allowed.
/// </summary>
public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds)
{
var oldProject = GetRequiredProjectState(projectId);
if (documentIds.Count != oldProject.DocumentStates.Count)
{
throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds));
}
foreach (var id in documentIds)
{
if (!oldProject.DocumentStates.Contains(id))
{
throw new InvalidOperationException($"The document '{id}' does not exist in the project.");
}
}
var newProject = oldProject.UpdateDocumentsOrder(documentIds);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false));
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified metadata references.
/// </summary>
public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences)
{
if (metadataReferences.Count == 0)
{
return this;
}
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.MetadataReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(metadataReferences);
return ForkProject(oldProject.WithMetadataReferences(newReferences));
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified metadata reference.
/// </summary>
public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.MetadataReferences.ToImmutableArray();
var newReferences = oldReferences.Remove(metadataReference);
if (oldReferences == newReferences)
{
return this;
}
return ForkProject(oldProject.WithMetadataReferences(newReferences));
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified metadata references.
/// </summary>
public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithMetadataReferences(metadataReferences);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified analyzer references.
/// </summary>
public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences)
{
if (analyzerReferences.Length == 0)
{
return this;
}
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(analyzerReferences);
return ForkProject(
oldProject.WithAnalyzerReferences(newReferences),
new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language));
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified analyzer reference.
/// </summary>
public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
{
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.Remove(analyzerReference);
if (oldReferences == newReferences)
{
return this;
}
return ForkProject(
oldProject.WithAnalyzerReferences(newReferences),
new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language));
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified analyzer references.
/// </summary>
public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithAnalyzerReferences(analyzerReferences);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the corresponding projects updated to include new
/// documents defined by the document info.
/// </summary>
public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos)
{
return AddDocumentsToMultipleProjects(documentInfos,
(documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions),
(oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents)));
}
/// <summary>
/// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project.
/// </summary>
/// <param name="documentInfos">The set of documents to add.</param>
/// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param>
/// <returns></returns>
private SolutionState AddDocumentsToMultipleProjects<T>(
ImmutableArray<DocumentInfo> documentInfos,
Func<DocumentInfo, ProjectState, T> createDocumentState,
Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState)
where T : TextDocumentState
{
if (documentInfos.IsDefault)
{
throw new ArgumentNullException(nameof(documentInfos));
}
if (documentInfos.IsEmpty)
{
return this;
}
// The documents might be contributing to multiple different projects; split them by project and then we'll process
// project-at-a-time.
var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId);
var newSolutionState = this;
foreach (var documentInfosInProject in documentInfosByProjectId)
{
CheckContainsProject(documentInfosInProject.Key);
var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!;
var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance();
foreach (var documentInfo in documentInfosInProject)
{
newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState));
}
var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree();
var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject);
newSolutionState = newSolutionState.ForkProject(newProjectState,
compilationTranslationAction,
newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject));
}
return newSolutionState;
}
public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos)
{
return AddDocumentsToMultipleProjects(documentInfos,
(documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices),
(projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents)));
}
public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos)
{
// Adding a new analyzer config potentially modifies the compilation options
return AddDocumentsToMultipleProjects(documentInfos,
(documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices),
(oldProject, documents) =>
{
var newProject = oldProject.AddAnalyzerConfigDocuments(documents);
return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true));
});
}
public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds)
{
return RemoveDocumentsFromMultipleProjects(documentIds,
(projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId),
(oldProject, documentIds, _) =>
{
var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds);
return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true));
});
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified document.
/// </summary>
public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds)
{
return RemoveDocumentsFromMultipleProjects(documentIds,
(projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId),
(projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates)));
}
private SolutionState RemoveDocumentsFromMultipleProjects<T>(
ImmutableArray<DocumentId> documentIds,
Func<ProjectState, DocumentId, T> getExistingTextDocumentState,
Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState)
where T : TextDocumentState
{
if (documentIds.IsEmpty)
{
return this;
}
// The documents might be contributing to multiple different projects; split them by project and then we'll process
// project-at-a-time.
var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId);
var newSolutionState = this;
foreach (var documentIdsInProject in documentIdsByProjectId)
{
var oldProjectState = this.GetProjectState(documentIdsInProject.Key);
if (oldProjectState == null)
{
throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key));
}
var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance();
foreach (var documentId in documentIdsInProject)
{
removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId));
}
var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree();
var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject);
newSolutionState = newSolutionState.ForkProject(newProjectState,
compilationTranslationAction,
newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject));
}
return newSolutionState;
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified additional documents.
/// </summary>
public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds)
{
return RemoveDocumentsFromMultipleProjects(documentIds,
(projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId),
(projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates)));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the specified name.
/// </summary>
public SolutionState WithDocumentName(DocumentId documentId, string name)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.Attributes.Name == name)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateName(name));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to be contained in
/// the sequence of logical folders.
/// </summary>
public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.Folders.SequenceEqual(folders))
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateFolders(folders));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the specified file path.
/// </summary>
public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.FilePath == filePath)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateFilePath(filePath));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// specified.
/// </summary>
public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// specified.
/// </summary>
public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAdditionalDocumentState(documentId);
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// specified.
/// </summary>
public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId);
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// and version specified.
/// </summary>
public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// and version specified.
/// </summary>
public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAdditionalDocumentState(documentId);
if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion)
{
return this;
}
return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the analyzer config document specified updated to have the text
/// and version specified.
/// </summary>
public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId);
if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion)
{
return this;
}
return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have a syntax tree
/// rooted by the specified syntax node.
/// </summary>
public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.TryGetSyntaxTree(out var oldTree) &&
oldTree.TryGetRoot(out var oldRoot) &&
oldRoot == root)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true);
}
private static async Task<Compilation> UpdateDocumentInCompilationAsync(
Compilation compilation,
DocumentState oldDocument,
DocumentState newDocument,
CancellationToken cancellationToken)
{
return compilation.ReplaceSyntaxTree(
await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false),
await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the source
/// code kind specified.
/// </summary>
public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.SourceCodeKind == sourceCodeKind)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true);
}
public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode)
{
var oldDocument = GetRequiredDocumentState(documentId);
// Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with
// old content. Also this should make sure we don't re-use latest doc version with data associated with opened document.
return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
var oldDocument = GetRequiredAdditionalDocumentState(documentId);
// Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with
// old content. Also this should make sure we don't re-use latest doc version with data associated with opened document.
return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true);
}
/// <summary>
/// Creates a new solution instance with the analyzer config document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId);
// Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with
// old content. Also this should make sure we don't re-use latest doc version with data associated with opened document.
return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode));
}
private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false)
{
var oldProject = GetProjectState(newDocument.Id.ProjectId)!;
var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions);
// This method shouldn't have been called if the document has not changed.
Debug.Assert(oldProject != newProject);
var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id);
var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath);
return ForkProject(
newProject,
new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument),
newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap);
}
private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false)
{
var oldProject = GetProjectState(newDocument.Id.ProjectId)!;
var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions);
// This method shouldn't have been called if the document has not changed.
Debug.Assert(oldProject != newProject);
var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id);
return ForkProject(
newProject,
translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument));
}
private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument)
{
var oldProject = GetProjectState(newDocument.Id.ProjectId)!;
var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument);
// This method shouldn't have been called if the document has not changed.
Debug.Assert(oldProject != newProject);
return ForkProject(newProject,
newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null);
}
/// <summary>
/// Creates a new snapshot with an updated project and an action that will produce a new
/// compilation matching the new project out of an old compilation. All dependent projects
/// are fixed-up if the change to the new project affects its public metadata, and old
/// dependent compilations are forgotten.
/// </summary>
private SolutionState ForkProject(
ProjectState newProjectState,
CompilationAndGeneratorDriverTranslationAction? translate = null,
ProjectDependencyGraph? newDependencyGraph = null,
ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null,
bool forkTracker = true)
{
var projectId = newProjectState.Id;
var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState);
// Remote supported languages can only change if the project changes language. This is an unexpected edge
// case, so it's not optimized for incremental updates.
var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language
? GetRemoteSupportedProjectLanguages(newStateMap)
: _remoteSupportedLanguages;
newDependencyGraph ??= _dependencyGraph;
var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph);
// If we have a tracker for this project, then fork it as well (along with the
// translation action and store it in the tracker map.
if (newTrackerMap.TryGetValue(projectId, out var tracker))
{
newTrackerMap = newTrackerMap.Remove(projectId);
if (forkTracker)
{
newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate));
}
}
return this.Branch(
idToProjectStateMap: newStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newTrackerMap,
dependencyGraph: newDependencyGraph,
filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap);
}
/// <summary>
/// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a
/// <see cref="TextDocument.FilePath"/> that matches the given file path.
/// </summary>
public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath)
{
if (string.IsNullOrEmpty(filePath))
{
return ImmutableArray<DocumentId>.Empty;
}
return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds)
? documentIds
: ImmutableArray<DocumentId>.Empty;
}
private static ProjectDependencyGraph CreateDependencyGraph(
IReadOnlyList<ProjectId> projectIds,
ImmutableDictionary<ProjectId, ProjectState> projectStates)
{
var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>(
state.Id,
state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet()))
.ToImmutableDictionary();
return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map);
}
private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph)
{
var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>();
IEnumerable<ProjectId>? dependencies = null;
foreach (var (id, tracker) in _projectIdToTrackerMap)
builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState));
return builder.ToImmutable();
// Returns true if 'tracker' can be reused for project 'id'
bool CanReuse(ProjectId id)
{
if (id == changedProjectId)
{
return true;
}
// Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'.
// If the information is not available, do not compute it.
var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id);
if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId))
{
return true;
}
// Compute the set of all projects that depend on 'projectId'. This information answers the same
// question as the previous check, but involves at most one transitive computation within the
// dependency graph.
dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId);
return !dependencies.Contains(id);
}
}
public SolutionState WithOptions(SerializableOptionSet options)
=> Branch(options: options);
public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences)
{
if (analyzerReferences.Count == 0)
{
return this;
}
var oldReferences = AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(analyzerReferences);
return Branch(analyzerReferences: newReferences);
}
public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference)
{
var oldReferences = AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.Remove(analyzerReference);
if (oldReferences == newReferences)
{
return this;
}
return Branch(analyzerReferences: newReferences);
}
public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences)
{
if (analyzerReferences == AnalyzerReferences)
{
return this;
}
return Branch(analyzerReferences: analyzerReferences);
}
// this lock guards all the mutable fields (do not share lock with derived classes)
private NonReentrantLock? _stateLockBackingField;
private NonReentrantLock StateLock
{
get
{
// TODO: why did I need to do a nullable suppression here?
return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!;
}
}
private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation;
private DateTime _timeOfLatestSolutionWithPartialCompilation;
private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation;
/// <summary>
/// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is
/// busy building this compilations.
///
/// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document.
///
/// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead.
/// </summary>
public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken)
{
try
{
var doc = this.GetRequiredDocumentState(documentId);
var tree = doc.GetSyntaxTree(cancellationToken);
using (this.StateLock.DisposableWait(cancellationToken))
{
// in progress solutions are disabled for some testing
if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled)
{
return this;
}
SolutionState? currentPartialSolution = null;
if (_latestSolutionWithPartialCompilation != null)
{
_latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution);
}
var reuseExistingPartialSolution =
currentPartialSolution != null &&
(DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 &&
_documentIdOfLatestSolutionWithPartialCompilation == documentId;
if (reuseExistingPartialSolution)
{
SolutionLogger.UseExistingPartialSolution();
return currentPartialSolution!;
}
// if we don't have one or it is stale, create a new partial solution
var tracker = this.GetCompilationTracker(documentId.ProjectId);
var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken);
var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState);
var newLanguages = _remoteSupportedLanguages;
var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker);
currentPartialSolution = this.Branch(
idToProjectStateMap: newIdToProjectStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newIdToTrackerMap,
dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap));
_latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution);
_timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow;
_documentIdOfLatestSolutionWithPartialCompilation = documentId;
SolutionLogger.CreatePartialSolution();
return currentPartialSolution;
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Creates a new solution instance with all the documents specified updated to have the same specified text.
/// </summary>
public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode)
{
var solution = this;
foreach (var documentId in documentIds)
{
if (documentId == null)
{
continue;
}
var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId);
if (doc != null)
{
if (!doc.TryGetText(out var existingText) || existingText != text)
{
solution = solution.WithDocumentText(documentId, text, mode);
}
}
}
return solution;
}
public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation)
{
CheckContainsProject(projectId);
compilation = null;
return this.TryGetCompilationTracker(projectId, out var tracker)
&& tracker.TryGetCompilation(out compilation);
}
/// <summary>
/// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project
/// does not support compilations.
/// </summary>
/// <remarks>
/// The compilation is guaranteed to have a syntax tree for each document of the project.
/// </remarks>
private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken)
{
// TODO: figure out where this is called and why the nullable suppression is required
return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken);
}
/// <summary>
/// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project
/// does not support compilations.
/// </summary>
/// <remarks>
/// The compilation is guaranteed to have a syntax tree for each document of the project.
/// </remarks>
public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken)
{
return project.SupportsCompilation
? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable()
: SpecializedTasks.Null<Compilation>();
}
/// <summary>
/// Return reference completeness for the given project and all projects this references.
/// </summary>
public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken)
{
// return HasAllInformation when compilation is not supported.
// regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness
return project.SupportsCompilation
? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken)
: project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False;
}
/// <summary>
/// Returns the generated document states for source generated documents.
/// </summary>
public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken)
{
return project.SupportsCompilation
? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken)
: new(TextDocumentStates<SourceGeneratedDocumentState>.Empty);
}
/// <summary>
/// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed.
/// </summary>
/// <remarks>
/// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been
/// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something
/// similarly tricky like that.
/// </remarks>
public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId)
{
return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId);
}
/// <summary>
/// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the
/// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source
/// generated file open, we need to make sure everything lines up.
/// </summary>
public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText)
{
// We won't support freezing multiple source generated documents at once. Although nothing in the implementation
// of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc.
// Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion
// also serves as a good check on the system. If down the road we need to support this, we can remove this check and
// update the out-of-process serialization logic accordingly.
Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document.");
var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId);
SourceGeneratedDocumentState newGeneratedState;
if (existingGeneratedState != null)
{
newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions);
// If the content already matched, we can just reuse the existing state
if (newGeneratedState == existingGeneratedState)
{
return this;
}
}
else
{
var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId);
newGeneratedState = SourceGeneratedDocumentState.Create(
documentIdentity,
sourceText,
projectState.ParseOptions!,
projectState.LanguageServices,
_solutionServices);
}
var projectId = documentIdentity.DocumentId.ProjectId;
var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph);
// We want to create a new snapshot with a new compilation tracker that will do this replacement.
// If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying
// computations). If we don't have one, we'll create one and then wrap it.
if (!newTrackerMap.TryGetValue(projectId, out var existingTracker))
{
existingTracker = CreateCompilationTracker(projectId, this);
}
newTrackerMap = newTrackerMap.SetItem(
projectId,
new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState));
return this.Branch(
projectIdToTrackerMap: newTrackerMap,
frozenSourceGeneratedDocument: newGeneratedState);
}
/// <summary>
/// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>.
/// </summary>
private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new();
/// <summary>
/// Get a metadata reference for the project's compilation
/// </summary>
public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken)
{
try
{
// Get the compilation state for this project. If it's not already created, then this
// will create it. Then force that state to completion and get a metadata reference to it.
var tracker = this.GetCompilationTracker(projectReference.ProjectId);
return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Attempt to get the best readily available compilation for the project. It may be a
/// partially built compilation.
/// </summary>
private MetadataReference? GetPartialMetadataReference(
ProjectReference projectReference,
ProjectState fromProject)
{
// Try to get the compilation state for this project. If it doesn't exist, don't do any
// more work.
if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state))
{
return null;
}
return state.GetPartialMetadataReference(fromProject, projectReference);
}
public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, string name, SymbolFilter filter, CancellationToken cancellationToken)
{
var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(name, filter, cancellationToken);
if (result.HasValue)
{
return result.Value;
}
// it looks like declaration compilation doesn't exist yet. we have to build full compilation
var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false);
if (compilation == null)
{
// some projects don't support compilations (e.g., TypeScript) so there's nothing to check
return false;
}
return compilation.ContainsSymbolsWithName(name, filter, cancellationToken);
}
public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken)
{
var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken);
if (result.HasValue)
{
return result.Value;
}
// it looks like declaration compilation doesn't exist yet. we have to build full compilation
var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false);
if (compilation == null)
{
// some projects don't support compilations (e.g., TypeScript) so there's nothing to check
return false;
}
return compilation.ContainsSymbolsWithName(predicate, filter, cancellationToken);
}
/// <summary>
/// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution.
/// </summary>
public ProjectDependencyGraph GetProjectDependencyGraph()
=> _dependencyGraph;
private void CheckNotContainsProject(ProjectId projectId)
{
if (this.ContainsProject(projectId))
{
throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project);
}
}
private void CheckContainsProject(ProjectId projectId)
{
if (!this.ContainsProject(projectId))
{
throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project);
}
}
internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference)
=> GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference);
internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference)
=> GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference);
internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
=> GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference);
internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId)
=> _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId);
internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages()
=> _remoteSupportedLanguages;
private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates)
{
var builder = ImmutableHashSet.CreateBuilder<string>();
foreach (var projectState in projectStates)
{
if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language))
{
builder.Add(projectState.Value.Language);
}
}
return builder.ToImmutable();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Logging;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a set of projects and their source code documents.
///
/// this is a green node of Solution like ProjectState/DocumentState are for
/// Project and Document.
/// </summary>
internal partial class SolutionState
{
// branch id for this solution
private readonly BranchId _branchId;
// the version of the workspace this solution is from
private readonly int _workspaceVersion;
private readonly SolutionInfo.SolutionAttributes _solutionAttributes;
private readonly SolutionServices _solutionServices;
private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap;
private readonly ImmutableHashSet<string> _remoteSupportedLanguages;
private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap;
private readonly ProjectDependencyGraph _dependencyGraph;
public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences;
// Values for all these are created on demand.
private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap;
// Checksums for this solution state
private readonly ValueSource<SolutionStateChecksums> _lazyChecksums;
/// <summary>
/// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over
/// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset
/// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined
/// for the entire solution). Lock this specific field before reading/writing to it.
/// </summary>
private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new();
// holds on data calculated based on the AnalyzerReferences list
private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers;
/// <summary>
/// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project
/// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the
/// question quickly after computing for the first one. Created on demand.
/// </summary>
private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId;
private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>();
private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState;
private SolutionState(
BranchId branchId,
int workspaceVersion,
SolutionServices solutionServices,
SolutionInfo.SolutionAttributes solutionAttributes,
IReadOnlyList<ProjectId> projectIds,
SerializableOptionSet options,
IReadOnlyList<AnalyzerReference> analyzerReferences,
ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
ImmutableHashSet<string> remoteSupportedLanguages,
ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap,
ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap,
ProjectDependencyGraph dependencyGraph,
Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers,
SourceGeneratedDocumentState? frozenSourceGeneratedDocument)
{
_branchId = branchId;
_workspaceVersion = workspaceVersion;
_solutionAttributes = solutionAttributes;
_solutionServices = solutionServices;
ProjectIds = projectIds;
Options = options;
AnalyzerReferences = analyzerReferences;
_projectIdToProjectStateMap = idToProjectStateMap;
_remoteSupportedLanguages = remoteSupportedLanguages;
_projectIdToTrackerMap = projectIdToTrackerMap;
_filePathToDocumentIdsMap = filePathToDocumentIdsMap;
_dependencyGraph = dependencyGraph;
_lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences);
_frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument;
// when solution state is changed, we recalculate its checksum
_lazyChecksums = new AsyncLazy<SolutionStateChecksums>(
c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true);
CheckInvariants();
// make sure we don't accidentally capture any state but the list of references:
static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences)
=> new(() => new HostDiagnosticAnalyzers(analyzerReferences));
}
public SolutionState(
BranchId primaryBranchId,
SolutionServices solutionServices,
SolutionInfo.SolutionAttributes solutionAttributes,
SerializableOptionSet options,
IReadOnlyList<AnalyzerReference> analyzerReferences)
: this(
primaryBranchId,
workspaceVersion: 0,
solutionServices,
solutionAttributes,
projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(),
options,
analyzerReferences,
idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty,
remoteSupportedLanguages: ImmutableHashSet<string>.Empty,
projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty,
filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase),
dependencyGraph: ProjectDependencyGraph.Empty,
lazyAnalyzers: null,
frozenSourceGeneratedDocument: null)
{
}
public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion)
{
var services = workspace != _solutionServices.Workspace
? new SolutionServices(workspace)
: _solutionServices;
// Note: this will potentially have problems if the workspace services are different, as some services
// get locked-in by document states and project states when first constructed.
return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services);
}
public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value;
public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes;
public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState;
public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap;
public int WorkspaceVersion => _workspaceVersion;
public SolutionServices Services => _solutionServices;
public SerializableOptionSet Options { get; }
/// <summary>
/// branch id of this solution
///
/// currently, it only supports one level of branching. there is a primary branch of a workspace and all other
/// branches that are branched from the primary branch.
///
/// one still can create multiple forked solutions from an already branched solution, but versions among those
/// can't be reliably used and compared.
///
/// version only has a meaning between primary solution and branched one or between solutions from same branch.
/// </summary>
public BranchId BranchId => _branchId;
/// <summary>
/// The Workspace this solution is associated with.
/// </summary>
public Workspace Workspace => _solutionServices.Workspace;
/// <summary>
/// The Id of the solution. Multiple solution instances may share the same Id.
/// </summary>
public SolutionId Id => _solutionAttributes.Id;
/// <summary>
/// The path to the solution file or null if there is no solution file.
/// </summary>
public string? FilePath => _solutionAttributes.FilePath;
/// <summary>
/// The solution version. This equates to the solution file's version.
/// </summary>
public VersionStamp Version => _solutionAttributes.Version;
/// <summary>
/// A list of all the ids for all the projects contained by the solution.
/// </summary>
public IReadOnlyList<ProjectId> ProjectIds { get; }
// Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them.
[Conditional("DEBUG")]
private void CheckInvariants()
{
Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count);
Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count);
// An id shouldn't point at a tracker for a different project.
Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id));
// project ids must be the same:
Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds));
Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds));
Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap)));
}
private SolutionState Branch(
SolutionInfo.SolutionAttributes? solutionAttributes = null,
IReadOnlyList<ProjectId>? projectIds = null,
SerializableOptionSet? options = null,
IReadOnlyList<AnalyzerReference>? analyzerReferences = null,
ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null,
ImmutableHashSet<string>? remoteSupportedProjectLanguages = null,
ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null,
ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null,
ProjectDependencyGraph? dependencyGraph = null,
Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default)
{
var branchId = GetBranchId();
if (idToProjectStateMap is not null)
{
Contract.ThrowIfNull(remoteSupportedProjectLanguages);
}
solutionAttributes ??= _solutionAttributes;
projectIds ??= ProjectIds;
idToProjectStateMap ??= _projectIdToProjectStateMap;
remoteSupportedProjectLanguages ??= _remoteSupportedLanguages;
Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap)));
options ??= Options.WithLanguages(remoteSupportedProjectLanguages);
analyzerReferences ??= AnalyzerReferences;
projectIdToTrackerMap ??= _projectIdToTrackerMap;
filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap;
dependencyGraph ??= _dependencyGraph;
var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState;
var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences);
if (branchId == _branchId &&
solutionAttributes == _solutionAttributes &&
projectIds == ProjectIds &&
options == Options &&
analyzerReferencesEqual &&
idToProjectStateMap == _projectIdToProjectStateMap &&
projectIdToTrackerMap == _projectIdToTrackerMap &&
filePathToDocumentIdsMap == _filePathToDocumentIdsMap &&
dependencyGraph == _dependencyGraph &&
newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState)
{
return this;
}
return new SolutionState(
branchId,
_workspaceVersion,
_solutionServices,
solutionAttributes,
projectIds,
options,
analyzerReferences,
idToProjectStateMap,
remoteSupportedProjectLanguages,
projectIdToTrackerMap,
filePathToDocumentIdsMap,
dependencyGraph,
analyzerReferencesEqual ? _lazyAnalyzers : null,
newFrozenSourceGeneratedDocumentState);
}
private SolutionState CreatePrimarySolution(
BranchId branchId,
int workspaceVersion,
SolutionServices services)
{
if (branchId == _branchId &&
workspaceVersion == _workspaceVersion &&
services == _solutionServices)
{
return this;
}
return new SolutionState(
branchId,
workspaceVersion,
services,
_solutionAttributes,
ProjectIds,
Options,
AnalyzerReferences,
_projectIdToProjectStateMap,
_remoteSupportedLanguages,
_projectIdToTrackerMap,
_filePathToDocumentIdsMap,
_dependencyGraph,
_lazyAnalyzers,
frozenSourceGeneratedDocument: null);
}
private BranchId GetBranchId()
{
// currently we only support one level branching.
// my reasonings are
// 1. it seems there is no-one who needs sub branches.
// 2. this lets us to branch without explicit branch API
return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId;
}
/// <summary>
/// The version of the most recently modified project.
/// </summary>
public VersionStamp GetLatestProjectVersion()
{
// this may produce a version that is out of sync with the actual Document versions.
var latestVersion = VersionStamp.Default;
foreach (var project in this.ProjectStates.Values)
{
latestVersion = project.Version.GetNewerVersion(latestVersion);
}
return latestVersion;
}
/// <summary>
/// True if the solution contains a project with the specified project ID.
/// </summary>
public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId)
=> projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId);
/// <summary>
/// True if the solution contains the document in one of its projects
/// </summary>
public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId)
{
return
documentId != null &&
this.ContainsProject(documentId.ProjectId) &&
this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId);
}
/// <summary>
/// True if the solution contains the additional document in one of its projects
/// </summary>
public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId)
{
return
documentId != null &&
this.ContainsProject(documentId.ProjectId) &&
this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId);
}
/// <summary>
/// True if the solution contains the analyzer config document in one of its projects
/// </summary>
public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId)
{
return
documentId != null &&
this.ContainsProject(documentId.ProjectId) &&
this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId);
}
private DocumentState GetRequiredDocumentState(DocumentId documentId)
=> GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId);
private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId)
=> GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId);
private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId)
=> GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId);
internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId)
{
if (syntaxTree != null)
{
// is this tree known to be associated with a document?
var documentId = DocumentState.GetDocumentIdForTree(syntaxTree);
if (documentId != null && (projectId == null || documentId.ProjectId == projectId))
{
// does this solution even have the document?
var projectState = GetProjectState(documentId.ProjectId);
if (projectState != null)
{
var document = projectState.DocumentStates.GetState(documentId);
if (document != null)
{
// does this document really have the syntax tree?
if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
{
return document;
}
}
else
{
var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId);
if (generatedDocument != null)
{
// does this document really have the syntax tree?
if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
{
return generatedDocument;
}
}
}
}
}
}
return null;
}
public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken)
=> this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken);
public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken)
=> this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken);
public ProjectState? GetProjectState(ProjectId projectId)
{
_projectIdToProjectStateMap.TryGetValue(projectId, out var state);
return state;
}
public ProjectState GetRequiredProjectState(ProjectId projectId)
{
var result = GetProjectState(projectId);
Contract.ThrowIfNull(result);
return result;
}
/// <summary>
/// Gets the <see cref="Project"/> associated with an assembly symbol.
/// </summary>
public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol)
{
if (assemblySymbol == null)
return null;
s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id);
return id == null ? null : this.GetProjectState(id);
}
private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker)
=> _projectIdToTrackerMap.TryGetValue(projectId, out tracker);
private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker;
private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution)
{
var projectState = solution.GetProjectState(projectId);
Contract.ThrowIfNull(projectState);
return new CompilationTracker(projectState);
}
private ICompilationTracker GetCompilationTracker(ProjectId projectId)
{
if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker))
{
tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this);
}
return tracker;
}
private SolutionState AddProject(ProjectId projectId, ProjectState projectState)
{
// changed project list so, increment version.
var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion());
var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId);
var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState);
var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language)
? _remoteSupportedLanguages.Add(projectState.Language)
: _remoteSupportedLanguages;
var newDependencyGraph = _dependencyGraph
.WithAdditionalProject(projectId)
.WithAdditionalProjectReferences(projectId, projectState.ProjectReferences);
// It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow
// dangling references like that. If so, we'll need to link those in too.
foreach (var newState in newStateMap)
{
foreach (var projectReference in newState.Value.ProjectReferences)
{
if (projectReference.ProjectId == projectId)
{
newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences(
newState.Key,
SpecializedCollections.SingletonReadOnlyList(projectReference));
break;
}
}
}
var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph);
var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId]));
return Branch(
solutionAttributes: newSolutionAttributes,
projectIds: newProjectIds,
idToProjectStateMap: newStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newTrackerMap,
filePathToDocumentIdsMap: newFilePathToDocumentIdsMap,
dependencyGraph: newDependencyGraph);
}
/// <summary>
/// Create a new solution instance that includes a project with the specified project information.
/// </summary>
public SolutionState AddProject(ProjectInfo projectInfo)
{
if (projectInfo == null)
{
throw new ArgumentNullException(nameof(projectInfo));
}
var projectId = projectInfo.Id;
var language = projectInfo.Language;
if (language == null)
{
throw new ArgumentNullException(nameof(language));
}
var displayName = projectInfo.Name;
if (displayName == null)
{
throw new ArgumentNullException(nameof(displayName));
}
CheckNotContainsProject(projectId);
var languageServices = this.Workspace.Services.GetLanguageServices(language);
if (languageServices == null)
{
throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language));
}
var newProject = new ProjectState(projectInfo, languageServices, _solutionServices);
return this.AddProject(newProject.Id, newProject);
}
private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates)
{
var builder = _filePathToDocumentIdsMap.ToBuilder();
foreach (var documentState in documentStates)
{
var filePath = documentState.FilePath;
if (RoslynString.IsNullOrEmpty(filePath))
{
continue;
}
builder.MultiAdd(filePath, documentState.Id);
}
return builder.ToImmutable();
}
private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState)
=> projectState.DocumentStates.States.Values
.Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values)
.Concat(projectState.AnalyzerConfigDocumentStates.States.Values);
/// <summary>
/// Create a new solution instance without the project specified.
/// </summary>
public SolutionState RemoveProject(ProjectId projectId)
{
if (projectId == null)
{
throw new ArgumentNullException(nameof(projectId));
}
CheckContainsProject(projectId);
// changed project list so, increment version.
var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion());
var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId);
var newStateMap = _projectIdToProjectStateMap.Remove(projectId);
// Remote supported languages only changes if the removed project is the last project of a supported language.
var newLanguages = _remoteSupportedLanguages;
if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState)
&& RemoteSupportedLanguages.IsSupported(projectState.Language))
{
var stillSupportsLanguage = false;
foreach (var (id, state) in _projectIdToProjectStateMap)
{
if (id == projectId)
continue;
if (state.Language == projectState.Language)
{
stillSupportsLanguage = true;
break;
}
}
if (!stillSupportsLanguage)
{
newLanguages = newLanguages.Remove(projectState.Language);
}
}
var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId);
var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph);
var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId]));
return this.Branch(
solutionAttributes: newSolutionAttributes,
projectIds: newProjectIds,
idToProjectStateMap: newStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newTrackerMap.Remove(projectId),
filePathToDocumentIdsMap: newFilePathToDocumentIdsMap,
dependencyGraph: newDependencyGraph);
}
private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates)
{
var builder = _filePathToDocumentIdsMap.ToBuilder();
foreach (var documentState in documentStates)
{
var filePath = documentState.FilePath;
if (RoslynString.IsNullOrEmpty(filePath))
{
continue;
}
if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id))
{
throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'.");
}
builder.MultiRemove(filePath, documentState.Id);
}
return builder.ToImmutable();
}
private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath)
{
if (oldFilePath == newFilePath)
{
return _filePathToDocumentIdsMap;
}
var builder = _filePathToDocumentIdsMap.ToBuilder();
if (!RoslynString.IsNullOrEmpty(oldFilePath))
{
builder.MultiRemove(oldFilePath, documentId);
}
if (!RoslynString.IsNullOrEmpty(newFilePath))
{
builder.MultiAdd(newFilePath, documentId);
}
return builder.ToImmutable();
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the new
/// assembly name.
/// </summary>
public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithAssemblyName(assemblyName);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName));
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the output file path.
/// </summary>
public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithOutputFilePath(outputFilePath);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the output file path.
/// </summary>
public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the compiler output file path.
/// </summary>
public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithCompilationOutputInfo(info);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the default namespace.
/// </summary>
public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithDefaultNamespace(defaultNamespace);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the name.
/// </summary>
public SolutionState WithProjectName(ProjectId projectId, string name)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithName(name);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Creates a new solution instance with the project specified updated to have the project file path.
/// </summary>
public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithFilePath(filePath);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified compilation options.
/// </summary>
public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithCompilationOptions(options);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false));
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified parse options.
/// </summary>
public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithParseOptions(options);
if (oldProject == newProject)
{
return this;
}
if (Workspace.PartialSemanticsEnabled)
{
// don't fork tracker with queued action since access via partial semantics can become inconsistent (throw).
// Since changing options is rare event, it is okay to start compilation building from scratch.
return ForkProject(newProject, forkTracker: false);
}
else
{
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true));
}
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified hasAllInformation.
/// </summary>
public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithHasAllInformation(hasAllInformation);
if (oldProject == newProject)
{
return this;
}
// fork without any change on compilation.
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to have
/// the specified runAnalyzers.
/// </summary>
public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithRunAnalyzers(runAnalyzers);
if (oldProject == newProject)
{
return this;
}
// fork without any change on compilation.
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include
/// the specified project references.
/// </summary>
public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences)
{
if (projectReferences.Count == 0)
{
return this;
}
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.ProjectReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(projectReferences);
var newProject = oldProject.WithProjectReferences(newReferences);
var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences);
return ForkProject(newProject, newDependencyGraph: newDependencyGraph);
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer
/// include the specified project reference.
/// </summary>
public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference)
{
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.ProjectReferences.ToImmutableArray();
// Note: uses ProjectReference equality to compare references.
var newReferences = oldReferences.Remove(projectReference);
if (oldReferences == newReferences)
{
return this;
}
var newProject = oldProject.WithProjectReferences(newReferences);
ProjectDependencyGraph newDependencyGraph;
if (newProject.ContainsReferenceToProject(projectReference.ProjectId) ||
!_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId))
{
// Two cases:
// 1) The project contained multiple non-equivalent references to the project,
// and not all of them were removed. The dependency graph doesn't change.
// Note that there might be two references to the same project, one with
// extern alias and the other without. These are not considered duplicates.
// 2) The referenced project is not part of the solution and hence not included
// in the dependency graph.
newDependencyGraph = _dependencyGraph;
}
else
{
newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId);
}
return ForkProject(newProject, newDependencyGraph: newDependencyGraph);
}
/// <summary>
/// Create a new solution instance with the project specified updated to contain
/// the specified list of project references.
/// </summary>
public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithProjectReferences(projectReferences);
if (oldProject == newProject)
{
return this;
}
var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences);
return ForkProject(newProject, newDependencyGraph: newDependencyGraph);
}
/// <summary>
/// Creates a new solution instance with the project documents in the order by the specified document ids.
/// The specified document ids must be the same as what is already in the project; no adding or removing is allowed.
/// </summary>
public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds)
{
var oldProject = GetRequiredProjectState(projectId);
if (documentIds.Count != oldProject.DocumentStates.Count)
{
throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds));
}
foreach (var id in documentIds)
{
if (!oldProject.DocumentStates.Contains(id))
{
throw new InvalidOperationException($"The document '{id}' does not exist in the project.");
}
}
var newProject = oldProject.UpdateDocumentsOrder(documentIds);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false));
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified metadata references.
/// </summary>
public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences)
{
if (metadataReferences.Count == 0)
{
return this;
}
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.MetadataReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(metadataReferences);
return ForkProject(oldProject.WithMetadataReferences(newReferences));
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified metadata reference.
/// </summary>
public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference)
{
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.MetadataReferences.ToImmutableArray();
var newReferences = oldReferences.Remove(metadataReference);
if (oldReferences == newReferences)
{
return this;
}
return ForkProject(oldProject.WithMetadataReferences(newReferences));
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified metadata references.
/// </summary>
public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithMetadataReferences(metadataReferences);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the project specified updated to include the
/// specified analyzer references.
/// </summary>
public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences)
{
if (analyzerReferences.Length == 0)
{
return this;
}
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(analyzerReferences);
return ForkProject(
oldProject.WithAnalyzerReferences(newReferences),
new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language));
}
/// <summary>
/// Create a new solution instance with the project specified updated to no longer include
/// the specified analyzer reference.
/// </summary>
public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
{
var oldProject = GetRequiredProjectState(projectId);
var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.Remove(analyzerReference);
if (oldReferences == newReferences)
{
return this;
}
return ForkProject(
oldProject.WithAnalyzerReferences(newReferences),
new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language));
}
/// <summary>
/// Create a new solution instance with the project specified updated to include only the
/// specified analyzer references.
/// </summary>
public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences)
{
var oldProject = GetRequiredProjectState(projectId);
var newProject = oldProject.WithAnalyzerReferences(analyzerReferences);
if (oldProject == newProject)
{
return this;
}
return ForkProject(newProject);
}
/// <summary>
/// Create a new solution instance with the corresponding projects updated to include new
/// documents defined by the document info.
/// </summary>
public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos)
{
return AddDocumentsToMultipleProjects(documentInfos,
(documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions),
(oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents)));
}
/// <summary>
/// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project.
/// </summary>
/// <param name="documentInfos">The set of documents to add.</param>
/// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param>
/// <returns></returns>
private SolutionState AddDocumentsToMultipleProjects<T>(
ImmutableArray<DocumentInfo> documentInfos,
Func<DocumentInfo, ProjectState, T> createDocumentState,
Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState)
where T : TextDocumentState
{
if (documentInfos.IsDefault)
{
throw new ArgumentNullException(nameof(documentInfos));
}
if (documentInfos.IsEmpty)
{
return this;
}
// The documents might be contributing to multiple different projects; split them by project and then we'll process
// project-at-a-time.
var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId);
var newSolutionState = this;
foreach (var documentInfosInProject in documentInfosByProjectId)
{
CheckContainsProject(documentInfosInProject.Key);
var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!;
var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance();
foreach (var documentInfo in documentInfosInProject)
{
newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState));
}
var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree();
var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject);
newSolutionState = newSolutionState.ForkProject(newProjectState,
compilationTranslationAction,
newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject));
}
return newSolutionState;
}
public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos)
{
return AddDocumentsToMultipleProjects(documentInfos,
(documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices),
(projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents)));
}
public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos)
{
// Adding a new analyzer config potentially modifies the compilation options
return AddDocumentsToMultipleProjects(documentInfos,
(documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices),
(oldProject, documents) =>
{
var newProject = oldProject.AddAnalyzerConfigDocuments(documents);
return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true));
});
}
public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds)
{
return RemoveDocumentsFromMultipleProjects(documentIds,
(projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId),
(oldProject, documentIds, _) =>
{
var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds);
return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true));
});
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified document.
/// </summary>
public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds)
{
return RemoveDocumentsFromMultipleProjects(documentIds,
(projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId),
(projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates)));
}
private SolutionState RemoveDocumentsFromMultipleProjects<T>(
ImmutableArray<DocumentId> documentIds,
Func<ProjectState, DocumentId, T> getExistingTextDocumentState,
Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState)
where T : TextDocumentState
{
if (documentIds.IsEmpty)
{
return this;
}
// The documents might be contributing to multiple different projects; split them by project and then we'll process
// project-at-a-time.
var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId);
var newSolutionState = this;
foreach (var documentIdsInProject in documentIdsByProjectId)
{
var oldProjectState = this.GetProjectState(documentIdsInProject.Key);
if (oldProjectState == null)
{
throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key));
}
var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance();
foreach (var documentId in documentIdsInProject)
{
removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId));
}
var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree();
var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject);
newSolutionState = newSolutionState.ForkProject(newProjectState,
compilationTranslationAction,
newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject));
}
return newSolutionState;
}
/// <summary>
/// Creates a new solution instance that no longer includes the specified additional documents.
/// </summary>
public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds)
{
return RemoveDocumentsFromMultipleProjects(documentIds,
(projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId),
(projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates)));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the specified name.
/// </summary>
public SolutionState WithDocumentName(DocumentId documentId, string name)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.Attributes.Name == name)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateName(name));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to be contained in
/// the sequence of logical folders.
/// </summary>
public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.Folders.SequenceEqual(folders))
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateFolders(folders));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the specified file path.
/// </summary>
public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.FilePath == filePath)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateFilePath(filePath));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// specified.
/// </summary>
public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// specified.
/// </summary>
public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAdditionalDocumentState(documentId);
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// specified.
/// </summary>
public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId);
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the text
/// and version specified.
/// </summary>
public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// and version specified.
/// </summary>
public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAdditionalDocumentState(documentId);
if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion)
{
return this;
}
return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true);
}
/// <summary>
/// Creates a new solution instance with the analyzer config document specified updated to have the text
/// and version specified.
/// </summary>
public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId);
if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion)
{
return this;
}
return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have a syntax tree
/// rooted by the specified syntax node.
/// </summary>
public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.TryGetSyntaxTree(out var oldTree) &&
oldTree.TryGetRoot(out var oldRoot) &&
oldRoot == root)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true);
}
private static async Task<Compilation> UpdateDocumentInCompilationAsync(
Compilation compilation,
DocumentState oldDocument,
DocumentState newDocument,
CancellationToken cancellationToken)
{
return compilation.ReplaceSyntaxTree(
await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false),
await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false));
}
/// <summary>
/// Creates a new solution instance with the document specified updated to have the source
/// code kind specified.
/// </summary>
public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind)
{
var oldDocument = GetRequiredDocumentState(documentId);
if (oldDocument.SourceCodeKind == sourceCodeKind)
{
return this;
}
return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true);
}
public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode)
{
var oldDocument = GetRequiredDocumentState(documentId);
// Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with
// old content. Also this should make sure we don't re-use latest doc version with data associated with opened document.
return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true);
}
/// <summary>
/// Creates a new solution instance with the additional document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
var oldDocument = GetRequiredAdditionalDocumentState(documentId);
// Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with
// old content. Also this should make sure we don't re-use latest doc version with data associated with opened document.
return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true);
}
/// <summary>
/// Creates a new solution instance with the analyzer config document specified updated to have the text
/// supplied by the text loader.
/// </summary>
public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode)
{
var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId);
// Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with
// old content. Also this should make sure we don't re-use latest doc version with data associated with opened document.
return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode));
}
private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false)
{
var oldProject = GetProjectState(newDocument.Id.ProjectId)!;
var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions);
// This method shouldn't have been called if the document has not changed.
Debug.Assert(oldProject != newProject);
var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id);
var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath);
return ForkProject(
newProject,
new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument),
newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap);
}
private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false)
{
var oldProject = GetProjectState(newDocument.Id.ProjectId)!;
var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions);
// This method shouldn't have been called if the document has not changed.
Debug.Assert(oldProject != newProject);
var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id);
return ForkProject(
newProject,
translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument));
}
private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument)
{
var oldProject = GetProjectState(newDocument.Id.ProjectId)!;
var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument);
// This method shouldn't have been called if the document has not changed.
Debug.Assert(oldProject != newProject);
return ForkProject(newProject,
newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null);
}
/// <summary>
/// Creates a new snapshot with an updated project and an action that will produce a new
/// compilation matching the new project out of an old compilation. All dependent projects
/// are fixed-up if the change to the new project affects its public metadata, and old
/// dependent compilations are forgotten.
/// </summary>
private SolutionState ForkProject(
ProjectState newProjectState,
CompilationAndGeneratorDriverTranslationAction? translate = null,
ProjectDependencyGraph? newDependencyGraph = null,
ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null,
bool forkTracker = true)
{
var projectId = newProjectState.Id;
var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState);
// Remote supported languages can only change if the project changes language. This is an unexpected edge
// case, so it's not optimized for incremental updates.
var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language
? GetRemoteSupportedProjectLanguages(newStateMap)
: _remoteSupportedLanguages;
newDependencyGraph ??= _dependencyGraph;
var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph);
// If we have a tracker for this project, then fork it as well (along with the
// translation action and store it in the tracker map.
if (newTrackerMap.TryGetValue(projectId, out var tracker))
{
newTrackerMap = newTrackerMap.Remove(projectId);
if (forkTracker)
{
newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate));
}
}
return this.Branch(
idToProjectStateMap: newStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newTrackerMap,
dependencyGraph: newDependencyGraph,
filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap);
}
/// <summary>
/// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a
/// <see cref="TextDocument.FilePath"/> that matches the given file path.
/// </summary>
public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath)
{
if (string.IsNullOrEmpty(filePath))
{
return ImmutableArray<DocumentId>.Empty;
}
return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds)
? documentIds
: ImmutableArray<DocumentId>.Empty;
}
private static ProjectDependencyGraph CreateDependencyGraph(
IReadOnlyList<ProjectId> projectIds,
ImmutableDictionary<ProjectId, ProjectState> projectStates)
{
var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>(
state.Id,
state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet()))
.ToImmutableDictionary();
return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map);
}
private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph)
{
var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>();
IEnumerable<ProjectId>? dependencies = null;
foreach (var (id, tracker) in _projectIdToTrackerMap)
builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState));
return builder.ToImmutable();
// Returns true if 'tracker' can be reused for project 'id'
bool CanReuse(ProjectId id)
{
if (id == changedProjectId)
{
return true;
}
// Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'.
// If the information is not available, do not compute it.
var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id);
if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId))
{
return true;
}
// Compute the set of all projects that depend on 'projectId'. This information answers the same
// question as the previous check, but involves at most one transitive computation within the
// dependency graph.
dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId);
return !dependencies.Contains(id);
}
}
public SolutionState WithOptions(SerializableOptionSet options)
=> Branch(options: options);
public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences)
{
if (analyzerReferences.Count == 0)
{
return this;
}
var oldReferences = AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.AddRange(analyzerReferences);
return Branch(analyzerReferences: newReferences);
}
public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference)
{
var oldReferences = AnalyzerReferences.ToImmutableArray();
var newReferences = oldReferences.Remove(analyzerReference);
if (oldReferences == newReferences)
{
return this;
}
return Branch(analyzerReferences: newReferences);
}
public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences)
{
if (analyzerReferences == AnalyzerReferences)
{
return this;
}
return Branch(analyzerReferences: analyzerReferences);
}
// this lock guards all the mutable fields (do not share lock with derived classes)
private NonReentrantLock? _stateLockBackingField;
private NonReentrantLock StateLock
{
get
{
// TODO: why did I need to do a nullable suppression here?
return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!;
}
}
private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation;
private DateTime _timeOfLatestSolutionWithPartialCompilation;
private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation;
/// <summary>
/// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is
/// busy building this compilations.
///
/// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document.
///
/// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead.
/// </summary>
public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken)
{
try
{
var doc = this.GetRequiredDocumentState(documentId);
var tree = doc.GetSyntaxTree(cancellationToken);
using (this.StateLock.DisposableWait(cancellationToken))
{
// in progress solutions are disabled for some testing
if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled)
{
return this;
}
SolutionState? currentPartialSolution = null;
if (_latestSolutionWithPartialCompilation != null)
{
_latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution);
}
var reuseExistingPartialSolution =
currentPartialSolution != null &&
(DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 &&
_documentIdOfLatestSolutionWithPartialCompilation == documentId;
if (reuseExistingPartialSolution)
{
SolutionLogger.UseExistingPartialSolution();
return currentPartialSolution!;
}
// if we don't have one or it is stale, create a new partial solution
var tracker = this.GetCompilationTracker(documentId.ProjectId);
var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken);
var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState);
var newLanguages = _remoteSupportedLanguages;
var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker);
currentPartialSolution = this.Branch(
idToProjectStateMap: newIdToProjectStateMap,
remoteSupportedProjectLanguages: newLanguages,
projectIdToTrackerMap: newIdToTrackerMap,
dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap));
_latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution);
_timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow;
_documentIdOfLatestSolutionWithPartialCompilation = documentId;
SolutionLogger.CreatePartialSolution();
return currentPartialSolution;
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Creates a new solution instance with all the documents specified updated to have the same specified text.
/// </summary>
public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode)
{
var solution = this;
foreach (var documentId in documentIds)
{
if (documentId == null)
{
continue;
}
var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId);
if (doc != null)
{
if (!doc.TryGetText(out var existingText) || existingText != text)
{
solution = solution.WithDocumentText(documentId, text, mode);
}
}
}
return solution;
}
public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation)
{
CheckContainsProject(projectId);
compilation = null;
return this.TryGetCompilationTracker(projectId, out var tracker)
&& tracker.TryGetCompilation(out compilation);
}
/// <summary>
/// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project
/// does not support compilations.
/// </summary>
/// <remarks>
/// The compilation is guaranteed to have a syntax tree for each document of the project.
/// </remarks>
private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken)
{
// TODO: figure out where this is called and why the nullable suppression is required
return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken);
}
/// <summary>
/// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project
/// does not support compilations.
/// </summary>
/// <remarks>
/// The compilation is guaranteed to have a syntax tree for each document of the project.
/// </remarks>
public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken)
{
return project.SupportsCompilation
? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable()
: SpecializedTasks.Null<Compilation>();
}
/// <summary>
/// Return reference completeness for the given project and all projects this references.
/// </summary>
public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken)
{
// return HasAllInformation when compilation is not supported.
// regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness
return project.SupportsCompilation
? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken)
: project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False;
}
/// <summary>
/// Returns the generated document states for source generated documents.
/// </summary>
public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken)
{
return project.SupportsCompilation
? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken)
: new(TextDocumentStates<SourceGeneratedDocumentState>.Empty);
}
/// <summary>
/// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed.
/// </summary>
/// <remarks>
/// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been
/// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something
/// similarly tricky like that.
/// </remarks>
public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId)
{
return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId);
}
/// <summary>
/// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the
/// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source
/// generated file open, we need to make sure everything lines up.
/// </summary>
public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText)
{
// We won't support freezing multiple source generated documents at once. Although nothing in the implementation
// of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc.
// Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion
// also serves as a good check on the system. If down the road we need to support this, we can remove this check and
// update the out-of-process serialization logic accordingly.
Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document.");
var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId);
SourceGeneratedDocumentState newGeneratedState;
if (existingGeneratedState != null)
{
newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions);
// If the content already matched, we can just reuse the existing state
if (newGeneratedState == existingGeneratedState)
{
return this;
}
}
else
{
var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId);
newGeneratedState = SourceGeneratedDocumentState.Create(
documentIdentity,
sourceText,
projectState.ParseOptions!,
projectState.LanguageServices,
_solutionServices);
}
var projectId = documentIdentity.DocumentId.ProjectId;
var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph);
// We want to create a new snapshot with a new compilation tracker that will do this replacement.
// If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying
// computations). If we don't have one, we'll create one and then wrap it.
if (!newTrackerMap.TryGetValue(projectId, out var existingTracker))
{
existingTracker = CreateCompilationTracker(projectId, this);
}
newTrackerMap = newTrackerMap.SetItem(
projectId,
new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState));
return this.Branch(
projectIdToTrackerMap: newTrackerMap,
frozenSourceGeneratedDocument: newGeneratedState);
}
/// <summary>
/// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>.
/// </summary>
private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new();
/// <summary>
/// Get a metadata reference for the project's compilation
/// </summary>
public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken)
{
try
{
// Get the compilation state for this project. If it's not already created, then this
// will create it. Then force that state to completion and get a metadata reference to it.
var tracker = this.GetCompilationTracker(projectReference.ProjectId);
return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Attempt to get the best readily available compilation for the project. It may be a
/// partially built compilation.
/// </summary>
private MetadataReference? GetPartialMetadataReference(
ProjectReference projectReference,
ProjectState fromProject)
{
// Try to get the compilation state for this project. If it doesn't exist, don't do any
// more work.
if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state))
{
return null;
}
return state.GetPartialMetadataReference(fromProject, projectReference);
}
/// <summary>
/// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution.
/// </summary>
public ProjectDependencyGraph GetProjectDependencyGraph()
=> _dependencyGraph;
private void CheckNotContainsProject(ProjectId projectId)
{
if (this.ContainsProject(projectId))
{
throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project);
}
}
private void CheckContainsProject(ProjectId projectId)
{
if (!this.ContainsProject(projectId))
{
throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project);
}
}
internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference)
=> GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference);
internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference)
=> GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference);
internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference)
=> GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference);
internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId)
=> _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId);
internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages()
=> _remoteSupportedLanguages;
private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates)
{
var builder = ImmutableHashSet.CreateBuilder<string>();
foreach (var projectState in projectStates)
{
if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language))
{
builder.Add(projectState.Value.Language);
}
}
return builder.ToImmutable();
}
}
}
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/VisualBasic/Portable/FindSymbols/VisualBasicDeclaredSymbolInfoFactoryService.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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.FindSymbols
<ExportLanguageService(GetType(IDeclaredSymbolInfoFactoryService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicDeclaredSymbolInfoFactoryService
Inherits AbstractDeclaredSymbolInfoFactoryService(Of
CompilationUnitSyntax,
ImportsStatementSyntax,
NamespaceBlockSyntax,
TypeBlockSyntax,
EnumBlockSyntax,
StatementSyntax)
Private Const ExtensionName As String = "Extension"
Private Const ExtensionAttributeName As String = "ExtensionAttribute"
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Private Shared Function GetInheritanceNames(stringTable As StringTable, typeBlock As TypeBlockSyntax) As ImmutableArray(Of String)
Dim builder = ArrayBuilder(Of String).GetInstance()
Dim aliasMap = GetAliasMap(typeBlock)
Try
For Each inheritsStatement In typeBlock.Inherits
AddInheritanceNames(builder, inheritsStatement.Types, aliasMap)
Next
For Each implementsStatement In typeBlock.Implements
AddInheritanceNames(builder, implementsStatement.Types, aliasMap)
Next
Intern(stringTable, builder)
Return builder.ToImmutableAndFree()
Finally
FreeAliasMap(aliasMap)
End Try
End Function
Private Shared Function GetAliasMap(typeBlock As TypeBlockSyntax) As Dictionary(Of String, String)
Dim compilationUnit = typeBlock.SyntaxTree.GetCompilationUnitRoot()
Dim aliasMap As Dictionary(Of String, String) = Nothing
For Each import In compilationUnit.Imports
For Each clause In import.ImportsClauses
If clause.IsKind(SyntaxKind.SimpleImportsClause) Then
Dim simpleImport = DirectCast(clause, SimpleImportsClauseSyntax)
If simpleImport.Alias IsNot Nothing Then
Dim mappedName = GetTypeName(simpleImport.Name)
If mappedName IsNot Nothing Then
aliasMap = If(aliasMap, AllocateAliasMap())
aliasMap(simpleImport.Alias.Identifier.ValueText) = mappedName
End If
End If
End If
Next
Next
Return aliasMap
End Function
Private Shared Sub AddInheritanceNames(
builder As ArrayBuilder(Of String),
types As SeparatedSyntaxList(Of TypeSyntax),
aliasMap As Dictionary(Of String, String))
For Each typeSyntax In types
AddInheritanceName(builder, typeSyntax, aliasMap)
Next
End Sub
Private Shared Sub AddInheritanceName(
builder As ArrayBuilder(Of String),
typeSyntax As TypeSyntax,
aliasMap As Dictionary(Of String, String))
Dim name = GetTypeName(typeSyntax)
If name IsNot Nothing Then
builder.Add(name)
Dim mappedName As String = Nothing
If aliasMap?.TryGetValue(name, mappedName) = True Then
' Looks Like this could be an alias. Also include the name the alias points to
builder.Add(mappedName)
End If
End If
End Sub
Private Shared Function GetTypeName(typeSyntax As TypeSyntax) As String
If TypeOf typeSyntax Is SimpleNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, SimpleNameSyntax))
ElseIf TypeOf typeSyntax Is QualifiedNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, QualifiedNameSyntax).Right)
End If
Return Nothing
End Function
Private Shared Function GetSimpleName(simpleName As SimpleNameSyntax) As String
Return simpleName.Identifier.ValueText
End Function
Protected Overrides Function GetContainerDisplayName(node As StatementSyntax) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters)
End Function
Protected Overrides Function GetFullyQualifiedContainerName(node As StatementSyntax, rootNamespace As String) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces, rootNamespace)
End Function
Protected Overrides Sub AddDeclaredSymbolInfosWorker(
container As SyntaxNode,
node As StatementSyntax,
stringTable As StringTable,
declaredSymbolInfos As ArrayBuilder(Of DeclaredSymbolInfo),
aliases As Dictionary(Of String, String),
extensionMethodInfo As Dictionary(Of String, ArrayBuilder(Of Integer)),
containerDisplayName As String,
fullyQualifiedContainerName As String,
cancellationToken As CancellationToken)
' If this Is a part of partial type that only contains nested types, then we don't make an info type for it.
' That's because we effectively think of this as just being a virtual container just to hold the nested
' types, And Not something someone would want to explicitly navigate to itself. Similar to how we think of
' namespaces.
Dim typeDecl = TryCast(node, TypeBlockSyntax)
If typeDecl IsNot Nothing AndAlso
typeDecl.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) AndAlso
typeDecl.Members.Any() AndAlso
typeDecl.Members.All(Function(m) TypeOf m Is TypeBlockSyntax) Then
Return
End If
If node.Kind() = SyntaxKind.PropertyBlock Then
node = DirectCast(node, PropertyBlockSyntax).PropertyStatement
ElseIf node.Kind() = SyntaxKind.EventBlock Then
node = DirectCast(node, EventBlockSyntax).EventStatement
ElseIf TypeOf node Is MethodBlockBaseSyntax Then
node = DirectCast(node, MethodBlockBaseSyntax).BlockStatement
End If
Dim kind = node.Kind()
Select Case kind
Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock
Dim typeBlock = CType(node, TypeBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeDecl.BlockStatement.Identifier.ValueText,
GetTypeParameterSuffix(typeBlock.BlockStatement.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
typeBlock.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
If(kind = SyntaxKind.ClassBlock, DeclaredSymbolInfoKind.Class,
If(kind = SyntaxKind.InterfaceBlock, DeclaredSymbolInfoKind.Interface,
If(kind = SyntaxKind.ModuleBlock, DeclaredSymbolInfoKind.Module,
DeclaredSymbolInfoKind.Struct))),
GetAccessibility(container, typeBlock, typeBlock.BlockStatement.Modifiers),
typeBlock.BlockStatement.Identifier.Span,
GetInheritanceNames(stringTable, typeBlock),
IsNestedType(typeBlock)))
Return
Case SyntaxKind.EnumBlock
Dim enumDecl = DirectCast(node, EnumBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumDecl.EnumStatement.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
enumDecl.EnumStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Enum,
GetAccessibility(container, enumDecl, enumDecl.EnumStatement.Modifiers),
enumDecl.EnumStatement.Identifier.Span,
ImmutableArray(Of String).Empty,
IsNestedType(enumDecl)))
Return
Case SyntaxKind.SubNewStatement
Dim constructor = DirectCast(node, SubNewStatementSyntax)
Dim typeBlock = TryCast(container, TypeBlockSyntax)
If typeBlock IsNot Nothing Then
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeBlock.BlockStatement.Identifier.ValueText,
GetConstructorSuffix(constructor),
containerDisplayName,
fullyQualifiedContainerName,
constructor.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Constructor,
GetAccessibility(container, constructor, constructor.Modifiers),
constructor.NewKeyword.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(constructor.ParameterList?.Parameters.Count, 0)))
Return
End If
Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement
Dim delegateDecl = DirectCast(node, DelegateStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
delegateDecl.Identifier.ValueText,
GetTypeParameterSuffix(delegateDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Delegate,
GetAccessibility(container, delegateDecl, delegateDecl.Modifiers),
delegateDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EnumMemberDeclaration
Dim enumMember = DirectCast(node, EnumMemberDeclarationSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumMember.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
isPartial:=False,
DeclaredSymbolInfoKind.EnumMember,
Accessibility.Public,
enumMember.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EventStatement
Dim eventDecl = DirectCast(node, EventStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
eventDecl.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Event,
GetAccessibility(container, eventDecl, eventDecl.Modifiers),
eventDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Dim isExtension = IsExtensionMethod(funcDecl)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
funcDecl.Identifier.ValueText,
GetMethodSuffix(funcDecl),
containerDisplayName,
fullyQualifiedContainerName,
funcDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(isExtension, DeclaredSymbolInfoKind.ExtensionMethod, DeclaredSymbolInfoKind.Method),
GetAccessibility(container, funcDecl, funcDecl.Modifiers),
funcDecl.Identifier.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(funcDecl.ParameterList?.Parameters.Count, 0),
typeParameterCount:=If(funcDecl.TypeParameterList?.Parameters.Count, 0)))
If isExtension Then
AddExtensionMethodInfo(funcDecl, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo)
End If
Return
Case SyntaxKind.PropertyStatement
Dim propertyDecl = DirectCast(node, PropertyStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
propertyDecl.Identifier.ValueText,
GetPropertySuffix(propertyDecl),
containerDisplayName,
fullyQualifiedContainerName,
propertyDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Property,
GetAccessibility(container, propertyDecl, propertyDecl.Modifiers),
propertyDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FieldDeclaration
Dim fieldDecl = DirectCast(node, FieldDeclarationSyntax)
For Each variableDeclarator In fieldDecl.Declarators
For Each modifiedIdentifier In variableDeclarator.Names
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
modifiedIdentifier.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
fieldDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(fieldDecl.Modifiers.Any(Function(m) m.Kind() = SyntaxKind.ConstKeyword),
DeclaredSymbolInfoKind.Constant,
DeclaredSymbolInfoKind.Field),
GetAccessibility(container, fieldDecl, fieldDecl.Modifiers),
modifiedIdentifier.Identifier.Span,
ImmutableArray(Of String).Empty))
Next
Next
End Select
End Sub
Protected Overrides Function GetChildren(node As CompilationUnitSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As NamespaceBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As TypeBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As EnumBlockSyntax) As IEnumerable(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetUsingAliases(node As CompilationUnitSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return node.Imports
End Function
Protected Overrides Function GetUsingAliases(node As NamespaceBlockSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return Nothing
End Function
Private Shared Function IsExtensionMethod(node As MethodStatementSyntax) As Boolean
Dim parameterCount = node.ParameterList?.Parameters.Count
' Extension method must have at least one parameter and declared inside a module
If Not parameterCount.HasValue OrElse parameterCount.Value = 0 OrElse TypeOf node.Parent?.Parent IsNot ModuleBlockSyntax Then
Return False
End If
For Each attributeList In node.AttributeLists
For Each attribute In attributeList.Attributes
' ExtensionAttribute takes no argument.
If attribute.ArgumentList?.Arguments.Count > 0 Then
Continue For
End If
Dim name = attribute.Name.GetRightmostName()?.ToString()
If String.Equals(name, ExtensionName, StringComparison.OrdinalIgnoreCase) OrElse String.Equals(name, ExtensionAttributeName, StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Next
Next
Return False
End Function
Private Shared Function IsNestedType(node As DeclarationStatementSyntax) As Boolean
Return TypeOf node.Parent Is TypeBlockSyntax
End Function
Private Shared Function GetAccessibility(container As SyntaxNode, node As StatementSyntax, modifiers As SyntaxTokenList) As Accessibility
Dim sawFriend = False
For Each modifier In modifiers
Select Case modifier.Kind()
Case SyntaxKind.PublicKeyword : Return Accessibility.Public
Case SyntaxKind.PrivateKeyword : Return Accessibility.Private
Case SyntaxKind.ProtectedKeyword : Return Accessibility.Protected
Case SyntaxKind.FriendKeyword
sawFriend = True
Continue For
End Select
Next
If sawFriend Then
Return Accessibility.Internal
End If
' No accessibility modifiers
Select Case container.Kind()
Case SyntaxKind.ClassBlock
' In a class, fields and shared-constructors are private by default,
' everything Else Is Public
If node.Kind() = SyntaxKind.FieldDeclaration Then
Return Accessibility.Private
End If
If node.Kind() = SyntaxKind.SubNewStatement AndAlso
DirectCast(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword) Then
Return Accessibility.Private
End If
Return Accessibility.Public
Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
' Everything in a struct/interface/module is public
Return Accessibility.Public
End Select
' Otherwise, it's internal
Return Accessibility.Internal
End Function
Private Shared Function GetMethodSuffix(method As MethodStatementSyntax) As String
Return GetTypeParameterSuffix(method.TypeParameterList) & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetConstructorSuffix(method As SubNewStatementSyntax) As String
Return ".New" & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetPropertySuffix([property] As PropertyStatementSyntax) As String
If [property].ParameterList Is Nothing Then
Return Nothing
End If
Return GetSuffix([property].ParameterList)
End Function
Private Shared Function GetTypeParameterSuffix(typeParameterList As TypeParameterListSyntax) As String
If typeParameterList Is Nothing Then
Return Nothing
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("(Of ")
Dim First = True
For Each parameter In typeParameterList.Parameters
If Not First Then
builder.Append(", ")
End If
builder.Append(parameter.Identifier.Text)
First = False
Next
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
''' <summary>
''' Builds up the suffix to show for something with parameters in navigate-to.
''' While it would be nice to just use the compiler SymbolDisplay API for this,
''' it would be too expensive as it requires going back to Symbols (which requires
''' creating compilations, etc.) in a perf sensitive area.
'''
''' So, instead, we just build a reasonable suffix using the pure syntax that a
''' user provided. That means that if they wrote "Method(System.Int32 i)" we'll
''' show that as "Method(System.Int32)" Not "Method(Integer)". Given that this Is
''' actually what the user wrote, And it saves us from ever having to go back to
''' symbols/compilations, this Is well worth it, even if it does mean we have to
''' create our own 'symbol display' logic here.
''' </summary>
Private Shared Function GetSuffix(parameterList As ParameterListSyntax) As String
If parameterList Is Nothing OrElse parameterList.Parameters.Count = 0 Then
Return "()"
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("("c)
If parameterList IsNot Nothing Then
AppendParameters(parameterList.Parameters, builder)
End If
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
Private Shared Sub AppendParameters(parameters As SeparatedSyntaxList(Of ParameterSyntax), builder As StringBuilder)
Dim First = True
For Each parameter In parameters
If Not First Then
builder.Append(", ")
End If
For Each modifier In parameter.Modifiers
If modifier.Kind() <> SyntaxKind.ByValKeyword Then
builder.Append(modifier.Text)
builder.Append(" "c)
End If
Next
If parameter.AsClause?.Type IsNot Nothing Then
AppendTokens(parameter.AsClause.Type, builder)
End If
First = False
Next
End Sub
Protected Overrides Function GetReceiverTypeName(node As StatementSyntax) As String
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Debug.Assert(IsExtensionMethod(funcDecl))
Dim typeParameterNames = funcDecl.TypeParameterList?.Parameters.SelectAsArray(Function(p) p.Identifier.Text)
Dim targetTypeName As String = Nothing
Dim isArray As Boolean = False
TryGetSimpleTypeNameWorker(funcDecl.ParameterList.Parameters(0).AsClause?.Type, typeParameterNames, targetTypeName, isArray)
Return CreateReceiverTypeString(targetTypeName, isArray)
End Function
Protected Overrides Function TryGetAliasesFromUsingDirective(importStatement As ImportsStatementSyntax, ByRef aliases As ImmutableArray(Of (aliasName As String, name As String))) As Boolean
Dim builder = ArrayBuilder(Of (String, String)).GetInstance()
If importStatement IsNot Nothing Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
Dim aliasName, name As String
#Disable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
If simpleImportsClause.Alias IsNot Nothing AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause.Alias, Nothing, aliasName, Nothing) AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause, Nothing, name, Nothing) Then
#Enable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
builder.Add((aliasName, name))
End If
End If
Next
aliases = builder.ToImmutableAndFree()
Return True
End If
aliases = Nothing
Return False
End Function
Private Shared Function TryGetSimpleTypeNameWorker(node As SyntaxNode, typeParameterNames As ImmutableArray(Of String)?, ByRef simpleTypeName As String, ByRef isArray As Boolean) As Boolean
isArray = False
If TypeOf node Is IdentifierNameSyntax Then
Dim identifierName = DirectCast(node, IdentifierNameSyntax)
Dim text = identifierName.Identifier.Text
simpleTypeName = If(typeParameterNames?.Contains(text), Nothing, text)
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is ArrayTypeSyntax Then
isArray = True
Dim arrayType = DirectCast(node, ArrayTypeSyntax)
Return TryGetSimpleTypeNameWorker(arrayType.ElementType, typeParameterNames, simpleTypeName, Nothing)
ElseIf TypeOf node Is GenericNameSyntax Then
Dim genericName = DirectCast(node, GenericNameSyntax)
Dim name = genericName.Identifier.Text
Dim arity = genericName.Arity
simpleTypeName = If(arity = 0, name, name + ArityUtilities.GetMetadataAritySuffix(arity))
Return True
ElseIf TypeOf node Is QualifiedNameSyntax Then
' For an identifier to the right of a '.', it can't be a type parameter,
' so we don't need to check for it further.
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
Return TryGetSimpleTypeNameWorker(qualifiedName.Right, Nothing, simpleTypeName, Nothing)
ElseIf TypeOf node Is NullableTypeSyntax Then
Return TryGetSimpleTypeNameWorker(DirectCast(node, NullableTypeSyntax).ElementType, typeParameterNames, simpleTypeName, isArray)
ElseIf TypeOf node Is PredefinedTypeSyntax Then
simpleTypeName = GetSpecialTypeName(DirectCast(node, PredefinedTypeSyntax))
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is TupleTypeSyntax Then
Dim tupleArity = DirectCast(node, TupleTypeSyntax).Elements.Count
simpleTypeName = CreateValueTupleTypeString(tupleArity)
Return True
End If
simpleTypeName = Nothing
Return False
End Function
Private Shared Function GetSpecialTypeName(predefinedTypeNode As PredefinedTypeSyntax) As String
Select Case predefinedTypeNode.Keyword.Kind()
Case SyntaxKind.BooleanKeyword
Return "Boolean"
Case SyntaxKind.ByteKeyword
Return "Byte"
Case SyntaxKind.CharKeyword
Return "Char"
Case SyntaxKind.DateKeyword
Return "DateTime"
Case SyntaxKind.DecimalKeyword
Return "Decimal"
Case SyntaxKind.DoubleKeyword
Return "Double"
Case SyntaxKind.IntegerKeyword
Return "Int32"
Case SyntaxKind.LongKeyword
Return "Int64"
Case SyntaxKind.ObjectKeyword
Return "Object"
Case SyntaxKind.SByteKeyword
Return "SByte"
Case SyntaxKind.ShortKeyword
Return "Int16"
Case SyntaxKind.SingleKeyword
Return "Single"
Case SyntaxKind.StringKeyword
Return "String"
Case SyntaxKind.UIntegerKeyword
Return "UInt32"
Case SyntaxKind.ULongKeyword
Return "UInt64"
Case SyntaxKind.UShortKeyword
Return "UInt16"
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetRootNamespace(compilationOptions As CompilationOptions) As String
Return DirectCast(compilationOptions, VisualBasicCompilationOptions).RootNamespace
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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.FindSymbols
<ExportLanguageService(GetType(IDeclaredSymbolInfoFactoryService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicDeclaredSymbolInfoFactoryService
Inherits AbstractDeclaredSymbolInfoFactoryService(Of
CompilationUnitSyntax,
ImportsStatementSyntax,
NamespaceBlockSyntax,
TypeBlockSyntax,
EnumBlockSyntax,
StatementSyntax,
NameSyntax,
QualifiedNameSyntax,
IdentifierNameSyntax)
Private Const ExtensionName As String = "Extension"
Private Const ExtensionAttributeName As String = "ExtensionAttribute"
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Private Shared Function GetInheritanceNames(stringTable As StringTable, typeBlock As TypeBlockSyntax) As ImmutableArray(Of String)
Dim builder = ArrayBuilder(Of String).GetInstance()
Dim aliasMap = GetAliasMap(typeBlock)
Try
For Each inheritsStatement In typeBlock.Inherits
AddInheritanceNames(builder, inheritsStatement.Types, aliasMap)
Next
For Each implementsStatement In typeBlock.Implements
AddInheritanceNames(builder, implementsStatement.Types, aliasMap)
Next
Intern(stringTable, builder)
Return builder.ToImmutableAndFree()
Finally
FreeAliasMap(aliasMap)
End Try
End Function
Private Shared Function GetAliasMap(typeBlock As TypeBlockSyntax) As Dictionary(Of String, String)
Dim compilationUnit = typeBlock.SyntaxTree.GetCompilationUnitRoot()
Dim aliasMap As Dictionary(Of String, String) = Nothing
For Each import In compilationUnit.Imports
For Each clause In import.ImportsClauses
If clause.IsKind(SyntaxKind.SimpleImportsClause) Then
Dim simpleImport = DirectCast(clause, SimpleImportsClauseSyntax)
If simpleImport.Alias IsNot Nothing Then
Dim mappedName = GetTypeName(simpleImport.Name)
If mappedName IsNot Nothing Then
aliasMap = If(aliasMap, AllocateAliasMap())
aliasMap(simpleImport.Alias.Identifier.ValueText) = mappedName
End If
End If
End If
Next
Next
Return aliasMap
End Function
Private Shared Sub AddInheritanceNames(
builder As ArrayBuilder(Of String),
types As SeparatedSyntaxList(Of TypeSyntax),
aliasMap As Dictionary(Of String, String))
For Each typeSyntax In types
AddInheritanceName(builder, typeSyntax, aliasMap)
Next
End Sub
Private Shared Sub AddInheritanceName(
builder As ArrayBuilder(Of String),
typeSyntax As TypeSyntax,
aliasMap As Dictionary(Of String, String))
Dim name = GetTypeName(typeSyntax)
If name IsNot Nothing Then
builder.Add(name)
Dim mappedName As String = Nothing
If aliasMap?.TryGetValue(name, mappedName) = True Then
' Looks Like this could be an alias. Also include the name the alias points to
builder.Add(mappedName)
End If
End If
End Sub
Private Shared Function GetTypeName(typeSyntax As TypeSyntax) As String
If TypeOf typeSyntax Is SimpleNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, SimpleNameSyntax))
ElseIf TypeOf typeSyntax Is QualifiedNameSyntax Then
Return GetSimpleName(DirectCast(typeSyntax, QualifiedNameSyntax).Right)
End If
Return Nothing
End Function
Private Shared Function GetSimpleName(simpleName As SimpleNameSyntax) As String
Return simpleName.Identifier.ValueText
End Function
Protected Overrides Function GetContainerDisplayName(node As StatementSyntax) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters)
End Function
Protected Overrides Function GetFullyQualifiedContainerName(node As StatementSyntax, rootNamespace As String) As String
Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces, rootNamespace)
End Function
Protected Overrides Sub AddDeclaredSymbolInfosWorker(
container As SyntaxNode,
node As StatementSyntax,
stringTable As StringTable,
declaredSymbolInfos As ArrayBuilder(Of DeclaredSymbolInfo),
aliases As Dictionary(Of String, String),
extensionMethodInfo As Dictionary(Of String, ArrayBuilder(Of Integer)),
containerDisplayName As String,
fullyQualifiedContainerName As String,
cancellationToken As CancellationToken)
' If this Is a part of partial type that only contains nested types, then we don't make an info type for it.
' That's because we effectively think of this as just being a virtual container just to hold the nested
' types, And Not something someone would want to explicitly navigate to itself. Similar to how we think of
' namespaces.
Dim typeDecl = TryCast(node, TypeBlockSyntax)
If typeDecl IsNot Nothing AndAlso
typeDecl.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) AndAlso
typeDecl.Members.Any() AndAlso
typeDecl.Members.All(Function(m) TypeOf m Is TypeBlockSyntax) Then
Return
End If
If node.Kind() = SyntaxKind.PropertyBlock Then
node = DirectCast(node, PropertyBlockSyntax).PropertyStatement
ElseIf node.Kind() = SyntaxKind.EventBlock Then
node = DirectCast(node, EventBlockSyntax).EventStatement
ElseIf TypeOf node Is MethodBlockBaseSyntax Then
node = DirectCast(node, MethodBlockBaseSyntax).BlockStatement
End If
Dim kind = node.Kind()
Select Case kind
Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock
Dim typeBlock = CType(node, TypeBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeDecl.BlockStatement.Identifier.ValueText,
GetTypeParameterSuffix(typeBlock.BlockStatement.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
typeBlock.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
If(kind = SyntaxKind.ClassBlock, DeclaredSymbolInfoKind.Class,
If(kind = SyntaxKind.InterfaceBlock, DeclaredSymbolInfoKind.Interface,
If(kind = SyntaxKind.ModuleBlock, DeclaredSymbolInfoKind.Module,
DeclaredSymbolInfoKind.Struct))),
GetAccessibility(container, typeBlock, typeBlock.BlockStatement.Modifiers),
typeBlock.BlockStatement.Identifier.Span,
GetInheritanceNames(stringTable, typeBlock),
IsNestedType(typeBlock)))
Return
Case SyntaxKind.EnumBlock
Dim enumDecl = DirectCast(node, EnumBlockSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumDecl.EnumStatement.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
enumDecl.EnumStatement.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Enum,
GetAccessibility(container, enumDecl, enumDecl.EnumStatement.Modifiers),
enumDecl.EnumStatement.Identifier.Span,
ImmutableArray(Of String).Empty,
IsNestedType(enumDecl)))
Return
Case SyntaxKind.SubNewStatement
Dim constructor = DirectCast(node, SubNewStatementSyntax)
Dim typeBlock = TryCast(container, TypeBlockSyntax)
If typeBlock IsNot Nothing Then
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
typeBlock.BlockStatement.Identifier.ValueText,
GetConstructorSuffix(constructor),
containerDisplayName,
fullyQualifiedContainerName,
constructor.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Constructor,
GetAccessibility(container, constructor, constructor.Modifiers),
constructor.NewKeyword.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(constructor.ParameterList?.Parameters.Count, 0)))
Return
End If
Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement
Dim delegateDecl = DirectCast(node, DelegateStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
delegateDecl.Identifier.ValueText,
GetTypeParameterSuffix(delegateDecl.TypeParameterList),
containerDisplayName,
fullyQualifiedContainerName,
delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Delegate,
GetAccessibility(container, delegateDecl, delegateDecl.Modifiers),
delegateDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EnumMemberDeclaration
Dim enumMember = DirectCast(node, EnumMemberDeclarationSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
enumMember.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
isPartial:=False,
DeclaredSymbolInfoKind.EnumMember,
Accessibility.Public,
enumMember.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.EventStatement
Dim eventDecl = DirectCast(node, EventStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
eventDecl.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Event,
GetAccessibility(container, eventDecl, eventDecl.Modifiers),
eventDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Dim isExtension = IsExtensionMethod(funcDecl)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
funcDecl.Identifier.ValueText,
GetMethodSuffix(funcDecl),
containerDisplayName,
fullyQualifiedContainerName,
funcDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(isExtension, DeclaredSymbolInfoKind.ExtensionMethod, DeclaredSymbolInfoKind.Method),
GetAccessibility(container, funcDecl, funcDecl.Modifiers),
funcDecl.Identifier.Span,
ImmutableArray(Of String).Empty,
parameterCount:=If(funcDecl.ParameterList?.Parameters.Count, 0),
typeParameterCount:=If(funcDecl.TypeParameterList?.Parameters.Count, 0)))
If isExtension Then
AddExtensionMethodInfo(funcDecl, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo)
End If
Return
Case SyntaxKind.PropertyStatement
Dim propertyDecl = DirectCast(node, PropertyStatementSyntax)
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
propertyDecl.Identifier.ValueText,
GetPropertySuffix(propertyDecl),
containerDisplayName,
fullyQualifiedContainerName,
propertyDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
DeclaredSymbolInfoKind.Property,
GetAccessibility(container, propertyDecl, propertyDecl.Modifiers),
propertyDecl.Identifier.Span,
ImmutableArray(Of String).Empty))
Return
Case SyntaxKind.FieldDeclaration
Dim fieldDecl = DirectCast(node, FieldDeclarationSyntax)
For Each variableDeclarator In fieldDecl.Declarators
For Each modifiedIdentifier In variableDeclarator.Names
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
modifiedIdentifier.Identifier.ValueText, Nothing,
containerDisplayName,
fullyQualifiedContainerName,
fieldDecl.Modifiers.Any(SyntaxKind.PartialKeyword),
If(fieldDecl.Modifiers.Any(Function(m) m.Kind() = SyntaxKind.ConstKeyword),
DeclaredSymbolInfoKind.Constant,
DeclaredSymbolInfoKind.Field),
GetAccessibility(container, fieldDecl, fieldDecl.Modifiers),
modifiedIdentifier.Identifier.Span,
ImmutableArray(Of String).Empty))
Next
Next
End Select
End Sub
Protected Overrides Function GetChildren(node As CompilationUnitSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As NamespaceBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As TypeBlockSyntax) As SyntaxList(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetChildren(node As EnumBlockSyntax) As IEnumerable(Of StatementSyntax)
Return node.Members
End Function
Protected Overrides Function GetUsingAliases(node As CompilationUnitSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return node.Imports
End Function
Protected Overrides Function GetUsingAliases(node As NamespaceBlockSyntax) As SyntaxList(Of ImportsStatementSyntax)
Return Nothing
End Function
Protected Overrides Function GetName(node As NamespaceBlockSyntax) As NameSyntax
Return node.NamespaceStatement.Name
End Function
Protected Overrides Function GetLeft(node As QualifiedNameSyntax) As NameSyntax
Return node.Left
End Function
Protected Overrides Function GetRight(node As QualifiedNameSyntax) As NameSyntax
Return node.Right
End Function
Protected Overrides Function GetIdentifier(node As IdentifierNameSyntax) As SyntaxToken
Return node.Identifier
End Function
Private Shared Function IsExtensionMethod(node As MethodStatementSyntax) As Boolean
Dim parameterCount = node.ParameterList?.Parameters.Count
' Extension method must have at least one parameter and declared inside a module
If Not parameterCount.HasValue OrElse parameterCount.Value = 0 OrElse TypeOf node.Parent?.Parent IsNot ModuleBlockSyntax Then
Return False
End If
For Each attributeList In node.AttributeLists
For Each attribute In attributeList.Attributes
' ExtensionAttribute takes no argument.
If attribute.ArgumentList?.Arguments.Count > 0 Then
Continue For
End If
Dim name = attribute.Name.GetRightmostName()?.ToString()
If String.Equals(name, ExtensionName, StringComparison.OrdinalIgnoreCase) OrElse String.Equals(name, ExtensionAttributeName, StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Next
Next
Return False
End Function
Private Shared Function IsNestedType(node As DeclarationStatementSyntax) As Boolean
Return TypeOf node.Parent Is TypeBlockSyntax
End Function
Private Shared Function GetAccessibility(container As SyntaxNode, node As StatementSyntax, modifiers As SyntaxTokenList) As Accessibility
Dim sawFriend = False
For Each modifier In modifiers
Select Case modifier.Kind()
Case SyntaxKind.PublicKeyword : Return Accessibility.Public
Case SyntaxKind.PrivateKeyword : Return Accessibility.Private
Case SyntaxKind.ProtectedKeyword : Return Accessibility.Protected
Case SyntaxKind.FriendKeyword
sawFriend = True
Continue For
End Select
Next
If sawFriend Then
Return Accessibility.Internal
End If
' No accessibility modifiers
Select Case container.Kind()
Case SyntaxKind.ClassBlock
' In a class, fields and shared-constructors are private by default,
' everything Else Is Public
If node.Kind() = SyntaxKind.FieldDeclaration Then
Return Accessibility.Private
End If
If node.Kind() = SyntaxKind.SubNewStatement AndAlso
DirectCast(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword) Then
Return Accessibility.Private
End If
Return Accessibility.Public
Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
' Everything in a struct/interface/module is public
Return Accessibility.Public
End Select
' Otherwise, it's internal
Return Accessibility.Internal
End Function
Private Shared Function GetMethodSuffix(method As MethodStatementSyntax) As String
Return GetTypeParameterSuffix(method.TypeParameterList) & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetConstructorSuffix(method As SubNewStatementSyntax) As String
Return ".New" & GetSuffix(method.ParameterList)
End Function
Private Shared Function GetPropertySuffix([property] As PropertyStatementSyntax) As String
If [property].ParameterList Is Nothing Then
Return Nothing
End If
Return GetSuffix([property].ParameterList)
End Function
Private Shared Function GetTypeParameterSuffix(typeParameterList As TypeParameterListSyntax) As String
If typeParameterList Is Nothing Then
Return Nothing
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("(Of ")
Dim First = True
For Each parameter In typeParameterList.Parameters
If Not First Then
builder.Append(", ")
End If
builder.Append(parameter.Identifier.Text)
First = False
Next
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
''' <summary>
''' Builds up the suffix to show for something with parameters in navigate-to.
''' While it would be nice to just use the compiler SymbolDisplay API for this,
''' it would be too expensive as it requires going back to Symbols (which requires
''' creating compilations, etc.) in a perf sensitive area.
'''
''' So, instead, we just build a reasonable suffix using the pure syntax that a
''' user provided. That means that if they wrote "Method(System.Int32 i)" we'll
''' show that as "Method(System.Int32)" Not "Method(Integer)". Given that this Is
''' actually what the user wrote, And it saves us from ever having to go back to
''' symbols/compilations, this Is well worth it, even if it does mean we have to
''' create our own 'symbol display' logic here.
''' </summary>
Private Shared Function GetSuffix(parameterList As ParameterListSyntax) As String
If parameterList Is Nothing OrElse parameterList.Parameters.Count = 0 Then
Return "()"
End If
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
builder.Append("("c)
If parameterList IsNot Nothing Then
AppendParameters(parameterList.Parameters, builder)
End If
builder.Append(")"c)
Return pooledBuilder.ToStringAndFree()
End Function
Private Shared Sub AppendParameters(parameters As SeparatedSyntaxList(Of ParameterSyntax), builder As StringBuilder)
Dim First = True
For Each parameter In parameters
If Not First Then
builder.Append(", ")
End If
For Each modifier In parameter.Modifiers
If modifier.Kind() <> SyntaxKind.ByValKeyword Then
builder.Append(modifier.Text)
builder.Append(" "c)
End If
Next
If parameter.AsClause?.Type IsNot Nothing Then
AppendTokens(parameter.AsClause.Type, builder)
End If
First = False
Next
End Sub
Protected Overrides Function GetReceiverTypeName(node As StatementSyntax) As String
Dim funcDecl = DirectCast(node, MethodStatementSyntax)
Debug.Assert(IsExtensionMethod(funcDecl))
Dim typeParameterNames = funcDecl.TypeParameterList?.Parameters.SelectAsArray(Function(p) p.Identifier.Text)
Dim targetTypeName As String = Nothing
Dim isArray As Boolean = False
TryGetSimpleTypeNameWorker(funcDecl.ParameterList.Parameters(0).AsClause?.Type, typeParameterNames, targetTypeName, isArray)
Return CreateReceiverTypeString(targetTypeName, isArray)
End Function
Protected Overrides Function TryGetAliasesFromUsingDirective(importStatement As ImportsStatementSyntax, ByRef aliases As ImmutableArray(Of (aliasName As String, name As String))) As Boolean
Dim builder = ArrayBuilder(Of (String, String)).GetInstance()
If importStatement IsNot Nothing Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
Dim aliasName, name As String
#Disable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
If simpleImportsClause.Alias IsNot Nothing AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause.Alias, Nothing, aliasName, Nothing) AndAlso
TryGetSimpleTypeNameWorker(simpleImportsClause, Nothing, name, Nothing) Then
#Enable Warning BC42030 ' Variable is passed by reference before it has been assigned a value
builder.Add((aliasName, name))
End If
End If
Next
aliases = builder.ToImmutableAndFree()
Return True
End If
aliases = Nothing
Return False
End Function
Private Shared Function TryGetSimpleTypeNameWorker(node As SyntaxNode, typeParameterNames As ImmutableArray(Of String)?, ByRef simpleTypeName As String, ByRef isArray As Boolean) As Boolean
isArray = False
If TypeOf node Is IdentifierNameSyntax Then
Dim identifierName = DirectCast(node, IdentifierNameSyntax)
Dim text = identifierName.Identifier.Text
simpleTypeName = If(typeParameterNames?.Contains(text), Nothing, text)
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is ArrayTypeSyntax Then
isArray = True
Dim arrayType = DirectCast(node, ArrayTypeSyntax)
Return TryGetSimpleTypeNameWorker(arrayType.ElementType, typeParameterNames, simpleTypeName, Nothing)
ElseIf TypeOf node Is GenericNameSyntax Then
Dim genericName = DirectCast(node, GenericNameSyntax)
Dim name = genericName.Identifier.Text
Dim arity = genericName.Arity
simpleTypeName = If(arity = 0, name, name + ArityUtilities.GetMetadataAritySuffix(arity))
Return True
ElseIf TypeOf node Is QualifiedNameSyntax Then
' For an identifier to the right of a '.', it can't be a type parameter,
' so we don't need to check for it further.
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
Return TryGetSimpleTypeNameWorker(qualifiedName.Right, Nothing, simpleTypeName, Nothing)
ElseIf TypeOf node Is NullableTypeSyntax Then
Return TryGetSimpleTypeNameWorker(DirectCast(node, NullableTypeSyntax).ElementType, typeParameterNames, simpleTypeName, isArray)
ElseIf TypeOf node Is PredefinedTypeSyntax Then
simpleTypeName = GetSpecialTypeName(DirectCast(node, PredefinedTypeSyntax))
Return simpleTypeName IsNot Nothing
ElseIf TypeOf node Is TupleTypeSyntax Then
Dim tupleArity = DirectCast(node, TupleTypeSyntax).Elements.Count
simpleTypeName = CreateValueTupleTypeString(tupleArity)
Return True
End If
simpleTypeName = Nothing
Return False
End Function
Private Shared Function GetSpecialTypeName(predefinedTypeNode As PredefinedTypeSyntax) As String
Select Case predefinedTypeNode.Keyword.Kind()
Case SyntaxKind.BooleanKeyword
Return "Boolean"
Case SyntaxKind.ByteKeyword
Return "Byte"
Case SyntaxKind.CharKeyword
Return "Char"
Case SyntaxKind.DateKeyword
Return "DateTime"
Case SyntaxKind.DecimalKeyword
Return "Decimal"
Case SyntaxKind.DoubleKeyword
Return "Double"
Case SyntaxKind.IntegerKeyword
Return "Int32"
Case SyntaxKind.LongKeyword
Return "Int64"
Case SyntaxKind.ObjectKeyword
Return "Object"
Case SyntaxKind.SByteKeyword
Return "SByte"
Case SyntaxKind.ShortKeyword
Return "Int16"
Case SyntaxKind.SingleKeyword
Return "Single"
Case SyntaxKind.StringKeyword
Return "String"
Case SyntaxKind.UIntegerKeyword
Return "UInt32"
Case SyntaxKind.ULongKeyword
Return "UInt64"
Case SyntaxKind.UShortKeyword
Return "UInt16"
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetRootNamespace(compilationOptions As CompilationOptions) As String
Return DirectCast(compilationOptions, VisualBasicCompilationOptions).RootNamespace
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundTryCast.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
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundTryCast
Public Sub New(
syntax As SyntaxNode,
operand As BoundExpression,
conversionKind As ConversionKind,
type As TypeSymbol,
Optional hasErrors As Boolean = False
)
Me.New(syntax, operand, conversionKind, constantValueOpt:=Nothing, type:=type, hasErrors:=hasErrors)
End Sub
Public Sub New(
syntax As SyntaxNode,
operand As BoundExpression,
conversionKind As ConversionKind,
relaxationLambdaOpt As BoundLambda,
type As TypeSymbol,
Optional hasErrors As Boolean = False
)
Me.New(syntax, operand, conversionKind, constantValueOpt:=Nothing, relaxationLambdaOpt:=relaxationLambdaOpt, type:=type, hasErrors:=hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
Me.New(syntax, operand, conversionKind, constantValueOpt, relaxationLambdaOpt:=Nothing, type:=type, hasErrors:=hasErrors)
End Sub
Public Overrides ReadOnly Property ExplicitCastInCode As Boolean
Get
Return True
End Get
End Property
#If DEBUG Then
Private Sub Validate()
ValidateConstantValue()
Operand.AssertRValue()
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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundTryCast
Public Sub New(
syntax As SyntaxNode,
operand As BoundExpression,
conversionKind As ConversionKind,
type As TypeSymbol,
Optional hasErrors As Boolean = False
)
Me.New(syntax, operand, conversionKind, constantValueOpt:=Nothing, type:=type, hasErrors:=hasErrors)
End Sub
Public Sub New(
syntax As SyntaxNode,
operand As BoundExpression,
conversionKind As ConversionKind,
relaxationLambdaOpt As BoundLambda,
type As TypeSymbol,
Optional hasErrors As Boolean = False
)
Me.New(syntax, operand, conversionKind, constantValueOpt:=Nothing, relaxationLambdaOpt:=relaxationLambdaOpt, type:=type, hasErrors:=hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
Me.New(syntax, operand, conversionKind, constantValueOpt, relaxationLambdaOpt:=Nothing, type:=type, hasErrors:=hasErrors)
End Sub
Public Overrides ReadOnly Property ExplicitCastInCode As Boolean
Get
Return True
End Get
End Property
#If DEBUG Then
Private Sub Validate()
ValidateConstantValue()
Operand.AssertRValue()
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/CSharpTest2/Recommendations/DelegateKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class DelegateKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
await VerifyAbsenceAsync(
@"using Goo = d$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
await VerifyAbsenceAsync(
@"global using Goo = d$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingAliasTypeParameter()
{
await VerifyKeywordAsync(
@"using Goo = T<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGlobalUsingAliasTypeParameter()
{
await VerifyKeywordAsync(
@"global using Goo = T<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
=> await VerifyAbsenceAsync(@"abstract $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSealed()
=> await VerifyAbsenceAsync(@"sealed $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatic()
{
await VerifyKeywordAsync(SourceCodeKind.Regular, @"static $$");
await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$");
}
[WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))]
public async Task TestAfterKeywordIndicatingLocalFunction(string keyword)
{
await VerifyKeywordAsync(SourceCodeKind.Regular, AddInsideMethod(@$"{keyword} $$"));
await VerifyKeywordAsync(SourceCodeKind.Script, AddInsideMethod(@$"{keyword} $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticPublic()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$");
await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegate()
=> await VerifyKeywordAsync(@"delegate $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateAsArgument()
{
await VerifyKeywordAsync(AddInsideMethod(
@"Assert.Throws<InvalidOperationException>($$"));
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInConstMemberInitializer1()
{
await VerifyAbsenceAsync(
@"class E {
const int a = $$
}");
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnumMemberInitializer1()
{
await VerifyAbsenceAsync(
@"enum E {
a = $$
}");
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInConstLocalInitializer1()
{
await VerifyAbsenceAsync(
@"class E {
void Goo() {
const int a = $$
}
}");
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInMemberInitializer1()
{
await VerifyKeywordAsync(
@"class E {
int a = $$
}");
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(607197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607197")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsyncInMethodBody()
{
await VerifyKeywordAsync(@"
using System;
class C
{
void M()
{
Action a = async $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsyncInMemberDeclaration()
{
await VerifyKeywordAsync(@"
using System;
class C
{
async $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeList()
{
await VerifyKeywordAsync(@"
using System;
class C
{
delegate*<$$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class DelegateKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
await VerifyAbsenceAsync(
@"using Goo = d$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
await VerifyAbsenceAsync(
@"global using Goo = d$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingAliasTypeParameter()
{
await VerifyKeywordAsync(
@"using Goo = T<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGlobalUsingAliasTypeParameter()
{
await VerifyKeywordAsync(
@"global using Goo = T<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
=> await VerifyAbsenceAsync(@"abstract $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSealed()
=> await VerifyAbsenceAsync(@"sealed $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatic()
{
await VerifyKeywordAsync(SourceCodeKind.Regular, @"static $$");
await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$");
}
[WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))]
public async Task TestAfterKeywordIndicatingLocalFunction(string keyword)
{
await VerifyKeywordAsync(SourceCodeKind.Regular, AddInsideMethod(@$"{keyword} $$"));
await VerifyKeywordAsync(SourceCodeKind.Script, AddInsideMethod(@$"{keyword} $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStaticPublic()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$");
await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegate()
=> await VerifyKeywordAsync(@"delegate $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestDelegateAsArgument()
{
await VerifyKeywordAsync(AddInsideMethod(
@"Assert.Throws<InvalidOperationException>($$"));
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInConstMemberInitializer1()
{
await VerifyAbsenceAsync(
@"class E {
const int a = $$
}");
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnumMemberInitializer1()
{
await VerifyAbsenceAsync(
@"enum E {
a = $$
}");
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInConstLocalInitializer1()
{
await VerifyAbsenceAsync(
@"class E {
void Goo() {
const int a = $$
}
}");
}
[WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInMemberInitializer1()
{
await VerifyKeywordAsync(
@"class E {
int a = $$
}");
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(607197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607197")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsyncInMethodBody()
{
await VerifyKeywordAsync(@"
using System;
class C
{
void M()
{
Action a = async $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsyncInMemberDeclaration()
{
await VerifyKeywordAsync(@"
using System;
class C
{
async $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeList()
{
await VerifyKeywordAsync(@"
using System;
class C
{
delegate*<$$");
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/CSharp/Portable/Errors/CSharpDiagnosticFormatter.cs | // Licensed to the .NET Foundation under one or more 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
{
public class CSharpDiagnosticFormatter : DiagnosticFormatter
{
internal CSharpDiagnosticFormatter()
{
}
public static new CSharpDiagnosticFormatter Instance { get; } = new CSharpDiagnosticFormatter();
}
}
| // Licensed to the .NET Foundation under one or more 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
{
public class CSharpDiagnosticFormatter : DiagnosticFormatter
{
internal CSharpDiagnosticFormatter()
{
}
public static new CSharpDiagnosticFormatter Instance { get; } = new CSharpDiagnosticFormatter();
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeNamespace;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace
{
[ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeNamespaceService :
AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeNamespaceService()
{
}
protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync(
Document document,
SyntaxNode container,
CancellationToken cancellationToken)
{
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles
|| document.IsGeneratedCode(cancellationToken))
{
return default;
}
TextSpan containerSpan;
if (container is BaseNamespaceDeclarationSyntax)
{
containerSpan = container.Span;
}
else if (container is CompilationUnitSyntax)
{
// A compilation unit as container means user want to move all its members from global to some namespace.
// We use an empty span to indicate this case.
containerSpan = default;
}
else
{
throw ExceptionUtilities.Unreachable;
}
if (!IsSupportedLinkedDocument(document, out var allDocumentIds))
return default;
return await TryGetApplicableContainersFromAllDocumentsAsync(
document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false);
}
protected override string GetDeclaredNamespace(SyntaxNode container)
{
if (container is CompilationUnitSyntax)
return string.Empty;
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl);
throw ExceptionUtilities.Unreachable;
}
protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container)
{
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return namespaceDecl.Members;
if (container is CompilationUnitSyntax compilationUnit)
return compilationUnit.Members;
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed.
/// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on
/// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead.
/// </summary>
/// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from
/// `SymbolFinder.FindReferencesAsync`.</param>
/// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference
/// will be replaced with given namespace in the new node.</param>
/// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param>
/// <param name="newNode">The replacement node.</param>
public override bool TryGetReplacementReferenceSyntax(
SyntaxNode reference,
ImmutableArray<string> newNamespaceParts,
ISyntaxFactsService syntaxFacts,
[NotNullWhen(returnValue: true)] out SyntaxNode? oldNode,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (reference is not SimpleNameSyntax nameRef)
{
oldNode = newNode = null;
return false;
}
// A few different cases are handled here:
//
// 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done.
// And both old and new will point to the original reference.
//
// 2. When the new namespace is not specified, we don't need to change the qualified part of reference.
// Both old and new will point to the qualified reference.
//
// 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace.
// As a result, we need replace qualified reference with the simple name.
//
// 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global
// namespace. We need to replace the qualified reference with a new qualified reference (which is qualified
// with new namespace.)
//
// Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases.
if (syntaxFacts.IsRightSideOfQualifiedName(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) ||
syntaxFacts.IsNameOfMemberBindingExpression(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref)
{
// This is the case where the reference is the right most part of a qualified name in `cref`.
// for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`.
// This is the form of `cref` we need to handle as a spacial case when changing namespace name or
// changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the
// same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`.
var container = qualifiedCref.Container;
var aliasQualifier = GetAliasQualifier(container);
if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
// We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`,
// which is a alias qualified simple name, similar to the regular case above.
oldNode = qualifiedCref;
newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!);
}
else
{
// if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`,
// which is just a regular namespace node, no cref node involve here.
oldNode = container;
newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
}
return true;
}
// Simple name reference, nothing to be done.
// The name will be resolved by adding proper import.
oldNode = newNode = nameRef;
return false;
}
private static bool TryGetGlobalQualifiedName(
ImmutableArray<string> newNamespaceParts,
SimpleNameSyntax nameNode,
string? aliasQualifier,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (IsGlobalNamespace(newNamespaceParts))
{
// If new namespace is "", then name will be declared in global namespace.
// We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified)
var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia());
return true;
}
newNode = null;
return false;
}
/// <summary>
/// Try to change the namespace declaration based on the following rules:
/// - if neither declared nor target namespace are "" (i.e. global namespace),
/// then we try to change the name of the namespace.
/// - if declared namespace is "", then we try to move all types declared
/// in global namespace in the document into a new namespace declaration.
/// - if target namespace is "", then we try to move all members in declared
/// namespace to global namespace (i.e. remove the namespace declaration).
/// </summary>
protected override CompilationUnitSyntax ChangeNamespaceDeclaration(
CompilationUnitSyntax root,
ImmutableArray<string> declaredNamespaceParts,
ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault);
var container = root.GetAnnotatedNodes(ContainerAnnotation).Single();
if (container is CompilationUnitSyntax compilationUnit)
{
// Move everything from global namespace to a namespace declaration
Debug.Assert(IsGlobalNamespace(declaredNamespaceParts));
return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts);
}
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
{
// Move everything to global namespace
if (IsGlobalNamespace(targetNamespaceParts))
return MoveMembersFromNamespaceToGlobal(root, namespaceDecl);
// Change namespace name
return root.ReplaceNode(
namespaceDecl,
namespaceDecl.WithName(
CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation))
.WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added
}
throw ExceptionUtilities.Unreachable;
}
private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal(
CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl)
{
var (namespaceOpeningTrivia, namespaceClosingTrivia) =
GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl);
var members = namespaceDecl.Members;
var eofToken = root.EndOfFileToken
.WithAdditionalAnnotations(WarningAnnotation);
// Try to preserve trivia from original namespace declaration.
// If there's any member inside the declaration, we attach them to the
// first and last member, otherwise, simply attach all to the EOF token.
if (members.Count > 0)
{
var first = members.First();
var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia);
members = members.Replace(first, firstWithTrivia);
var last = members.Last();
var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia);
members = members.Replace(last, lastWithTrivia);
}
else
{
eofToken = eofToken.WithPrependedLeadingTrivia(
namespaceOpeningTrivia.Concat(namespaceClosingTrivia));
}
// Moving inner imports out of the namespace declaration can lead to a break in semantics.
// For example:
//
// namespace A.B.C
// {
// using D.E.F;
// }
//
// The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside,
// it may fail to resolve.
return root.Update(
root.Externs.AddRange(namespaceDecl.Externs),
root.Usings.AddRange(namespaceDecl.Usings),
root.AttributeLists,
root.Members.ReplaceRange(namespaceDecl, members),
eofToken);
}
private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax));
var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration(
name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithAdditionalAnnotations(WarningAnnotation),
externs: default,
usings: default,
members: compilationUnit.Members);
return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl))
.WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added
}
/// <summary>
/// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace
/// declaration or a compilation unit, contain no partial declarations and meet the following additional
/// requirements:
///
/// - If a namespace declaration:
/// 1. It doesn't contain or is nested in other namespace declarations
/// 2. The name of the namespace is valid (i.e. no errors)
///
/// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration
/// inside (i.e. all members are declared in global namespace)
/// </summary>
protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(syntaxRoot);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
SyntaxNode? container = null;
// Empty span means that user wants to move all types declared in the document to a new namespace.
// This action is only supported when everything in the document is declared in global namespace,
// which we use the number of namespace declaration nodes to decide.
if (span.IsEmpty)
{
if (ContainsNamespaceDeclaration(compilationUnit))
return null;
container = compilationUnit;
}
else
{
// Otherwise, the span should contain a namespace declaration node, which must be the only one
// in the entire syntax spine to enable the change namespace operation.
if (!compilationUnit.Span.Contains(span))
return null;
var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true);
var namespaceDecls = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().ToImmutableArray();
if (namespaceDecls.Length != 1)
return null;
var namespaceDecl = namespaceDecls[0];
if (namespaceDecl == null)
return null;
if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error))
return null;
if (ContainsNamespaceDeclaration(node))
return null;
container = namespaceDecl;
}
var containsPartial =
await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false);
if (containsPartial)
return null;
return container;
static bool ContainsNamespaceDeclaration(SyntaxNode node)
=> node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax)
.OfType<BaseNamespaceDeclarationSyntax>().Any();
}
private static string? GetAliasQualifier(SyntaxNode? name)
{
while (true)
{
switch (name)
{
case QualifiedNameSyntax qualifiedNameNode:
name = qualifiedNameNode.Left;
continue;
case MemberAccessExpressionSyntax memberAccessNode:
name = memberAccessNode.Expression;
continue;
case AliasQualifiedNameSyntax aliasQualifiedNameNode:
return aliasQualifiedNameNode.Alias.Identifier.ValueText;
}
return null;
}
}
private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece);
}
private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
{
return aliasQualifier == null
? (NameSyntax)namePiece
: SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
}
return SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1),
namePiece);
}
/// <summary>
/// return trivia attached to namespace declaration.
/// Leading trivia of the node and trivia around opening brace, as well as
/// trivia around closing brace are concatenated together respectively.
/// </summary>
private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia)
GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace)
{
var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
openingBuilder.AddRange(baseNamespace.GetLeadingTrivia());
if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration)
{
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia);
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia);
}
else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace)
{
openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia);
}
return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeNamespace;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace
{
[ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeNamespaceService :
AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeNamespaceService()
{
}
protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync(
Document document,
SyntaxNode container,
CancellationToken cancellationToken)
{
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles
|| document.IsGeneratedCode(cancellationToken))
{
return default;
}
TextSpan containerSpan;
if (container is BaseNamespaceDeclarationSyntax)
{
containerSpan = container.Span;
}
else if (container is CompilationUnitSyntax)
{
// A compilation unit as container means user want to move all its members from global to some namespace.
// We use an empty span to indicate this case.
containerSpan = default;
}
else
{
throw ExceptionUtilities.Unreachable;
}
if (!IsSupportedLinkedDocument(document, out var allDocumentIds))
return default;
return await TryGetApplicableContainersFromAllDocumentsAsync(
document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false);
}
protected override string GetDeclaredNamespace(SyntaxNode container)
{
if (container is CompilationUnitSyntax)
return string.Empty;
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl);
throw ExceptionUtilities.Unreachable;
}
protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container)
{
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return namespaceDecl.Members;
if (container is CompilationUnitSyntax compilationUnit)
return compilationUnit.Members;
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed.
/// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on
/// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead.
/// </summary>
/// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from
/// `SymbolFinder.FindReferencesAsync`.</param>
/// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference
/// will be replaced with given namespace in the new node.</param>
/// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param>
/// <param name="newNode">The replacement node.</param>
public override bool TryGetReplacementReferenceSyntax(
SyntaxNode reference,
ImmutableArray<string> newNamespaceParts,
ISyntaxFactsService syntaxFacts,
[NotNullWhen(returnValue: true)] out SyntaxNode? oldNode,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (reference is not SimpleNameSyntax nameRef)
{
oldNode = newNode = null;
return false;
}
// A few different cases are handled here:
//
// 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done.
// And both old and new will point to the original reference.
//
// 2. When the new namespace is not specified, we don't need to change the qualified part of reference.
// Both old and new will point to the qualified reference.
//
// 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace.
// As a result, we need replace qualified reference with the simple name.
//
// 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global
// namespace. We need to replace the qualified reference with a new qualified reference (which is qualified
// with new namespace.)
//
// Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases.
if (syntaxFacts.IsRightSideOfQualifiedName(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) ||
syntaxFacts.IsNameOfMemberBindingExpression(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref)
{
// This is the case where the reference is the right most part of a qualified name in `cref`.
// for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`.
// This is the form of `cref` we need to handle as a spacial case when changing namespace name or
// changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the
// same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`.
var container = qualifiedCref.Container;
var aliasQualifier = GetAliasQualifier(container);
if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
// We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`,
// which is a alias qualified simple name, similar to the regular case above.
oldNode = qualifiedCref;
newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!);
}
else
{
// if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`,
// which is just a regular namespace node, no cref node involve here.
oldNode = container;
newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
}
return true;
}
// Simple name reference, nothing to be done.
// The name will be resolved by adding proper import.
oldNode = newNode = nameRef;
return false;
}
private static bool TryGetGlobalQualifiedName(
ImmutableArray<string> newNamespaceParts,
SimpleNameSyntax nameNode,
string? aliasQualifier,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (IsGlobalNamespace(newNamespaceParts))
{
// If new namespace is "", then name will be declared in global namespace.
// We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified)
var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia());
return true;
}
newNode = null;
return false;
}
/// <summary>
/// Try to change the namespace declaration based on the following rules:
/// - if neither declared nor target namespace are "" (i.e. global namespace),
/// then we try to change the name of the namespace.
/// - if declared namespace is "", then we try to move all types declared
/// in global namespace in the document into a new namespace declaration.
/// - if target namespace is "", then we try to move all members in declared
/// namespace to global namespace (i.e. remove the namespace declaration).
/// </summary>
protected override CompilationUnitSyntax ChangeNamespaceDeclaration(
CompilationUnitSyntax root,
ImmutableArray<string> declaredNamespaceParts,
ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault);
var container = root.GetAnnotatedNodes(ContainerAnnotation).Single();
if (container is CompilationUnitSyntax compilationUnit)
{
// Move everything from global namespace to a namespace declaration
Debug.Assert(IsGlobalNamespace(declaredNamespaceParts));
return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts);
}
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
{
// Move everything to global namespace
if (IsGlobalNamespace(targetNamespaceParts))
return MoveMembersFromNamespaceToGlobal(root, namespaceDecl);
// Change namespace name
return root.ReplaceNode(
namespaceDecl,
namespaceDecl.WithName(
CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation))
.WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added
}
throw ExceptionUtilities.Unreachable;
}
private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal(
CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl)
{
var (namespaceOpeningTrivia, namespaceClosingTrivia) =
GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl);
var members = namespaceDecl.Members;
var eofToken = root.EndOfFileToken
.WithAdditionalAnnotations(WarningAnnotation);
// Try to preserve trivia from original namespace declaration.
// If there's any member inside the declaration, we attach them to the
// first and last member, otherwise, simply attach all to the EOF token.
if (members.Count > 0)
{
var first = members.First();
var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia);
members = members.Replace(first, firstWithTrivia);
var last = members.Last();
var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia);
members = members.Replace(last, lastWithTrivia);
}
else
{
eofToken = eofToken.WithPrependedLeadingTrivia(
namespaceOpeningTrivia.Concat(namespaceClosingTrivia));
}
// Moving inner imports out of the namespace declaration can lead to a break in semantics.
// For example:
//
// namespace A.B.C
// {
// using D.E.F;
// }
//
// The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside,
// it may fail to resolve.
return root.Update(
root.Externs.AddRange(namespaceDecl.Externs),
root.Usings.AddRange(namespaceDecl.Usings),
root.AttributeLists,
root.Members.ReplaceRange(namespaceDecl, members),
eofToken);
}
private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax));
var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration(
name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithAdditionalAnnotations(WarningAnnotation),
externs: default,
usings: default,
members: compilationUnit.Members);
return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl))
.WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added
}
/// <summary>
/// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace
/// declaration or a compilation unit, contain no partial declarations and meet the following additional
/// requirements:
///
/// - If a namespace declaration:
/// 1. It doesn't contain or is nested in other namespace declarations
/// 2. The name of the namespace is valid (i.e. no errors)
///
/// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration
/// inside (i.e. all members are declared in global namespace)
/// </summary>
protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(syntaxRoot);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
SyntaxNode? container = null;
// Empty span means that user wants to move all types declared in the document to a new namespace.
// This action is only supported when everything in the document is declared in global namespace,
// which we use the number of namespace declaration nodes to decide.
if (span.IsEmpty)
{
if (ContainsNamespaceDeclaration(compilationUnit))
return null;
container = compilationUnit;
}
else
{
// Otherwise, the span should contain a namespace declaration node, which must be the only one
// in the entire syntax spine to enable the change namespace operation.
if (!compilationUnit.Span.Contains(span))
return null;
var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true);
var namespaceDecls = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().ToImmutableArray();
if (namespaceDecls.Length != 1)
return null;
var namespaceDecl = namespaceDecls[0];
if (namespaceDecl == null)
return null;
if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error))
return null;
if (ContainsNamespaceDeclaration(node))
return null;
container = namespaceDecl;
}
var containsPartial =
await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false);
if (containsPartial)
return null;
return container;
static bool ContainsNamespaceDeclaration(SyntaxNode node)
=> node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax)
.OfType<BaseNamespaceDeclarationSyntax>().Any();
}
private static string? GetAliasQualifier(SyntaxNode? name)
{
while (true)
{
switch (name)
{
case QualifiedNameSyntax qualifiedNameNode:
name = qualifiedNameNode.Left;
continue;
case MemberAccessExpressionSyntax memberAccessNode:
name = memberAccessNode.Expression;
continue;
case AliasQualifiedNameSyntax aliasQualifiedNameNode:
return aliasQualifiedNameNode.Alias.Identifier.ValueText;
}
return null;
}
}
private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece);
}
private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
{
return aliasQualifier == null
? (NameSyntax)namePiece
: SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
}
return SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1),
namePiece);
}
/// <summary>
/// return trivia attached to namespace declaration.
/// Leading trivia of the node and trivia around opening brace, as well as
/// trivia around closing brace are concatenated together respectively.
/// </summary>
private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia)
GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace)
{
var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
openingBuilder.AddRange(baseNamespace.GetLeadingTrivia());
if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration)
{
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia);
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia);
}
else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace)
{
openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia);
}
return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree());
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/CSharpTest2/Recommendations/ModuleKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ModuleKeywordRecommenderTests : 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 TestNotInAttributeInsideClass()
{
await VerifyAbsenceAsync(
@"class C {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterAttributeInsideClass()
{
await VerifyAbsenceAsync(
@"class C {
[Goo]
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterMethod()
{
await VerifyAbsenceAsync(
@"class C {
void Goo() {
}
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterProperty()
{
await VerifyAbsenceAsync(
@"class C {
int Goo {
get;
}
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterField()
{
await VerifyAbsenceAsync(
@"class C {
int Goo;
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterEvent()
{
await VerifyAbsenceAsync(
@"class C {
event Action<int> Goo;
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInOuterAttribute()
{
await VerifyKeywordAsync(
@"[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInOuterAttributeInNamespace()
{
await VerifyAbsenceAsync(
@"namespace Goo {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInParameterAttribute()
{
await VerifyAbsenceAsync(
@"class C {
void Goo([$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAttribute()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEventAttribute()
{
await VerifyAbsenceAsync(
@"class C {
event Action<int> Goo { [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClassModuleParameters()
{
await VerifyAbsenceAsync(
@"class C<[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInDelegateModuleParameters()
{
await VerifyAbsenceAsync(
@"delegate void D<[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInMethodModuleParameters()
{
await VerifyAbsenceAsync(
@"class C {
void M<[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInInterface()
{
await VerifyAbsenceAsync(
@"interface I {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInStruct()
{
await VerifyAbsenceAsync(
@"struct S {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnum()
{
await VerifyAbsenceAsync(
@"enum E {
[$$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ModuleKeywordRecommenderTests : 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 TestNotInAttributeInsideClass()
{
await VerifyAbsenceAsync(
@"class C {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterAttributeInsideClass()
{
await VerifyAbsenceAsync(
@"class C {
[Goo]
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterMethod()
{
await VerifyAbsenceAsync(
@"class C {
void Goo() {
}
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterProperty()
{
await VerifyAbsenceAsync(
@"class C {
int Goo {
get;
}
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterField()
{
await VerifyAbsenceAsync(
@"class C {
int Goo;
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInAttributeAfterEvent()
{
await VerifyAbsenceAsync(
@"class C {
event Action<int> Goo;
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInOuterAttribute()
{
await VerifyKeywordAsync(
@"[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInOuterAttributeInNamespace()
{
await VerifyAbsenceAsync(
@"namespace Goo {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInParameterAttribute()
{
await VerifyAbsenceAsync(
@"class C {
void Goo([$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAttribute()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEventAttribute()
{
await VerifyAbsenceAsync(
@"class C {
event Action<int> Goo { [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClassModuleParameters()
{
await VerifyAbsenceAsync(
@"class C<[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInDelegateModuleParameters()
{
await VerifyAbsenceAsync(
@"delegate void D<[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInMethodModuleParameters()
{
await VerifyAbsenceAsync(
@"class C {
void M<[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInInterface()
{
await VerifyAbsenceAsync(
@"interface I {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInStruct()
{
await VerifyAbsenceAsync(
@"struct S {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnum()
{
await VerifyAbsenceAsync(
@"enum E {
[$$");
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpKeywordHighlighting.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpKeywordHighlighting : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpKeywordHighlighting(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpKeywordHighlighting))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void Foreach()
{
var input = @"class C
{
void M()
{
[|foreach|](var c in """") { if(true) [|break|]; else [|continue|]; }
}
}";
Roslyn.Test.Utilities.MarkupTestFile.GetSpans(input, out var text, out ImmutableArray<TextSpan> spans);
VisualStudio.Editor.SetText(text);
Verify("foreach", spans);
Verify("break", spans);
Verify("continue", spans);
Verify("in", ImmutableArray.Create<TextSpan>());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void PreprocessorConditionals()
{
var input = @"
#define Debug
#undef Trace
class PurchaseTransaction
{
void Commit() {
{|if:#if|} Debug
CheckConsistency();
{|else:#if|} Trace
WriteToLog(this.ToString());
{|else:#else|}
Exit();
{|else:#endif|}
{|if:#endif|}
CommitHelper();
}
}";
Test.Utilities.MarkupTestFile.GetSpans(
input,
out var text,
out IDictionary<string, ImmutableArray<TextSpan>> spans);
VisualStudio.Editor.SetText(text);
Verify("#if", spans["if"]);
Verify("#else", spans["else"]);
Verify("#endif", spans["else"]);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void PreprocessorRegions()
{
var input = @"
class C
{
[|#region|] Main
static void Main()
{
}
[|#endregion|]
}";
Test.Utilities.MarkupTestFile.GetSpans(
input,
out var text,
out ImmutableArray<TextSpan> spans);
VisualStudio.Editor.SetText(text);
Verify("#region", spans);
Verify("#endregion", spans);
}
private void Verify(string marker, ImmutableArray<TextSpan> expectedCount)
{
VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.Classification,
FeatureAttribute.KeywordHighlighting);
Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpKeywordHighlighting : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpKeywordHighlighting(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpKeywordHighlighting))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void Foreach()
{
var input = @"class C
{
void M()
{
[|foreach|](var c in """") { if(true) [|break|]; else [|continue|]; }
}
}";
Roslyn.Test.Utilities.MarkupTestFile.GetSpans(input, out var text, out ImmutableArray<TextSpan> spans);
VisualStudio.Editor.SetText(text);
Verify("foreach", spans);
Verify("break", spans);
Verify("continue", spans);
Verify("in", ImmutableArray.Create<TextSpan>());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void PreprocessorConditionals()
{
var input = @"
#define Debug
#undef Trace
class PurchaseTransaction
{
void Commit() {
{|if:#if|} Debug
CheckConsistency();
{|else:#if|} Trace
WriteToLog(this.ToString());
{|else:#else|}
Exit();
{|else:#endif|}
{|if:#endif|}
CommitHelper();
}
}";
Test.Utilities.MarkupTestFile.GetSpans(
input,
out var text,
out IDictionary<string, ImmutableArray<TextSpan>> spans);
VisualStudio.Editor.SetText(text);
Verify("#if", spans["if"]);
Verify("#else", spans["else"]);
Verify("#endif", spans["else"]);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Classification)]
public void PreprocessorRegions()
{
var input = @"
class C
{
[|#region|] Main
static void Main()
{
}
[|#endregion|]
}";
Test.Utilities.MarkupTestFile.GetSpans(
input,
out var text,
out ImmutableArray<TextSpan> spans);
VisualStudio.Editor.SetText(text);
Verify("#region", spans);
Verify("#endregion", spans);
}
private void Verify(string marker, ImmutableArray<TextSpan> expectedCount)
{
VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.Classification,
FeatureAttribute.KeywordHighlighting);
Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags());
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/CSharp/LanguageServices/CSharpContentTypeLanguageService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices
{
[ExportContentTypeLanguageService(ContentTypeNames.CSharpContentType, LanguageNames.CSharp), Shared]
internal class CSharpContentTypeLanguageService : IContentTypeLanguageService
{
private readonly IContentTypeRegistryService _contentTypeRegistry;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpContentTypeLanguageService(IContentTypeRegistryService contentTypeRegistry)
=> _contentTypeRegistry = contentTypeRegistry;
public IContentType GetDefaultContentType()
=> _contentTypeRegistry.GetContentType(ContentTypeNames.CSharpContentType);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices
{
[ExportContentTypeLanguageService(ContentTypeNames.CSharpContentType, LanguageNames.CSharp), Shared]
internal class CSharpContentTypeLanguageService : IContentTypeLanguageService
{
private readonly IContentTypeRegistryService _contentTypeRegistry;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpContentTypeLanguageService(IContentTypeRegistryService contentTypeRegistry)
=> _contentTypeRegistry = contentTypeRegistry;
public IContentType GetDefaultContentType()
=> _contentTypeRegistry.GetContentType(ContentTypeNames.CSharpContentType);
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/WinMdTests.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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class WinMdTests
Inherits ExpressionCompilerTestBase
''' <summary>
''' Handle runtime assemblies rather than Windows.winmd
''' (compile-time assembly) since those are the assemblies
''' loaded in the debuggee.
''' </summary>
<WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub Win8RuntimeAssemblies()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim comp = CreateEmptyCompilation({source}, options:=TestOptions.DebugDll, references:=WinRtRefs)
Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")
Assert.True(runtimeAssemblies.Length >= 2)
' no reference to Windows.winmd
WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies),
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(p Is Nothing, f, Nothing)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}")
End Sub)
End Sub
<Fact>
Public Sub Win8OnWin8()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsData)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win8OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win10OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
"Windows")
End Sub
Private Sub CompileTimeAndRuntimeAssemblies(
compileReferences As ImmutableArray(Of MetadataReference),
runtimeReferences As ImmutableArray(Of MetadataReference),
storageAssemblyName As String)
Const source =
"Class C
Shared Sub M(a As LibraryA.A, b As LibraryB.B, t As Windows.Data.Text.TextSegment, f As Windows.Storage.StorageFolder)
End Sub
End Class"
Dim c0 = CreateEmptyCompilation({source}, compileReferences, TestOptions.DebugDll)
WithRuntimeInstance(c0, runtimeReferences,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(a, If(b, If(t, f)))", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}")
testData = New CompilationTestData()
Dim result = context.CompileExpression("f", errorMessage, testData)
Assert.Null(errorMessage)
Dim methodData = testData.GetMethodData("<>x.<>m0")
methodData.VerifyIL(
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.3
IL_0001: ret
}")
' Check return type is from runtime assembly.
Dim assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference()
Dim comp = VisualBasicCompilation.Create(
assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(),
references:=runtimeReferences.Concat(ImmutableArray.Create(Of MetadataReference)(assemblyReference)))
Using metadata = ModuleMetadata.CreateFromImage(result.Assembly)
Dim reader = metadata.MetadataReader
Dim typeDef = reader.GetTypeDef("<>x")
Dim methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0")
Dim [module] = DirectCast(comp.GetMember("<>x").ContainingModule, PEModuleSymbol)
Dim metadataDecoder = New MetadataDecoder([module])
Dim signatureHeader As SignatureHeader = Nothing
Dim metadataException As BadImageFormatException = Nothing
Dim parameters = metadataDecoder.GetSignatureForMethod(methodHandle, signatureHeader, metadataException)
Assert.Equal(parameters.Length, 5)
Dim actualReturnType = parameters(0).Type
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class) ' not error
Dim expectedReturnType = comp.GetMember("Windows.Storage.StorageFolder")
Assert.Equal(expectedReturnType, actualReturnType)
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name)
End Using
End Sub)
End Sub
''' <summary>
''' Assembly-qualified name containing "ContentType=WindowsRuntime",
''' and referencing runtime assembly.
''' </summary>
<WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub AssemblyQualifiedName()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim comp = CreateEmptyCompilation({source}, WinRtRefs, TestOptions.DebugDll)
Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")
WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies),
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim aliases = ImmutableArray.Create(
VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"))
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"If(DirectCast(s.Attributes, Object), d.UniversalTime)",
DkmEvaluationFlags.TreatAsExpression,
aliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Function Windows.Storage.StorageFolder.get_Attributes() As Windows.Storage.FileAttributes""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""Windows.Foundation.DateTime.UniversalTime As Long""
IL_0031: box ""Long""
IL_0036: ret
}")
End Sub)
End Sub
Private Shared Function ToVersion1_3(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_3(bytes)
End Function
Private Shared Function ToVersion1_4(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_4(bytes)
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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Public Class WinMdTests
Inherits ExpressionCompilerTestBase
''' <summary>
''' Handle runtime assemblies rather than Windows.winmd
''' (compile-time assembly) since those are the assemblies
''' loaded in the debuggee.
''' </summary>
<WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub Win8RuntimeAssemblies()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim comp = CreateEmptyCompilation({source}, options:=TestOptions.DebugDll, references:=WinRtRefs)
Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")
Assert.True(runtimeAssemblies.Length >= 2)
' no reference to Windows.winmd
WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies),
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(p Is Nothing, f, Nothing)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}")
End Sub)
End Sub
<Fact>
Public Sub Win8OnWin8()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsData)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win8OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
"Windows.Storage")
End Sub
<Fact>
Public Sub Win10OnWin10()
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsData)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.WindowsStorage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(TestResources.ExpressionCompiler.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.LibraryB).GetReference()),
"Windows")
End Sub
Private Sub CompileTimeAndRuntimeAssemblies(
compileReferences As ImmutableArray(Of MetadataReference),
runtimeReferences As ImmutableArray(Of MetadataReference),
storageAssemblyName As String)
Const source =
"Class C
Shared Sub M(a As LibraryA.A, b As LibraryB.B, t As Windows.Data.Text.TextSegment, f As Windows.Storage.StorageFolder)
End Sub
End Class"
Dim c0 = CreateEmptyCompilation({source}, compileReferences, TestOptions.DebugDll)
WithRuntimeInstance(c0, runtimeReferences,
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression("If(a, If(b, If(t, f)))", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}")
testData = New CompilationTestData()
Dim result = context.CompileExpression("f", errorMessage, testData)
Assert.Null(errorMessage)
Dim methodData = testData.GetMethodData("<>x.<>m0")
methodData.VerifyIL(
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.3
IL_0001: ret
}")
' Check return type is from runtime assembly.
Dim assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference()
Dim comp = VisualBasicCompilation.Create(
assemblyName:=ExpressionCompilerUtilities.GenerateUniqueName(),
references:=runtimeReferences.Concat(ImmutableArray.Create(Of MetadataReference)(assemblyReference)))
Using metadata = ModuleMetadata.CreateFromImage(result.Assembly)
Dim reader = metadata.MetadataReader
Dim typeDef = reader.GetTypeDef("<>x")
Dim methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0")
Dim [module] = DirectCast(comp.GetMember("<>x").ContainingModule, PEModuleSymbol)
Dim metadataDecoder = New MetadataDecoder([module])
Dim signatureHeader As SignatureHeader = Nothing
Dim metadataException As BadImageFormatException = Nothing
Dim parameters = metadataDecoder.GetSignatureForMethod(methodHandle, signatureHeader, metadataException)
Assert.Equal(parameters.Length, 5)
Dim actualReturnType = parameters(0).Type
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class) ' not error
Dim expectedReturnType = comp.GetMember("Windows.Storage.StorageFolder")
Assert.Equal(expectedReturnType, actualReturnType)
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name)
End Using
End Sub)
End Sub
''' <summary>
''' Assembly-qualified name containing "ContentType=WindowsRuntime",
''' and referencing runtime assembly.
''' </summary>
<WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")>
<ConditionalFact(GetType(OSVersionWin8))>
Public Sub AssemblyQualifiedName()
Const source =
"Class C
Shared Sub M(f As Windows.Storage.StorageFolder, p As Windows.Foundation.Collections.PropertySet)
End Sub
End Class"
Dim comp = CreateEmptyCompilation({source}, WinRtRefs, TestOptions.DebugDll)
Dim runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")
WithRuntimeInstance(comp, {MscorlibRef}.Concat(runtimeAssemblies),
Sub(runtime)
Dim context = CreateMethodContext(runtime, "C.M")
Dim aliases = ImmutableArray.Create(
VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"))
Dim errorMessage As String = Nothing
Dim testData = New CompilationTestData()
context.CompileExpression(
"If(DirectCast(s.Attributes, Object), d.UniversalTime)",
DkmEvaluationFlags.TreatAsExpression,
aliases,
errorMessage,
testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Function Windows.Storage.StorageFolder.get_Attributes() As Windows.Storage.FileAttributes""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""Windows.Foundation.DateTime.UniversalTime As Long""
IL_0031: box ""Long""
IL_0036: ret
}")
End Sub)
End Sub
Private Shared Function ToVersion1_3(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_3(bytes)
End Function
Private Shared Function ToVersion1_4(bytes As Byte()) As Byte()
Return ExpressionCompilerTestHelpers.ToVersion1_4(bytes)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatcher.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface IRemoteServiceCallbackDispatcher
{
RemoteServiceCallbackDispatcher.Handle CreateHandle(object? instance);
}
internal class RemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
internal readonly struct Handle : IDisposable
{
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances;
public readonly RemoteServiceCallbackId Id;
public Handle(ConcurrentDictionary<RemoteServiceCallbackId, object> callbackInstances, RemoteServiceCallbackId callbackId)
{
_callbackInstances = callbackInstances;
Id = callbackId;
}
public void Dispose()
{
Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false);
}
}
private int _callbackId = 1;
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances = new(concurrencyLevel: 2, capacity: 10);
public Handle CreateHandle(object? instance)
{
if (instance is null)
{
return default;
}
var callbackId = new RemoteServiceCallbackId(Interlocked.Increment(ref _callbackId));
var handle = new Handle(_callbackInstances, callbackId);
_callbackInstances.Add(callbackId, instance);
return handle;
}
public object GetCallback(RemoteServiceCallbackId callbackId)
{
Contract.ThrowIfFalse(_callbackInstances.TryGetValue(callbackId, out var instance));
return 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.
using System;
using System.Collections.Concurrent;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface IRemoteServiceCallbackDispatcher
{
RemoteServiceCallbackDispatcher.Handle CreateHandle(object? instance);
}
internal class RemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
internal readonly struct Handle : IDisposable
{
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances;
public readonly RemoteServiceCallbackId Id;
public Handle(ConcurrentDictionary<RemoteServiceCallbackId, object> callbackInstances, RemoteServiceCallbackId callbackId)
{
_callbackInstances = callbackInstances;
Id = callbackId;
}
public void Dispose()
{
Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false);
}
}
private int _callbackId = 1;
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances = new(concurrencyLevel: 2, capacity: 10);
public Handle CreateHandle(object? instance)
{
if (instance is null)
{
return default;
}
var callbackId = new RemoteServiceCallbackId(Interlocked.Increment(ref _callbackId));
var handle = new Handle(_callbackInstances, callbackId);
_callbackInstances.Add(callbackId, instance);
return handle;
}
public object GetCallback(RemoteServiceCallbackId callbackId)
{
Contract.ThrowIfFalse(_callbackInstances.TryGetValue(callbackId, out var instance));
return instance;
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ExpressionCompiler.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
public abstract class ExpressionCompiler :
IDkmClrExpressionCompiler,
IDkmClrExpressionCompilerCallback,
IDkmModuleModifiedNotification,
IDkmModuleInstanceUnloadNotification,
IDkmLanguageFrameDecoder,
IDkmLanguageInstructionDecoder
{
// Need to support IDkmLanguageFrameDecoder and IDkmLanguageInstructionDecoder
// See https://github.com/dotnet/roslyn/issues/22620
private readonly IDkmLanguageFrameDecoder _languageFrameDecoder;
private readonly IDkmLanguageInstructionDecoder _languageInstructionDecoder;
private readonly bool _useReferencedAssembliesOnly;
public ExpressionCompiler(IDkmLanguageFrameDecoder languageFrameDecoder, IDkmLanguageInstructionDecoder languageInstructionDecoder)
{
_languageFrameDecoder = languageFrameDecoder;
_languageInstructionDecoder = languageInstructionDecoder;
_useReferencedAssembliesOnly = GetUseReferencedAssembliesOnlySetting();
}
DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery(
DkmInspectionContext inspectionContext,
DkmClrInstructionAddress instructionAddress,
bool argumentsOnly)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = argumentsOnly
? ImmutableArray<Alias>.Empty
: GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
string? error;
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var builder = ArrayBuilder<LocalAndMethod>.GetInstance();
var assembly = context.CompileGetLocals(
builder,
argumentsOnly,
aliases,
diagnostics,
out var typeName,
testData: null);
Debug.Assert((builder.Count == 0) == (assembly.Count == 0));
var locals = new ReadOnlyCollection<DkmClrLocalVariableInfo>(builder.SelectAsArray(ToLocalVariableInfo));
builder.Free();
return new GetLocalsResult(typeName, locals, assembly);
},
out error);
return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, CompilerId, r.Assembly, r.TypeName, r.Locals);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static ImmutableArray<Alias> GetAliases(DkmClrRuntimeInstance runtimeInstance, DkmInspectionContext inspectionContext)
{
var dkmAliases = runtimeInstance.GetAliases(inspectionContext);
if (dkmAliases == null)
{
return ImmutableArray<Alias>.Empty;
}
var builder = ArrayBuilder<Alias>.GetInstance(dkmAliases.Count);
foreach (var dkmAlias in dkmAliases)
{
builder.Add(new Alias(
dkmAlias.Kind,
dkmAlias.Name,
dkmAlias.FullName,
dkmAlias.Type,
dkmAlias.CustomTypeInfoPayloadTypeId,
dkmAlias.CustomTypeInfoPayload));
}
return builder.ToImmutableAndFree();
}
void IDkmClrExpressionCompiler.CompileExpression(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmInspectionContext inspectionContext,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileExpression(
expression.Text,
expression.CompilationFlags,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompiler.CompileAssignment(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmEvaluationResult lValue,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, lValue.InspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileAssignment(
lValue.FullName,
expression.Text,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
Debug.Assert(
r.CompileResult == null && r.ResultProperties.Flags == default ||
(r.ResultProperties.Flags & DkmClrCompilationResultFlags.PotentialSideEffect) == DkmClrCompilationResultFlags.PotentialSideEffect);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute(
DkmLanguageExpression expression,
DkmClrModuleInstance moduleInstance,
int token,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var runtimeInstance = moduleInstance.RuntimeInstance;
var appDomain = moduleInstance.AppDomain;
var compileResult = CompileWithRetry(
appDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.Mvid, token, useReferencedModulesOnly),
(context, diagnostics) =>
{
return context.CompileExpression(
expression.Text,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
diagnostics,
out var unusedResultProperties,
testData: null);
},
out error);
result = compileResult.ToQueryResult(CompilerId, resultProperties: default, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool GetUseReferencedAssembliesOnlySetting()
{
return RegistryHelpers.GetBoolRegistryValue("UseReferencedAssembliesOnly");
}
internal MakeAssemblyReferencesKind GetMakeAssemblyReferencesKind(bool useReferencedModulesOnly)
{
if (useReferencedModulesOnly)
{
return MakeAssemblyReferencesKind.DirectReferencesOnly;
}
return _useReferencedAssembliesOnly ? MakeAssemblyReferencesKind.AllReferences : MakeAssemblyReferencesKind.AllAssemblies;
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static bool ShouldTryAgainWithMoreMetadataBlocks(DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references)
{
var newReferences = DkmUtilities.GetMetadataBlocks(getMetaDataBytesPtrFunction, missingAssemblyIdentities);
if (newReferences.Length > 0)
{
references = references.AddRange(newReferences);
return true;
}
return false;
}
void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance)
{
RemoveDataItemIfNecessary(moduleInstance);
}
void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
RemoveDataItemIfNecessary(moduleInstance);
}
#region IDkmLanguageFrameDecoder, IDkmLanguageInstructionDecoder
void IDkmLanguageFrameDecoder.GetFrameName(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameName(inspectionContext, workList, frame, argumentFlags, completionRoutine);
}
void IDkmLanguageFrameDecoder.GetFrameReturnType(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameReturnType(inspectionContext, workList, frame, completionRoutine);
}
string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags)
{
return _languageInstructionDecoder.GetMethodName(languageInstructionAddress, argumentFlags);
}
#endregion
private void RemoveDataItemIfNecessary(DkmModuleInstance moduleInstance)
{
// If the module is not a managed module, the module change has no effect.
var module = moduleInstance as DkmClrModuleInstance;
if (module == null)
{
return;
}
// Drop any context cached on the AppDomain.
var appDomain = module.AppDomain;
RemoveDataItem(appDomain);
}
internal abstract DiagnosticFormatter DiagnosticFormatter { get; }
internal abstract DkmCompilerId CompilerId { get; }
internal abstract EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly);
internal abstract EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> lazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly);
internal abstract void RemoveDataItem(DkmClrAppDomain appDomain);
internal abstract ImmutableArray<MetadataBlock> GetMetadataBlocks(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance);
private EvaluationContextBase CreateMethodContext(
DkmClrInstructionAddress instructionAddress,
ImmutableArray<MetadataBlock> metadataBlocks,
bool useReferencedModulesOnly)
{
var moduleInstance = instructionAddress.ModuleInstance;
var methodToken = instructionAddress.MethodId.Token;
int localSignatureToken;
try
{
localSignatureToken = moduleInstance.GetLocalSignatureToken(methodToken);
}
catch (InvalidOperationException)
{
// No local signature. May occur when debugging .dmp.
localSignatureToken = 0;
}
catch (FileNotFoundException)
{
// No local signature. May occur when debugging heapless dumps.
localSignatureToken = 0;
}
return CreateMethodContext(
moduleInstance.AppDomain,
metadataBlocks,
new Lazy<ImmutableArray<AssemblyReaders>>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None),
symReader: moduleInstance.GetSymReader(),
moduleVersionId: moduleInstance.Mvid,
methodToken: methodToken,
methodVersion: (int)instructionAddress.MethodId.Version,
ilOffset: instructionAddress.ILOffset,
localSignatureToken: localSignatureToken,
useReferencedModulesOnly: useReferencedModulesOnly);
}
internal delegate EvaluationContextBase CreateContextDelegate(ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly);
internal delegate TResult CompileDelegate<TResult>(EvaluationContextBase context, DiagnosticBag diagnostics);
private TResult CompileWithRetry<TResult>(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
out string? errorMessage)
{
var metadataBlocks = GetMetadataBlocks(appDomain, runtimeInstance);
return CompileWithRetry(
metadataBlocks,
DiagnosticFormatter,
createContext,
compile,
(AssemblyIdentity assemblyIdentity, out uint size) => appDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size),
out errorMessage);
}
internal static TResult CompileWithRetry<TResult>(
ImmutableArray<MetadataBlock> metadataBlocks,
DiagnosticFormatter formatter,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string? errorMessage)
{
TResult compileResult;
PooledHashSet<AssemblyIdentity>? assembliesLoadedInRetryLoop = null;
bool tryAgain;
var linqLibrary = EvaluationContextBase.SystemLinqIdentity;
do
{
errorMessage = null;
var context = createContext(metadataBlocks, useReferencedModulesOnly: false);
var diagnostics = DiagnosticBag.GetInstance();
compileResult = compile(context, diagnostics);
tryAgain = false;
if (diagnostics.HasAnyErrors())
{
errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities(
diagnostics,
formatter,
preferredUICulture: null,
linqLibrary: linqLibrary,
useReferencedModulesOnly: out var useReferencedModulesOnly,
missingAssemblyIdentities: out var missingAssemblyIdentities);
// If there were LINQ-related errors, we'll initially add System.Linq (set above).
// If that doesn't work, we'll fall back to System.Core for subsequent retries.
linqLibrary = EvaluationContextBase.SystemCoreIdentity;
// Can we remove the `useReferencedModulesOnly` attempt if we're only using
// modules reachable from the current module? In short, can we avoid retrying?
if (useReferencedModulesOnly)
{
Debug.Assert(missingAssemblyIdentities.IsEmpty);
var otherContext = createContext(metadataBlocks, useReferencedModulesOnly: true);
var otherDiagnostics = DiagnosticBag.GetInstance();
var otherResult = compile(otherContext, otherDiagnostics);
if (!otherDiagnostics.HasAnyErrors())
{
errorMessage = null;
compileResult = otherResult;
}
otherDiagnostics.Free();
}
else
{
if (!missingAssemblyIdentities.IsEmpty)
{
if (assembliesLoadedInRetryLoop == null)
{
assembliesLoadedInRetryLoop = PooledHashSet<AssemblyIdentity>.GetInstance();
}
// If any identities failed to add (they were already in the list), then don't retry.
if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities))
{
tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks);
}
}
}
}
diagnostics.Free();
} while (tryAgain);
assembliesLoadedInRetryLoop?.Free();
return compileResult;
}
private static DkmClrLocalVariableInfo ToLocalVariableInfo(LocalAndMethod local)
{
ReadOnlyCollection<byte>? customTypeInfo;
Guid customTypeInfoId = local.GetCustomTypeInfo(out customTypeInfo);
return DkmClrLocalVariableInfo.Create(
local.LocalDisplayName,
local.LocalName,
local.MethodName,
local.Flags,
DkmEvaluationResultCategory.Data,
customTypeInfo.ToCustomTypeInfo(customTypeInfoId));
}
private readonly struct GetLocalsResult
{
internal readonly string TypeName;
internal readonly ReadOnlyCollection<DkmClrLocalVariableInfo> Locals;
internal readonly ReadOnlyCollection<byte> Assembly;
internal GetLocalsResult(string typeName, ReadOnlyCollection<DkmClrLocalVariableInfo> locals, ReadOnlyCollection<byte> assembly)
{
TypeName = typeName;
Locals = locals;
Assembly = assembly;
}
}
private readonly struct CompileExpressionResult
{
internal readonly CompileResult? CompileResult;
internal readonly ResultProperties ResultProperties;
internal CompileExpressionResult(CompileResult? compileResult, ResultProperties resultProperties)
{
CompileResult = compileResult;
ResultProperties = resultProperties;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
public abstract class ExpressionCompiler :
IDkmClrExpressionCompiler,
IDkmClrExpressionCompilerCallback,
IDkmModuleModifiedNotification,
IDkmModuleInstanceUnloadNotification,
IDkmLanguageFrameDecoder,
IDkmLanguageInstructionDecoder
{
// Need to support IDkmLanguageFrameDecoder and IDkmLanguageInstructionDecoder
// See https://github.com/dotnet/roslyn/issues/22620
private readonly IDkmLanguageFrameDecoder _languageFrameDecoder;
private readonly IDkmLanguageInstructionDecoder _languageInstructionDecoder;
private readonly bool _useReferencedAssembliesOnly;
public ExpressionCompiler(IDkmLanguageFrameDecoder languageFrameDecoder, IDkmLanguageInstructionDecoder languageInstructionDecoder)
{
_languageFrameDecoder = languageFrameDecoder;
_languageInstructionDecoder = languageInstructionDecoder;
_useReferencedAssembliesOnly = GetUseReferencedAssembliesOnlySetting();
}
DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery(
DkmInspectionContext inspectionContext,
DkmClrInstructionAddress instructionAddress,
bool argumentsOnly)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = argumentsOnly
? ImmutableArray<Alias>.Empty
: GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
string? error;
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var builder = ArrayBuilder<LocalAndMethod>.GetInstance();
var assembly = context.CompileGetLocals(
builder,
argumentsOnly,
aliases,
diagnostics,
out var typeName,
testData: null);
Debug.Assert((builder.Count == 0) == (assembly.Count == 0));
var locals = new ReadOnlyCollection<DkmClrLocalVariableInfo>(builder.SelectAsArray(ToLocalVariableInfo));
builder.Free();
return new GetLocalsResult(typeName, locals, assembly);
},
out error);
return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, CompilerId, r.Assembly, r.TypeName, r.Locals);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static ImmutableArray<Alias> GetAliases(DkmClrRuntimeInstance runtimeInstance, DkmInspectionContext inspectionContext)
{
var dkmAliases = runtimeInstance.GetAliases(inspectionContext);
if (dkmAliases == null)
{
return ImmutableArray<Alias>.Empty;
}
var builder = ArrayBuilder<Alias>.GetInstance(dkmAliases.Count);
foreach (var dkmAlias in dkmAliases)
{
builder.Add(new Alias(
dkmAlias.Kind,
dkmAlias.Name,
dkmAlias.FullName,
dkmAlias.Type,
dkmAlias.CustomTypeInfoPayloadTypeId,
dkmAlias.CustomTypeInfoPayload));
}
return builder.ToImmutableAndFree();
}
void IDkmClrExpressionCompiler.CompileExpression(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmInspectionContext inspectionContext,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileExpression(
expression.Text,
expression.CompilationFlags,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompiler.CompileAssignment(
DkmLanguageExpression expression,
DkmClrInstructionAddress instructionAddress,
DkmEvaluationResult lValue,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var moduleInstance = instructionAddress.ModuleInstance;
var runtimeInstance = instructionAddress.RuntimeInstance;
var aliases = GetAliases(runtimeInstance, lValue.InspectionContext); // NB: Not affected by retrying.
var r = CompileWithRetry(
moduleInstance.AppDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly),
(context, diagnostics) =>
{
var compileResult = context.CompileAssignment(
lValue.FullName,
expression.Text,
aliases,
diagnostics,
out var resultProperties,
testData: null);
return new CompileExpressionResult(compileResult, resultProperties);
},
out error);
Debug.Assert(
r.CompileResult == null && r.ResultProperties.Flags == default ||
(r.ResultProperties.Flags & DkmClrCompilationResultFlags.PotentialSideEffect) == DkmClrCompilationResultFlags.PotentialSideEffect);
result = r.CompileResult.ToQueryResult(CompilerId, r.ResultProperties, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute(
DkmLanguageExpression expression,
DkmClrModuleInstance moduleInstance,
int token,
out string? error,
out DkmCompiledClrInspectionQuery? result)
{
try
{
var runtimeInstance = moduleInstance.RuntimeInstance;
var appDomain = moduleInstance.AppDomain;
var compileResult = CompileWithRetry(
appDomain,
runtimeInstance,
(blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.Mvid, token, useReferencedModulesOnly),
(context, diagnostics) =>
{
return context.CompileExpression(
expression.Text,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
diagnostics,
out var unusedResultProperties,
testData: null);
},
out error);
result = compileResult.ToQueryResult(CompilerId, resultProperties: default, runtimeInstance);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool GetUseReferencedAssembliesOnlySetting()
{
return RegistryHelpers.GetBoolRegistryValue("UseReferencedAssembliesOnly");
}
internal MakeAssemblyReferencesKind GetMakeAssemblyReferencesKind(bool useReferencedModulesOnly)
{
if (useReferencedModulesOnly)
{
return MakeAssemblyReferencesKind.DirectReferencesOnly;
}
return _useReferencedAssembliesOnly ? MakeAssemblyReferencesKind.AllReferences : MakeAssemblyReferencesKind.AllAssemblies;
}
/// <remarks>
/// Internal for testing.
/// </remarks>
internal static bool ShouldTryAgainWithMoreMetadataBlocks(DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references)
{
var newReferences = DkmUtilities.GetMetadataBlocks(getMetaDataBytesPtrFunction, missingAssemblyIdentities);
if (newReferences.Length > 0)
{
references = references.AddRange(newReferences);
return true;
}
return false;
}
void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance)
{
RemoveDataItemIfNecessary(moduleInstance);
}
void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor)
{
RemoveDataItemIfNecessary(moduleInstance);
}
#region IDkmLanguageFrameDecoder, IDkmLanguageInstructionDecoder
void IDkmLanguageFrameDecoder.GetFrameName(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameName(inspectionContext, workList, frame, argumentFlags, completionRoutine);
}
void IDkmLanguageFrameDecoder.GetFrameReturnType(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine)
{
_languageFrameDecoder.GetFrameReturnType(inspectionContext, workList, frame, completionRoutine);
}
string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags)
{
return _languageInstructionDecoder.GetMethodName(languageInstructionAddress, argumentFlags);
}
#endregion
private void RemoveDataItemIfNecessary(DkmModuleInstance moduleInstance)
{
// If the module is not a managed module, the module change has no effect.
var module = moduleInstance as DkmClrModuleInstance;
if (module == null)
{
return;
}
// Drop any context cached on the AppDomain.
var appDomain = module.AppDomain;
RemoveDataItem(appDomain);
}
internal abstract DiagnosticFormatter DiagnosticFormatter { get; }
internal abstract DkmCompilerId CompilerId { get; }
internal abstract EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly);
internal abstract EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> lazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly);
internal abstract void RemoveDataItem(DkmClrAppDomain appDomain);
internal abstract ImmutableArray<MetadataBlock> GetMetadataBlocks(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance);
private EvaluationContextBase CreateMethodContext(
DkmClrInstructionAddress instructionAddress,
ImmutableArray<MetadataBlock> metadataBlocks,
bool useReferencedModulesOnly)
{
var moduleInstance = instructionAddress.ModuleInstance;
var methodToken = instructionAddress.MethodId.Token;
int localSignatureToken;
try
{
localSignatureToken = moduleInstance.GetLocalSignatureToken(methodToken);
}
catch (InvalidOperationException)
{
// No local signature. May occur when debugging .dmp.
localSignatureToken = 0;
}
catch (FileNotFoundException)
{
// No local signature. May occur when debugging heapless dumps.
localSignatureToken = 0;
}
return CreateMethodContext(
moduleInstance.AppDomain,
metadataBlocks,
new Lazy<ImmutableArray<AssemblyReaders>>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None),
symReader: moduleInstance.GetSymReader(),
moduleVersionId: moduleInstance.Mvid,
methodToken: methodToken,
methodVersion: (int)instructionAddress.MethodId.Version,
ilOffset: instructionAddress.ILOffset,
localSignatureToken: localSignatureToken,
useReferencedModulesOnly: useReferencedModulesOnly);
}
internal delegate EvaluationContextBase CreateContextDelegate(ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly);
internal delegate TResult CompileDelegate<TResult>(EvaluationContextBase context, DiagnosticBag diagnostics);
private TResult CompileWithRetry<TResult>(
DkmClrAppDomain appDomain,
DkmClrRuntimeInstance runtimeInstance,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
out string? errorMessage)
{
var metadataBlocks = GetMetadataBlocks(appDomain, runtimeInstance);
return CompileWithRetry(
metadataBlocks,
DiagnosticFormatter,
createContext,
compile,
(AssemblyIdentity assemblyIdentity, out uint size) => appDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size),
out errorMessage);
}
internal static TResult CompileWithRetry<TResult>(
ImmutableArray<MetadataBlock> metadataBlocks,
DiagnosticFormatter formatter,
CreateContextDelegate createContext,
CompileDelegate<TResult> compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string? errorMessage)
{
TResult compileResult;
PooledHashSet<AssemblyIdentity>? assembliesLoadedInRetryLoop = null;
bool tryAgain;
var linqLibrary = EvaluationContextBase.SystemLinqIdentity;
do
{
errorMessage = null;
var context = createContext(metadataBlocks, useReferencedModulesOnly: false);
var diagnostics = DiagnosticBag.GetInstance();
compileResult = compile(context, diagnostics);
tryAgain = false;
if (diagnostics.HasAnyErrors())
{
errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities(
diagnostics,
formatter,
preferredUICulture: null,
linqLibrary: linqLibrary,
useReferencedModulesOnly: out var useReferencedModulesOnly,
missingAssemblyIdentities: out var missingAssemblyIdentities);
// If there were LINQ-related errors, we'll initially add System.Linq (set above).
// If that doesn't work, we'll fall back to System.Core for subsequent retries.
linqLibrary = EvaluationContextBase.SystemCoreIdentity;
// Can we remove the `useReferencedModulesOnly` attempt if we're only using
// modules reachable from the current module? In short, can we avoid retrying?
if (useReferencedModulesOnly)
{
Debug.Assert(missingAssemblyIdentities.IsEmpty);
var otherContext = createContext(metadataBlocks, useReferencedModulesOnly: true);
var otherDiagnostics = DiagnosticBag.GetInstance();
var otherResult = compile(otherContext, otherDiagnostics);
if (!otherDiagnostics.HasAnyErrors())
{
errorMessage = null;
compileResult = otherResult;
}
otherDiagnostics.Free();
}
else
{
if (!missingAssemblyIdentities.IsEmpty)
{
if (assembliesLoadedInRetryLoop == null)
{
assembliesLoadedInRetryLoop = PooledHashSet<AssemblyIdentity>.GetInstance();
}
// If any identities failed to add (they were already in the list), then don't retry.
if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities))
{
tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks);
}
}
}
}
diagnostics.Free();
} while (tryAgain);
assembliesLoadedInRetryLoop?.Free();
return compileResult;
}
private static DkmClrLocalVariableInfo ToLocalVariableInfo(LocalAndMethod local)
{
ReadOnlyCollection<byte>? customTypeInfo;
Guid customTypeInfoId = local.GetCustomTypeInfo(out customTypeInfo);
return DkmClrLocalVariableInfo.Create(
local.LocalDisplayName,
local.LocalName,
local.MethodName,
local.Flags,
DkmEvaluationResultCategory.Data,
customTypeInfo.ToCustomTypeInfo(customTypeInfoId));
}
private readonly struct GetLocalsResult
{
internal readonly string TypeName;
internal readonly ReadOnlyCollection<DkmClrLocalVariableInfo> Locals;
internal readonly ReadOnlyCollection<byte> Assembly;
internal GetLocalsResult(string typeName, ReadOnlyCollection<DkmClrLocalVariableInfo> locals, ReadOnlyCollection<byte> assembly)
{
TypeName = typeName;
Locals = locals;
Assembly = assembly;
}
}
private readonly struct CompileExpressionResult
{
internal readonly CompileResult? CompileResult;
internal readonly ResultProperties ResultProperties;
internal CompileExpressionResult(CompileResult? compileResult, ResultProperties resultProperties)
{
CompileResult = compileResult;
ResultProperties = resultProperties;
}
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
#If CODE_STYLE Then
Imports Microsoft.CodeAnalysis.Internal.Editing
#Else
Imports Microsoft.CodeAnalysis.Editing
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Friend Class VisualBasicSyntaxFacts
Inherits AbstractSyntaxFacts
Implements ISyntaxFacts
Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts
Protected Sub New()
End Sub
Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive
Get
Return False
End Get
End Property
Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer
Get
Return CaseInsensitiveComparison.Comparer
End Get
End Property
Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker
Get
Return SyntaxFactory.ElasticMarker
End Get
End Property
Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds
Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService
Get
Return VisualBasicDocumentationCommentService.Instance
End Get
End Property
Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer
Return False
End Function
Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression
Return False
End Function
Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration
Return False
End Function
Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord
Return False
End Function
Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct
Return False
End Function
Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken
Return SyntaxFactory.ParseToken(text, startStatement:=True)
End Function
Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia
Return SyntaxFactory.ParseLeadingTrivia(text)
End Function
Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier
Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier)
Dim needsEscaping = keywordKind <> SyntaxKind.None
Return If(needsEscaping, "[" & identifier & "]", identifier)
End Function
Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return False
End Function
Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator
Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse
(IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax))
End Function
Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword
Return token.IsContextualKeyword()
End Function
Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword
Return token.IsReservedKeyword()
End Function
Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword
Return token.IsPreprocessorKeyword()
End Function
Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext
Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)
End Function
Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace
If token.Kind = SyntaxKind.CloseBraceToken Then
Dim tuples = token.Parent.GetBraces()
openBrace = tuples.openBrace
Return openBrace.Kind = SyntaxKind.OpenBraceToken
End If
Return False
End Function
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken)
End Function
Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective
Return TypeOf node Is DirectiveTriviaSyntax
End Function
Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo
Select Case node.Kind
Case SyntaxKind.ExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False)
Return True
Case SyntaxKind.EndExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(Nothing, True)
Return True
End Select
Return False
End Function
Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType
Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso
DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node
End Function
Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression
' VB doesn't support declaration expressions
Return False
End Function
Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName
Return node.IsParentKind(SyntaxKind.Attribute) AndAlso
DirectCast(node.Parent, AttributeSyntax).Name Is node
End Function
Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName
Dim vbNode = TryCast(node, SimpleNameSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName()
End Function
Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression
Dim vbNode = TryCast(node, ExpressionSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName()
End Function
Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression
Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax)
Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node
End Function
Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression
Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax))
End Function
Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression
Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression()
End Function
Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression
Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax)
expression = conditionalAccess.Expression
operatorToken = conditionalAccess.QuestionMarkToken
whenNotNull = conditionalAccess.WhenNotNull
End Sub
Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction
Return TypeOf node Is LambdaExpressionSyntax
End Function
Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument
Dim arg = TryCast(node, SimpleArgumentSyntax)
Return arg?.NameColonEquals IsNot Nothing
End Function
Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument
Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node)
End Function
Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter
Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier
End Function
Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter
Return TryCast(node, ParameterSyntax)?.Default
End Function
Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList
Return node.GetParameterList()
End Function
Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList
Return node.IsKind(SyntaxKind.ParameterList)
End Function
Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember
Return HasIncompleteParentMember(node)
End Function
Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName
Dim vbGenericName = TryCast(genericName, GenericNameSyntax)
Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing)
End Function
Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName
Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso
DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node
End Function
Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment
Return False
End Function
Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement
Return False
End Function
Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement
Return TypeOf node Is StatementSyntax
End Function
Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement
Return TypeOf node Is ExecutableStatementSyntax
End Function
Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody
Return TypeOf node Is MethodBlockBaseSyntax
End Function
Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement
Return TryCast(node, ReturnStatementSyntax)?.Expression
End Function
Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsThisConstructorInitializer()
End If
Return False
End Function
Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsBaseConstructorInitializer()
End If
Return False
End Function
Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword
Select Case token.Kind()
Case _
SyntaxKind.JoinKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.SelectKeyword
Return TypeOf token.Parent Is QueryClauseSyntax
Case SyntaxKind.GroupKeyword
Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation))
Case SyntaxKind.EqualsKeyword
Return TypeOf token.Parent Is JoinConditionSyntax
Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword
Return TypeOf token.Parent Is OrderingSyntax
Case SyntaxKind.InKeyword
Return TypeOf token.Parent Is CollectionRangeVariableSyntax
Case Else
Return False
End Select
End Function
Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression
' VB does not support throw expressions currently.
Return False
End Function
Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None
End Function
Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType = type
End Function
Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType
type = GetPredefinedType(token)
Return type <> PredefinedType.None
End Function
Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType
Select Case token.Kind
Case SyntaxKind.BooleanKeyword
Return PredefinedType.Boolean
Case SyntaxKind.ByteKeyword
Return PredefinedType.Byte
Case SyntaxKind.SByteKeyword
Return PredefinedType.SByte
Case SyntaxKind.IntegerKeyword
Return PredefinedType.Int32
Case SyntaxKind.UIntegerKeyword
Return PredefinedType.UInt32
Case SyntaxKind.ShortKeyword
Return PredefinedType.Int16
Case SyntaxKind.UShortKeyword
Return PredefinedType.UInt16
Case SyntaxKind.LongKeyword
Return PredefinedType.Int64
Case SyntaxKind.ULongKeyword
Return PredefinedType.UInt64
Case SyntaxKind.SingleKeyword
Return PredefinedType.Single
Case SyntaxKind.DoubleKeyword
Return PredefinedType.Double
Case SyntaxKind.DecimalKeyword
Return PredefinedType.Decimal
Case SyntaxKind.StringKeyword
Return PredefinedType.String
Case SyntaxKind.CharKeyword
Return PredefinedType.Char
Case SyntaxKind.ObjectKeyword
Return PredefinedType.Object
Case SyntaxKind.DateKeyword
Return PredefinedType.DateTime
Case Else
Return PredefinedType.None
End Select
End Function
Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None
End Function
Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op
End Function
Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator
op = GetPredefinedOperator(token)
Return op <> PredefinedOperator.None
End Function
Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator
Select Case token.Kind
Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken
Return PredefinedOperator.Addition
Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken
Return PredefinedOperator.Subtraction
Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword
Return PredefinedOperator.BitwiseAnd
Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword
Return PredefinedOperator.BitwiseOr
Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken
Return PredefinedOperator.Concatenate
Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken
Return PredefinedOperator.Division
Case SyntaxKind.EqualsToken
Return PredefinedOperator.Equality
Case SyntaxKind.XorKeyword
Return PredefinedOperator.ExclusiveOr
Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken
Return PredefinedOperator.Exponent
Case SyntaxKind.GreaterThanToken
Return PredefinedOperator.GreaterThan
Case SyntaxKind.GreaterThanEqualsToken
Return PredefinedOperator.GreaterThanOrEqual
Case SyntaxKind.LessThanGreaterThanToken
Return PredefinedOperator.Inequality
Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken
Return PredefinedOperator.IntegerDivision
Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken
Return PredefinedOperator.LeftShift
Case SyntaxKind.LessThanToken
Return PredefinedOperator.LessThan
Case SyntaxKind.LessThanEqualsToken
Return PredefinedOperator.LessThanOrEqual
Case SyntaxKind.LikeKeyword
Return PredefinedOperator.Like
Case SyntaxKind.NotKeyword
Return PredefinedOperator.Complement
Case SyntaxKind.ModKeyword
Return PredefinedOperator.Modulus
Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken
Return PredefinedOperator.Multiplication
Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken
Return PredefinedOperator.RightShift
Case Else
Return PredefinedOperator.None
End Select
End Function
Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText
Return SyntaxFacts.GetText(CType(kind, SyntaxKind))
End Function
Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter
Return SyntaxFacts.IsIdentifierPartCharacter(c)
End Function
Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter
Return SyntaxFacts.IsIdentifierStartCharacter(c)
End Function
Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter
Return c = "["c OrElse c = "]"c
End Function
Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier
Dim token = SyntaxFactory.ParseToken(identifier)
' TODO: There is no way to get the diagnostics to see if any are actually errors?
Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length
End Function
Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]"
End Function
Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter
Return c = "%"c OrElse
c = "&"c OrElse
c = "@"c OrElse
c = "!"c OrElse
c = "#"c OrElse
c = "$"c
End Function
Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence
Return False ' VB does not support identifiers with escaped unicode characters
End Function
Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral
Select Case token.Kind()
Case _
SyntaxKind.IntegerLiteralToken,
SyntaxKind.CharacterLiteralToken,
SyntaxKind.DecimalLiteralToken,
SyntaxKind.FloatingLiteralToken,
SyntaxKind.DateLiteralToken,
SyntaxKind.StringLiteralToken,
SyntaxKind.DollarSignDoubleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.InterpolatedStringTextToken,
SyntaxKind.TrueKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.NothingKeyword
Return True
End Select
Return False
End Function
Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral
Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken)
End Function
Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression
Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression))
End Function
Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken
Return Me.IsWord(token) OrElse
Me.IsLiteral(token) OrElse
Me.IsOperator(token)
End Function
Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression
Return False
End Function
Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName
Dim simpleName = TryCast(node, SimpleNameSyntax)
If simpleName IsNot Nothing Then
name = simpleName.Identifier.ValueText
arity = simpleName.Arity
End If
End Sub
Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric
Return name.IsKind(SyntaxKind.GenericName)
End Function
Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression
Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)
End Function
Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding
' Member bindings are a C# concept.
Return Nothing
End Function
Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression
' Member bindings are a C# concept.
Return Nothing
End Function
Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression
Dim invocation = TryCast(node, InvocationExpressionSyntax)
If invocation IsNot Nothing Then
expression = invocation?.Expression
argumentList = invocation?.ArgumentList
Return
End If
If node.Kind() = SyntaxKind.DictionaryAccessExpression Then
GetPartsOfMemberAccessExpression(node, expression, argumentList)
Return
End If
Return
End Sub
Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation
Return TryCast(node, InterpolationSyntax)?.Expression
End Function
Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList
Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing
End Function
Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext
Return node.IsInStaticContext()
End Function
Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument
Return TryCast(node, ArgumentSyntax).GetArgumentExpression()
End Function
Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument
' TODO(cyrusn): Consider the method this argument is passed to, to determine this.
Return RefKind.None
End Function
Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument
Return TypeOf node Is ArgumentSyntax
End Function
Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument
Dim argument = TryCast(node, ArgumentSyntax)
Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted
End Function
Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext
Return node.IsInConstantContext()
End Function
Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor
Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock)
End Function
Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext
Return False
End Function
Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute
Return DirectCast(node, AttributeSyntax).Name
End Function
Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression
Return DirectCast(node, ParenthesizedExpressionSyntax).Expression
End Function
Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier
Dim identifierName = TryCast(node, IdentifierNameSyntax)
Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso
identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso
identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso
identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute)
End Function
Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration
If root Is Nothing Then
Throw New ArgumentNullException(NameOf(root))
End If
If position < 0 OrElse position > root.Span.End Then
Throw New ArgumentOutOfRangeException(NameOf(position))
End If
Return root.
FindToken(position).
GetAncestors(Of SyntaxNode)().
FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax)
End Function
Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim parent = node.Parent
While node IsNot Nothing
If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then
Return node
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function FindTokenOnLeftOfPosition(node As SyntaxNode,
position As Integer,
Optional includeSkipped As Boolean = True,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition
Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments)
End Function
Public Function FindTokenOnRightOfPosition(node As SyntaxNode,
position As Integer,
Optional includeSkipped As Boolean = True,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition
Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments)
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim unused As SyntaxNode = Nothing
Return IsMemberInitializerNamedAssignmentIdentifier(node, unused)
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(
node As SyntaxNode,
ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
' .parent is the NamedField.
' .parent.parent is the ObjectInitializer.
' .parent.parent.parent will be the ObjectCreationExpression.
initializedInstance = identifier.Parent.Parent.Parent
Return True
End If
Return False
End Function
Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern
Return False
End Function
Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause
Return False
End Function
Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression
' VB doesn't have a specialized node for element access. Instead, it just uses an
' invocation expression or dictionary access expression.
Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression
End Function
Public Sub GetPartsOfParenthesizedExpression(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression
Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax)
openParen = parenthesizedExpression.OpenParenToken
expression = parenthesizedExpression.Expression
closeParen = parenthesizedExpression.CloseParenToken
End Sub
Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration
Return False
End Function
Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic
Return False
End Function
Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef
Return False
End Function
Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration
Contract.ThrowIfNull(root, NameOf(root))
Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position))
Dim [end] = root.FullSpan.End
If [end] = 0 Then
' empty file
Return Nothing
End If
' make sure position doesn't touch end of root
position = Math.Min(position, [end] - 1)
Dim node = root.FindToken(position).Parent
While node IsNot Nothing
If useFullSpan OrElse node.Span.Contains(position) Then
If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return node
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is FieldDeclarationSyntax Then
Return node
End If
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember
' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and
' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things
' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level
' members.
If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return True
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return True
End If
If TypeOf node Is DeclareStatementSyntax Then
Return True
End If
Return TypeOf node Is ConstructorBlockSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is OperatorBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is FieldDeclarationSyntax
End Function
Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding
Dim member = GetContainingMemberDeclaration(node, node.SpanStart)
If member Is Nothing Then
Return Nothing
End If
' TODO: currently we only support method for now
Dim method = TryCast(member, MethodBlockBaseSyntax)
If method IsNot Nothing Then
If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then
Return Nothing
End If
' We don't want to include the BlockStatement or any trailing trivia up to and including its statement
' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up
' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start
' of the EndBlockStatements leading trivia.
Dim firstStatement = method.Statements.FirstOrDefault()
Dim spanStart = If(firstStatement IsNot Nothing,
firstStatement.FullSpan.Start,
method.EndBlockStatement.FullSpan.Start)
Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart)
End If
Return Nothing
End Function
Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span)
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span)
End If
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span)
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span)
End If
Return False
End Function
Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean
If innerSpan.IsEmpty Then
Return outerSpan.Contains(innerSpan.Start)
End If
Return outerSpan.Contains(innerSpan)
End Function
Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=True, methodLevel:=True)
Return list
End Function
Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=False, methodLevel:=True)
Return list
End Function
Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration
Return node.IsKind(SyntaxKind.ClassBlock)
End Function
Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration
Return node.IsKind(SyntaxKind.NamespaceBlock)
End Function
Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration
If IsNamespaceDeclaration(node) Then
Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name
End If
Return Nothing
End Function
Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration
Return DirectCast(typeDeclaration, TypeBlockSyntax).Members
End Function
Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration
Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members
End Function
Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit
Return DirectCast(compilationUnit, CompilationUnitSyntax).Members
End Function
Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration
'Visual Basic doesn't have namespaced imports
Return Nothing
End Function
Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit
Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports
End Function
Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers
Return TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Private Const s_dotToken As String = "."
Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName
If node Is Nothing Then
Return String.Empty
End If
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
' member keyword (if any)
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then
Dim keywordToken = memberDeclaration.GetMemberKeywordToken()
If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then
builder.Append(keywordToken.Text)
builder.Append(" "c)
End If
End If
Dim names = ArrayBuilder(Of String).GetInstance()
' containing type(s)
Dim parent = node.Parent
While TypeOf parent Is TypeBlockSyntax
names.Push(GetName(parent, options, containsGlobalKeyword:=False))
parent = parent.Parent
End While
If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then
' containing namespace(s) in source (if any)
Dim containsGlobalKeyword As Boolean = False
While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock
names.Push(GetName(parent, options, containsGlobalKeyword))
parent = parent.Parent
End While
' root namespace (if any)
If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then
builder.Append(rootNamespace)
builder.Append(s_dotToken)
End If
End If
While Not names.IsEmpty()
Dim name = names.Pop()
If name IsNot Nothing Then
builder.Append(name)
builder.Append(s_dotToken)
End If
End While
names.Free()
' name (include generic type parameters)
builder.Append(GetName(node, options, containsGlobalKeyword:=False))
' parameter list (if any)
If (options And DisplayNameOptions.IncludeParameters) <> 0 Then
builder.Append(memberDeclaration.GetParameterList())
End If
' As clause (if any)
If (options And DisplayNameOptions.IncludeType) <> 0 Then
Dim asClause = memberDeclaration.GetAsClause()
If asClause IsNot Nothing Then
builder.Append(" "c)
builder.Append(asClause)
End If
End If
Return pooled.ToStringAndFree()
End Function
Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String
Const missingTokenPlaceholder As String = "?"
Select Case node.Kind()
Case SyntaxKind.CompilationUnit
Return Nothing
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier
Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text)
Case SyntaxKind.IncompleteMember
Return missingTokenPlaceholder
Case SyntaxKind.NamespaceBlock
Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name
If nameSyntax.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return Nothing
Else
Return GetName(nameSyntax, options, containsGlobalKeyword)
End If
Case SyntaxKind.QualifiedName
Dim qualified = CType(node, QualifiedNameSyntax)
If qualified.Left.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified
Else
Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword)
End If
End Select
Dim name As String = Nothing
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If memberDeclaration IsNot Nothing Then
Dim nameToken = memberDeclaration.GetNameToken()
If nameToken <> Nothing Then
name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text)
If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
builder.Append(name)
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList())
name = pooled.ToStringAndFree()
End If
End If
End If
Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString())
Return name
End Function
Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax)
If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then
builder.Append("(Of ")
builder.Append(typeParameterList.Parameters(0).Identifier.Text)
For i = 1 To typeParameterList.Parameters.Count - 1
builder.Append(", ")
builder.Append(typeParameterList.Parameters(i).Identifier.Text)
Next
builder.Append(")"c)
End If
End Sub
Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean)
Debug.Assert(topLevel OrElse methodLevel)
For Each member In node.GetMembers()
If IsTopLevelNodeWithMembers(member) Then
If topLevel Then
list.Add(member)
End If
AppendMembers(member, list, topLevel, methodLevel)
Continue For
End If
If methodLevel AndAlso IsMethodLevelMember(member) Then
list.Add(member)
End If
Next
End Sub
Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent
Dim node = token.Parent
While node IsNot Nothing
Dim parent = node.Parent
' If this node is on the left side of a member access expression, don't ascend
' further or we'll end up binding to something else.
Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
If memberAccess.Expression Is node Then
Exit While
End If
End If
' If this node is on the left side of a qualified name, don't ascend
' further or we'll end up binding to something else.
Dim qualifiedName = TryCast(parent, QualifiedNameSyntax)
If qualifiedName IsNot Nothing Then
If qualifiedName.Left Is node Then
Exit While
End If
End If
' If this node is the type of an object creation expression, return the
' object creation expression.
Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax)
If objectCreation IsNot Nothing Then
If objectCreation.Type Is node Then
node = parent
Exit While
End If
End If
' The inside of an interpolated string is treated as its own token so we
' need to force navigation to the parent expression syntax.
If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then
node = parent
Exit While
End If
' If this node is not parented by a name, we're done.
Dim name = TryCast(parent, NameSyntax)
If name Is Nothing Then
Exit While
End If
node = parent
End While
Return node
End Function
Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors
Dim compilationUnit = TryCast(root, CompilationUnitSyntax)
If compilationUnit Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim constructors = New List(Of SyntaxNode)()
AppendConstructors(compilationUnit.Members, constructors, cancellationToken)
Return constructors
End Function
Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken)
For Each member As StatementSyntax In members
cancellationToken.ThrowIfCancellationRequested()
Dim constructor = TryCast(member, ConstructorBlockSyntax)
If constructor IsNot Nothing Then
constructors.Add(constructor)
Continue For
End If
Dim [namespace] = TryCast(member, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
AppendConstructors([namespace].Members, constructors, cancellationToken)
End If
Dim [class] = TryCast(member, ClassBlockSyntax)
If [class] IsNot Nothing Then
AppendConstructors([class].Members, constructors, cancellationToken)
End If
Dim [struct] = TryCast(member, StructureBlockSyntax)
If [struct] IsNot Nothing Then
AppendConstructors([struct].Members, constructors, cancellationToken)
End If
Next
End Sub
Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition
Dim trivia = tree.FindTriviaToLeft(position, cancellationToken)
If trivia.Kind = SyntaxKind.DisabledTextTrivia Then
Return trivia.FullSpan
End If
Return Nothing
End Function
Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument
If TryCast(argument, ArgumentSyntax)?.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End If
Return String.Empty
End Function
Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument
' All argument types are ArgumentSyntax in VB.
Return GetNameForArgument(argument)
End Function
Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot
Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot()
End Function
Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Right,
TryCast(node, MemberAccessExpressionSyntax)?.Name)
End Function
Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Left,
TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget))
End Function
Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier
Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing
End Function
Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement
End Function
Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement
End Function
Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement
End Function
Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment
Return TryCast(node, AssignmentStatementSyntax)?.Right
End Function
Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator
Return node.IsKind(SyntaxKind.InferredFieldInitializer)
End Function
Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression
Return False
End Function
Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression
Return False
End Function
Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString
Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value
End Function
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral
Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral
' VB does not have verbatim strings
Return False
End Function
Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression
Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList)
End Function
Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression
Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList)
End Function
Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList
Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments
Return If(arguments.HasValue, arguments.Value, Nothing)
End Function
Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression
Return DirectCast(node, InvocationExpressionSyntax).ArgumentList
End Function
Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression
Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList
End Function
Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine
Return node.ConvertToSingleLine(useElasticTrivia)
End Function
Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return node.IsKind(SyntaxKind.DocumentationCommentTrivia)
End Function
Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport
Return node.IsKind(SyntaxKind.ImportsStatement)
End Function
Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute
Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword)
End Function
Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute
Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword)
End Function
Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean
If node.IsKind(SyntaxKind.Attribute) Then
Dim attributeNode = CType(node, AttributeSyntax)
If attributeNode.Target IsNot Nothing Then
Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget)
End If
End If
Return False
End Function
Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration
' From the Visual Basic language spec:
' NamespaceMemberDeclaration :=
' NamespaceDeclaration |
' TypeDeclaration
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
' ClassMemberDeclaration ::=
' NonModuleDeclaration |
' EventMemberDeclaration |
' VariableMemberDeclaration |
' ConstantMemberDeclaration |
' MethodMemberDeclaration |
' PropertyMemberDeclaration |
' ConstructorMemberDeclaration |
' OperatorDeclaration
Select Case node.Kind()
' Because fields declarations can define multiple symbols "Public a, b As Integer"
' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
Case SyntaxKind.VariableDeclarator
If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then
Return True
End If
Return False
Case SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumStatement,
SyntaxKind.EnumBlock,
SyntaxKind.StructureStatement,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassStatement,
SyntaxKind.ClassBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EventStatement,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.FieldDeclaration,
SyntaxKind.SubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SubNewStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.OperatorBlock
Return True
End Select
Return False
End Function
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return True
End Select
Return False
End Function
Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer
Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer
End Function
Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType
Return DirectCast(node, ObjectCreationExpressionSyntax).Type
End Function
Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement
Return node.IsKind(SyntaxKind.SimpleAssignmentStatement)
End Function
Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement
' VB only has assignment statements, so this can just delegate to that helper
GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right)
End Sub
Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement
Dim assignment = DirectCast(statement, AssignmentStatementSyntax)
left = assignment.Left
operatorToken = assignment.OperatorToken
right = assignment.Right
End Sub
Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression
Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name
End Function
Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName
Return DirectCast(node, SimpleNameSyntax).Identifier
End Function
Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier
End Function
Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter
Return DirectCast(node, ParameterSyntax).Identifier.Identifier
End Function
Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return DirectCast(node, TypeStatementSyntax).Identifier
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier
End Select
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName
Return DirectCast(node, IdentifierNameSyntax).Identifier
End Function
Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement
' VB does not have local functions
Return False
End Function
Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement
Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators.
Contains(DirectCast(declarator, VariableDeclaratorSyntax))
End Function
Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(token1, token2)
End Function
Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(node1, node2)
End Function
Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node
End Function
Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node
End Function
Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).Expression
End Function
Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach
Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement
Return DirectCast(node, ExpressionStatementSyntax).Expression
End Function
Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression
Return TypeOf node Is BinaryExpressionSyntax
End Function
Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression
Return node.IsKind(SyntaxKind.TypeOfIsExpression)
End Function
Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression
Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax)
left = binaryExpression.Left
operatorToken = binaryExpression.OperatorToken
right = binaryExpression.Right
End Sub
Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression
Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax)
condition = conditionalExpression.Condition
whenTrue = conditionalExpression.WhenTrue
whenFalse = conditionalExpression.WhenFalse
End Sub
Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses
Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node)
End Function
Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression
Dim tupleExpr = DirectCast(node, TupleExpressionSyntax)
openParen = tupleExpr.OpenParenToken
arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax))
closeParen = tupleExpr.CloseParenToken
End Sub
Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression
Return DirectCast(node, UnaryExpressionSyntax).Operand
End Function
Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression
Return DirectCast(node, UnaryExpressionSyntax).OperatorToken
End Function
Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression
Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax)
expression = memberAccess.Expression
operatorToken = memberAccess.OperatorToken
name = memberAccess.Name
End Sub
Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement
Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax)
End Function
Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have multi-line comments.
Return False
End Function
Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have multi-line comments.
Return False
End Function
Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have shebang directives.
Return False
End Function
Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean
Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind())
End Function
Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic
Return trivia.IsElastic()
End Function
Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective
Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes)
End Function
Public Function IsOnTypeHeader(
root As SyntaxNode,
position As Integer,
fullHeader As Boolean,
ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader
Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position)
If typeBlock Is Nothing Then
Return Nothing
End If
Dim typeStatement = typeBlock.BlockStatement
typeDeclaration = typeStatement
Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier)
If fullHeader Then
lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(),
If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(),
lastToken))
End If
Return IsOnHeader(root, position, typeBlock, lastToken)
End Function
Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader
Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position)
propertyDeclaration = node
If propertyDeclaration Is Nothing Then
Return False
End If
If node.AsClause IsNot Nothing Then
Return IsOnHeader(root, position, node, node.AsClause)
End If
Return IsOnHeader(root, position, node, node.Identifier)
End Function
Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader
Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position)
parameter = node
If parameter Is Nothing Then
Return False
End If
Return IsOnHeader(root, position, node, node)
End Function
Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader
Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position)
method = node
If method Is Nothing Then
Return False
End If
If node.HasReturnType() Then
Return IsOnHeader(root, position, method, node.GetReturnType())
End If
If node.ParameterList IsNot Nothing Then
Return IsOnHeader(root, position, method, node.ParameterList)
End If
Return IsOnHeader(root, position, node, node)
End Function
Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader
' No local functions in VisualBasic
Return False
End Function
Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader
Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position)
localDeclaration = node
If localDeclaration Is Nothing Then
Return False
End If
Dim initializersExpressions = node.Declarators.
Where(Function(d) d.Initializer IsNot Nothing).
SelectAsArray(Function(initialized) initialized.Initializer.Value)
Return IsOnHeader(root, position, node, node, initializersExpressions)
End Function
Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader
ifStatement = Nothing
Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position)
If multipleLineNode IsNot Nothing Then
ifStatement = multipleLineNode
Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement)
End If
Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position)
If singleLineNode IsNot Nothing Then
ifStatement = singleLineNode
Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition)
End If
Return False
End Function
Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader
whileStatement = Nothing
Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position)
If whileBlock IsNot Nothing Then
whileStatement = whileBlock
Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement)
End If
Return False
End Function
Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader
Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position)
foreachStatement = node
If foreachStatement Is Nothing Then
Return False
End If
Return IsOnHeader(root, position, node, node.ForEachStatement)
End Function
Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers
Dim token = root.FindToken(position)
Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax)
typeDeclaration = typeDecl
If typeDecl IsNot Nothing Then
Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End,
If(typeDecl.Inherits.LastOrDefault()?.Span.End,
typeDecl.BlockStatement.Span.End))
If position >= start AndAlso
position <= typeDecl.EndBlockStatement.Span.Start Then
Dim line = sourceText.Lines.GetLineFromPosition(position)
If Not line.IsEmptyOrWhitespace() Then
Return False
End If
Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position))
If member Is Nothing Then
' There are no members, Or we're after the last member.
Return True
Else
' We're within a member. Make sure we're in the leading whitespace of
' the member.
If position < member.SpanStart Then
For Each trivia In member.GetLeadingTrivia()
If Not trivia.IsWhitespaceOrEndOfLine() Then
Return False
End If
If trivia.FullSpan.Contains(position) Then
Return True
End If
Next
End If
End If
End If
End If
Return False
End Function
Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner
Return GetFileBanner(root)
End Function
Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner
Return GetFileBanner(firstToken)
End Function
Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean
Return token.ContainsInterleavedDirective(span, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(node, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(nodes, cancellationToken)
End Function
Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia
Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia
End Function
Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText
Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken)
End Function
Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers
Return node.GetModifiers()
End Function
Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers
Return node.WithModifiers(modifiers)
End Function
Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression
Return TypeOf node Is LiteralExpressionSyntax
End Function
Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement
Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators
End Function
Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Initializer
End Function
Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type
End Function
Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause
Return DirectCast(node, EqualsValueSyntax).Value
End Function
Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock
' VB has no equivalent of curly braces.
Return False
End Function
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock
Return node.IsExecutableBlock()
End Function
Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements
Return node.GetExecutableBlockStatements()
End Function
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock
Return nodes.FindInnermostCommonExecutableBlock()
End Function
Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer
Return IsExecutableBlock(node)
End Function
Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements
Return GetExecutableBlockStatements(node)
End Function
Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines
Return MyBase.GetLeadingBlankLines(node)
End Function
Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines
Return MyBase.GetNodeWithoutLeadingBlankLines(node)
End Function
Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression
Return node.Kind = SyntaxKind.CTypeExpression
End Function
Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression
Return node.Kind = SyntaxKind.DirectCastExpression
End Function
Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression
Dim cast = DirectCast(node, DirectCastExpressionSyntax)
type = cast.Type
expression = cast.Expression
End Sub
Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation
Throw New NotImplementedException()
End Function
Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride
If token.Kind() = SyntaxKind.OverridesKeyword Then
Dim parent = token.Parent
Select Case parent.Kind()
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(parent, MethodStatementSyntax)
Return method.Identifier
Case SyntaxKind.PropertyStatement
Dim [property] = DirectCast(parent, PropertyStatementSyntax)
Return [property].Identifier
End Select
End If
Return Nothing
End Function
Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective
Return MyBase.SpansPreprocessorDirective(nodes)
End Function
Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean
Return MyBase.SpansPreprocessorDirective(tokens)
End Function
Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression
Dim invocation = DirectCast(node, InvocationExpressionSyntax)
expression = invocation.Expression
argumentList = invocation.ArgumentList
End Sub
Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression
' Does not exist in VB.
Return False
End Function
Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists
Return node.GetAttributeLists()
End Function
Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective
Dim importStatement = TryCast(node, ImportsStatementSyntax)
If (importStatement IsNot Nothing) Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Return True
End If
End If
Next
End If
Return False
End Function
Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax
Dim xmlElement = TryCast(node, XmlElementSyntax)
If xmlElement IsNot Nothing Then
Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax)
Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName
End If
Return False
End Function
Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax
Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax)
If documentationCommentTrivia IsNot Nothing Then
Return documentationCommentTrivia.Content
End If
Return Nothing
End Function
Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility
Select Case declaration.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.ClassStatement,
SyntaxKind.StructureBlock,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.EnumBlock,
SyntaxKind.EnumStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.EventBlock,
SyntaxKind.EventStatement,
SyntaxKind.GetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.RaiseEventAccessorStatement
Return True
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubNewStatement
' Shared constructor cannot have modifiers in VB.
' Module constructors are implicitly Shared and can't have accessibility modifier.
Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso
Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock)
Case SyntaxKind.ModifiedIdentifier
Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator),
CanHaveAccessibility(declaration.Parent),
False)
Case SyntaxKind.VariableDeclarator
Return If(IsChildOfVariableDeclaration(declaration),
CanHaveAccessibility(declaration.Parent),
False)
Case Else
Return False
End Select
End Function
Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind)
End Function
Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean
Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement)
End Function
Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility
If Not CanHaveAccessibility(declaration) Then
Return Accessibility.NotApplicable
End If
Dim tokens = GetModifierTokens(declaration)
Dim acc As Accessibility
Dim mods As DeclarationModifiers
Dim isDefault As Boolean
GetAccessibilityAndModifiers(tokens, acc, mods, isDefault)
Return acc
End Function
Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.ClassStatement
Return DirectCast(declaration, ClassStatementSyntax).Modifiers
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.StructureStatement
Return DirectCast(declaration, StructureStatementSyntax).Modifiers
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.InterfaceStatement
Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers
Case SyntaxKind.EnumBlock
Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers
Case SyntaxKind.EnumStatement
Return DirectCast(declaration, EnumStatementSyntax).Modifiers
Case SyntaxKind.ModuleBlock
Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers
Case SyntaxKind.ModuleStatement
Return DirectCast(declaration, ModuleStatementSyntax).Modifiers
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(declaration, DelegateStatementSyntax).Modifiers
Case SyntaxKind.FieldDeclaration
Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(declaration, MethodStatementSyntax).Modifiers
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).Modifiers
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).Modifiers
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).Modifiers
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).Modifiers
Case SyntaxKind.ModifiedIdentifier
If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then
Return GetModifierTokens(declaration.Parent)
End If
Case SyntaxKind.LocalDeclarationStatement
Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers
Case SyntaxKind.VariableDeclarator
If IsChildOfVariableDeclaration(declaration) Then
Return GetModifierTokens(declaration.Parent)
End If
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement)
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(declaration, AccessorStatementSyntax).Modifiers
Case Else
Return Nothing
End Select
End Function
Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers
accessibility = Accessibility.NotApplicable
modifiers = DeclarationModifiers.None
isDefault = False
For Each token In modifierTokens
Select Case token.Kind
Case SyntaxKind.DefaultKeyword
isDefault = True
Case SyntaxKind.PublicKeyword
accessibility = Accessibility.Public
Case SyntaxKind.PrivateKeyword
If accessibility = Accessibility.Protected Then
accessibility = Accessibility.ProtectedAndFriend
Else
accessibility = Accessibility.Private
End If
Case SyntaxKind.FriendKeyword
If accessibility = Accessibility.Protected Then
accessibility = Accessibility.ProtectedOrFriend
Else
accessibility = Accessibility.Friend
End If
Case SyntaxKind.ProtectedKeyword
If accessibility = Accessibility.Friend Then
accessibility = Accessibility.ProtectedOrFriend
ElseIf accessibility = Accessibility.Private Then
accessibility = Accessibility.ProtectedAndFriend
Else
accessibility = Accessibility.Protected
End If
Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword
modifiers = modifiers Or DeclarationModifiers.Abstract
Case SyntaxKind.ShadowsKeyword
modifiers = modifiers Or DeclarationModifiers.[New]
Case SyntaxKind.OverridesKeyword
modifiers = modifiers Or DeclarationModifiers.Override
Case SyntaxKind.OverridableKeyword
modifiers = modifiers Or DeclarationModifiers.Virtual
Case SyntaxKind.SharedKeyword
modifiers = modifiers Or DeclarationModifiers.Static
Case SyntaxKind.AsyncKeyword
modifiers = modifiers Or DeclarationModifiers.Async
Case SyntaxKind.ConstKeyword
modifiers = modifiers Or DeclarationModifiers.Const
Case SyntaxKind.ReadOnlyKeyword
modifiers = modifiers Or DeclarationModifiers.ReadOnly
Case SyntaxKind.WriteOnlyKeyword
modifiers = modifiers Or DeclarationModifiers.WriteOnly
Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword
modifiers = modifiers Or DeclarationModifiers.Sealed
Case SyntaxKind.WithEventsKeyword
modifiers = modifiers Or DeclarationModifiers.WithEvents
Case SyntaxKind.PartialKeyword
modifiers = modifiers Or DeclarationModifiers.Partial
End Select
Next
End Sub
Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return DeclarationKind.CompilationUnit
Case SyntaxKind.NamespaceBlock
Return DeclarationKind.Namespace
Case SyntaxKind.ImportsStatement
Return DeclarationKind.NamespaceImport
Case SyntaxKind.ClassBlock
Return DeclarationKind.Class
Case SyntaxKind.StructureBlock
Return DeclarationKind.Struct
Case SyntaxKind.InterfaceBlock
Return DeclarationKind.Interface
Case SyntaxKind.EnumBlock
Return DeclarationKind.Enum
Case SyntaxKind.EnumMemberDeclaration
Return DeclarationKind.EnumMember
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DeclarationKind.Delegate
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DeclarationKind.Method
Case SyntaxKind.FunctionStatement
If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then
Return DeclarationKind.Method
End If
Case SyntaxKind.SubStatement
If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then
Return DeclarationKind.Method
End If
Case SyntaxKind.ConstructorBlock
Return DeclarationKind.Constructor
Case SyntaxKind.PropertyBlock
If IsIndexer(declaration) Then
Return DeclarationKind.Indexer
Else
Return DeclarationKind.Property
End If
Case SyntaxKind.PropertyStatement
If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then
If IsIndexer(declaration) Then
Return DeclarationKind.Indexer
Else
Return DeclarationKind.Property
End If
End If
Case SyntaxKind.OperatorBlock
Return DeclarationKind.Operator
Case SyntaxKind.OperatorStatement
If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then
Return DeclarationKind.Operator
End If
Case SyntaxKind.EventBlock
Return DeclarationKind.CustomEvent
Case SyntaxKind.EventStatement
If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then
Return DeclarationKind.Event
End If
Case SyntaxKind.Parameter
Return DeclarationKind.Parameter
Case SyntaxKind.FieldDeclaration
Return DeclarationKind.Field
Case SyntaxKind.LocalDeclarationStatement
If GetDeclarationCount(declaration) = 1 Then
Return DeclarationKind.Variable
End If
Case SyntaxKind.ModifiedIdentifier
If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then
If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then
Return DeclarationKind.Field
ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then
Return DeclarationKind.Variable
End If
End If
Case SyntaxKind.Attribute
Dim list = TryCast(declaration.Parent, AttributeListSyntax)
If list Is Nothing OrElse list.Attributes.Count > 1 Then
Return DeclarationKind.Attribute
End If
Case SyntaxKind.AttributeList
Dim list = DirectCast(declaration, AttributeListSyntax)
If list.Attributes.Count = 1 Then
Return DeclarationKind.Attribute
End If
Case SyntaxKind.GetAccessorBlock
Return DeclarationKind.GetAccessor
Case SyntaxKind.SetAccessorBlock
Return DeclarationKind.SetAccessor
Case SyntaxKind.AddHandlerAccessorBlock
Return DeclarationKind.AddAccessor
Case SyntaxKind.RemoveHandlerAccessorBlock
Return DeclarationKind.RemoveAccessor
Case SyntaxKind.RaiseEventAccessorBlock
Return DeclarationKind.RaiseAccessor
End Select
Return DeclarationKind.None
End Function
Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer
Dim count As Integer = 0
For i = 0 To nodes.Count - 1
count = count + GetDeclarationCount(nodes(i))
Next
Return count
End Function
Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators)
Case SyntaxKind.LocalDeclarationStatement
Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators)
Case SyntaxKind.VariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Count
Case SyntaxKind.AttributesStatement
Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists)
Case SyntaxKind.AttributeList
Return DirectCast(node, AttributeListSyntax).Attributes.Count
Case SyntaxKind.ImportsStatement
Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count
End Select
Return 1
End Function
Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement
Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword)
Case SyntaxKind.PropertyStatement
If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then
Dim p = DirectCast(declaration, PropertyStatementSyntax)
Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword)
End If
End Select
Return False
End Function
Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation
Return False
End Function
Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern
Return False
End Function
Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression
Return False
End Function
Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern
Return False
End Function
Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern
Return False
End Function
Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern
Return False
End Function
Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern
Return False
End Function
Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern
Return False
End Function
Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern
Return False
End Function
Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern
Return False
End Function
Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern
Return False
End Function
Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern
Return False
End Function
Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern
Return False
End Function
Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern
Return False
End Function
Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern
Return False
End Function
Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression
Throw ExceptionUtilities.Unreachable
End Sub
Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern
Throw ExceptionUtilities.Unreachable
End Function
Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern
Throw New NotImplementedException()
End Sub
Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern
Throw New NotImplementedException()
End Sub
Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern
Throw New NotImplementedException()
End Function
Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression
' ThrowExpression doesn't exist in VB
Throw New NotImplementedException()
End Function
Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement
Return node.IsKind(SyntaxKind.ThrowStatement)
End Function
Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction
Return False
End Function
Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression
Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax)
stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken
contents = interpolatedStringExpressionSyntax.Contents
stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken
End Sub
Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression
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 System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
#If CODE_STYLE Then
Imports Microsoft.CodeAnalysis.Internal.Editing
#Else
Imports Microsoft.CodeAnalysis.Editing
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Friend Class VisualBasicSyntaxFacts
Inherits AbstractSyntaxFacts
Implements ISyntaxFacts
Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts
Protected Sub New()
End Sub
Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive
Get
Return False
End Get
End Property
Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer
Get
Return CaseInsensitiveComparison.Comparer
End Get
End Property
Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker
Get
Return SyntaxFactory.ElasticMarker
End Get
End Property
Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds
Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService
Get
Return VisualBasicDocumentationCommentService.Instance
End Get
End Property
Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer
Return False
End Function
Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression
Return False
End Function
Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration
Return False
End Function
Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord
Return False
End Function
Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct
Return False
End Function
Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken
Return SyntaxFactory.ParseToken(text, startStatement:=True)
End Function
Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia
Return SyntaxFactory.ParseLeadingTrivia(text)
End Function
Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier
Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier)
Dim needsEscaping = keywordKind <> SyntaxKind.None
Return If(needsEscaping, "[" & identifier & "]", identifier)
End Function
Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return False
End Function
Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator
Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse
(IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax))
End Function
Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword
Return token.IsContextualKeyword()
End Function
Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword
Return token.IsReservedKeyword()
End Function
Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword
Return token.IsPreprocessorKeyword()
End Function
Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext
Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)
End Function
Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace
If token.Kind = SyntaxKind.CloseBraceToken Then
Dim tuples = token.Parent.GetBraces()
openBrace = tuples.openBrace
Return openBrace.Kind = SyntaxKind.OpenBraceToken
End If
Return False
End Function
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken)
End Function
Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective
Return TypeOf node Is DirectiveTriviaSyntax
End Function
Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo
Select Case node.Kind
Case SyntaxKind.ExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False)
Return True
Case SyntaxKind.EndExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(Nothing, True)
Return True
End Select
Return False
End Function
Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType
Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso
DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node
End Function
Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression
' VB doesn't support declaration expressions
Return False
End Function
Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName
Return node.IsParentKind(SyntaxKind.Attribute) AndAlso
DirectCast(node.Parent, AttributeSyntax).Name Is node
End Function
Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName
Dim vbNode = TryCast(node, SimpleNameSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName()
End Function
Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression
Dim vbNode = TryCast(node, ExpressionSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName()
End Function
Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression
Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax)
Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node
End Function
Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression
Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax))
End Function
Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression
Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression()
End Function
Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression
Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax)
expression = conditionalAccess.Expression
operatorToken = conditionalAccess.QuestionMarkToken
whenNotNull = conditionalAccess.WhenNotNull
End Sub
Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction
Return TypeOf node Is LambdaExpressionSyntax
End Function
Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument
Dim arg = TryCast(node, SimpleArgumentSyntax)
Return arg?.NameColonEquals IsNot Nothing
End Function
Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument
Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node)
End Function
Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter
Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier
End Function
Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter
Return TryCast(node, ParameterSyntax)?.Default
End Function
Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList
Return node.GetParameterList()
End Function
Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList
Return node.IsKind(SyntaxKind.ParameterList)
End Function
Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember
Return HasIncompleteParentMember(node)
End Function
Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName
Dim vbGenericName = TryCast(genericName, GenericNameSyntax)
Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing)
End Function
Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName
Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso
DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node
End Function
Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment
Return False
End Function
Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement
Return False
End Function
Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement
Return TypeOf node Is StatementSyntax
End Function
Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement
Return TypeOf node Is ExecutableStatementSyntax
End Function
Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody
Return TypeOf node Is MethodBlockBaseSyntax
End Function
Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement
Return TryCast(node, ReturnStatementSyntax)?.Expression
End Function
Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsThisConstructorInitializer()
End If
Return False
End Function
Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsBaseConstructorInitializer()
End If
Return False
End Function
Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword
Select Case token.Kind()
Case _
SyntaxKind.JoinKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.SelectKeyword
Return TypeOf token.Parent Is QueryClauseSyntax
Case SyntaxKind.GroupKeyword
Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation))
Case SyntaxKind.EqualsKeyword
Return TypeOf token.Parent Is JoinConditionSyntax
Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword
Return TypeOf token.Parent Is OrderingSyntax
Case SyntaxKind.InKeyword
Return TypeOf token.Parent Is CollectionRangeVariableSyntax
Case Else
Return False
End Select
End Function
Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression
' VB does not support throw expressions currently.
Return False
End Function
Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None
End Function
Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType = type
End Function
Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType
type = GetPredefinedType(token)
Return type <> PredefinedType.None
End Function
Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType
Select Case token.Kind
Case SyntaxKind.BooleanKeyword
Return PredefinedType.Boolean
Case SyntaxKind.ByteKeyword
Return PredefinedType.Byte
Case SyntaxKind.SByteKeyword
Return PredefinedType.SByte
Case SyntaxKind.IntegerKeyword
Return PredefinedType.Int32
Case SyntaxKind.UIntegerKeyword
Return PredefinedType.UInt32
Case SyntaxKind.ShortKeyword
Return PredefinedType.Int16
Case SyntaxKind.UShortKeyword
Return PredefinedType.UInt16
Case SyntaxKind.LongKeyword
Return PredefinedType.Int64
Case SyntaxKind.ULongKeyword
Return PredefinedType.UInt64
Case SyntaxKind.SingleKeyword
Return PredefinedType.Single
Case SyntaxKind.DoubleKeyword
Return PredefinedType.Double
Case SyntaxKind.DecimalKeyword
Return PredefinedType.Decimal
Case SyntaxKind.StringKeyword
Return PredefinedType.String
Case SyntaxKind.CharKeyword
Return PredefinedType.Char
Case SyntaxKind.ObjectKeyword
Return PredefinedType.Object
Case SyntaxKind.DateKeyword
Return PredefinedType.DateTime
Case Else
Return PredefinedType.None
End Select
End Function
Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None
End Function
Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op
End Function
Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator
op = GetPredefinedOperator(token)
Return op <> PredefinedOperator.None
End Function
Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator
Select Case token.Kind
Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken
Return PredefinedOperator.Addition
Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken
Return PredefinedOperator.Subtraction
Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword
Return PredefinedOperator.BitwiseAnd
Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword
Return PredefinedOperator.BitwiseOr
Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken
Return PredefinedOperator.Concatenate
Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken
Return PredefinedOperator.Division
Case SyntaxKind.EqualsToken
Return PredefinedOperator.Equality
Case SyntaxKind.XorKeyword
Return PredefinedOperator.ExclusiveOr
Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken
Return PredefinedOperator.Exponent
Case SyntaxKind.GreaterThanToken
Return PredefinedOperator.GreaterThan
Case SyntaxKind.GreaterThanEqualsToken
Return PredefinedOperator.GreaterThanOrEqual
Case SyntaxKind.LessThanGreaterThanToken
Return PredefinedOperator.Inequality
Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken
Return PredefinedOperator.IntegerDivision
Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken
Return PredefinedOperator.LeftShift
Case SyntaxKind.LessThanToken
Return PredefinedOperator.LessThan
Case SyntaxKind.LessThanEqualsToken
Return PredefinedOperator.LessThanOrEqual
Case SyntaxKind.LikeKeyword
Return PredefinedOperator.Like
Case SyntaxKind.NotKeyword
Return PredefinedOperator.Complement
Case SyntaxKind.ModKeyword
Return PredefinedOperator.Modulus
Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken
Return PredefinedOperator.Multiplication
Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken
Return PredefinedOperator.RightShift
Case Else
Return PredefinedOperator.None
End Select
End Function
Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText
Return SyntaxFacts.GetText(CType(kind, SyntaxKind))
End Function
Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter
Return SyntaxFacts.IsIdentifierPartCharacter(c)
End Function
Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter
Return SyntaxFacts.IsIdentifierStartCharacter(c)
End Function
Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter
Return c = "["c OrElse c = "]"c
End Function
Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier
Dim token = SyntaxFactory.ParseToken(identifier)
' TODO: There is no way to get the diagnostics to see if any are actually errors?
Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length
End Function
Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]"
End Function
Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter
Return c = "%"c OrElse
c = "&"c OrElse
c = "@"c OrElse
c = "!"c OrElse
c = "#"c OrElse
c = "$"c
End Function
Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence
Return False ' VB does not support identifiers with escaped unicode characters
End Function
Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral
Select Case token.Kind()
Case _
SyntaxKind.IntegerLiteralToken,
SyntaxKind.CharacterLiteralToken,
SyntaxKind.DecimalLiteralToken,
SyntaxKind.FloatingLiteralToken,
SyntaxKind.DateLiteralToken,
SyntaxKind.StringLiteralToken,
SyntaxKind.DollarSignDoubleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.InterpolatedStringTextToken,
SyntaxKind.TrueKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.NothingKeyword
Return True
End Select
Return False
End Function
Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral
Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken)
End Function
Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression
Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression))
End Function
Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken
Return Me.IsWord(token) OrElse
Me.IsLiteral(token) OrElse
Me.IsOperator(token)
End Function
Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression
Return False
End Function
Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName
Dim simpleName = TryCast(node, SimpleNameSyntax)
If simpleName IsNot Nothing Then
name = simpleName.Identifier.ValueText
arity = simpleName.Arity
End If
End Sub
Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric
Return name.IsKind(SyntaxKind.GenericName)
End Function
Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression
Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)
End Function
Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding
' Member bindings are a C# concept.
Return Nothing
End Function
Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression
' Member bindings are a C# concept.
Return Nothing
End Function
Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression
Dim invocation = TryCast(node, InvocationExpressionSyntax)
If invocation IsNot Nothing Then
expression = invocation?.Expression
argumentList = invocation?.ArgumentList
Return
End If
If node.Kind() = SyntaxKind.DictionaryAccessExpression Then
GetPartsOfMemberAccessExpression(node, expression, argumentList)
Return
End If
Return
End Sub
Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation
Return TryCast(node, InterpolationSyntax)?.Expression
End Function
Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList
Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing
End Function
Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext
Return node.IsInStaticContext()
End Function
Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument
Return TryCast(node, ArgumentSyntax).GetArgumentExpression()
End Function
Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument
' TODO(cyrusn): Consider the method this argument is passed to, to determine this.
Return RefKind.None
End Function
Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument
Return TypeOf node Is ArgumentSyntax
End Function
Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument
Dim argument = TryCast(node, ArgumentSyntax)
Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted
End Function
Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext
Return node.IsInConstantContext()
End Function
Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor
Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock)
End Function
Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext
Return False
End Function
Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute
Return DirectCast(node, AttributeSyntax).Name
End Function
Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression
Return DirectCast(node, ParenthesizedExpressionSyntax).Expression
End Function
Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier
Dim identifierName = TryCast(node, IdentifierNameSyntax)
Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso
identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso
identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso
identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute)
End Function
Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration
If root Is Nothing Then
Throw New ArgumentNullException(NameOf(root))
End If
If position < 0 OrElse position > root.Span.End Then
Throw New ArgumentOutOfRangeException(NameOf(position))
End If
Return root.
FindToken(position).
GetAncestors(Of SyntaxNode)().
FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax)
End Function
Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim parent = node.Parent
While node IsNot Nothing
If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then
Return node
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function FindTokenOnLeftOfPosition(node As SyntaxNode,
position As Integer,
Optional includeSkipped As Boolean = True,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition
Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments)
End Function
Public Function FindTokenOnRightOfPosition(node As SyntaxNode,
position As Integer,
Optional includeSkipped As Boolean = True,
Optional includeDirectives As Boolean = False,
Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition
Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments)
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim unused As SyntaxNode = Nothing
Return IsMemberInitializerNamedAssignmentIdentifier(node, unused)
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(
node As SyntaxNode,
ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
' .parent is the NamedField.
' .parent.parent is the ObjectInitializer.
' .parent.parent.parent will be the ObjectCreationExpression.
initializedInstance = identifier.Parent.Parent.Parent
Return True
End If
Return False
End Function
Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern
Return False
End Function
Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause
Return False
End Function
Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression
' VB doesn't have a specialized node for element access. Instead, it just uses an
' invocation expression or dictionary access expression.
Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression
End Function
Public Sub GetPartsOfParenthesizedExpression(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression
Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax)
openParen = parenthesizedExpression.OpenParenToken
expression = parenthesizedExpression.Expression
closeParen = parenthesizedExpression.CloseParenToken
End Sub
Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration
Return False
End Function
Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic
Return False
End Function
Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef
Return False
End Function
Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration
Contract.ThrowIfNull(root, NameOf(root))
Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position))
Dim [end] = root.FullSpan.End
If [end] = 0 Then
' empty file
Return Nothing
End If
' make sure position doesn't touch end of root
position = Math.Min(position, [end] - 1)
Dim node = root.FindToken(position).Parent
While node IsNot Nothing
If useFullSpan OrElse node.Span.Contains(position) Then
If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return node
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is FieldDeclarationSyntax Then
Return node
End If
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember
' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and
' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things
' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level
' members.
If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return True
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return True
End If
If TypeOf node Is DeclareStatementSyntax Then
Return True
End If
Return TypeOf node Is ConstructorBlockSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is OperatorBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is FieldDeclarationSyntax
End Function
Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding
Dim member = GetContainingMemberDeclaration(node, node.SpanStart)
If member Is Nothing Then
Return Nothing
End If
' TODO: currently we only support method for now
Dim method = TryCast(member, MethodBlockBaseSyntax)
If method IsNot Nothing Then
If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then
Return Nothing
End If
' We don't want to include the BlockStatement or any trailing trivia up to and including its statement
' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up
' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start
' of the EndBlockStatements leading trivia.
Dim firstStatement = method.Statements.FirstOrDefault()
Dim spanStart = If(firstStatement IsNot Nothing,
firstStatement.FullSpan.Start,
method.EndBlockStatement.FullSpan.Start)
Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart)
End If
Return Nothing
End Function
Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span)
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span)
End If
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span)
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span)
End If
Return False
End Function
Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean
If innerSpan.IsEmpty Then
Return outerSpan.Contains(innerSpan.Start)
End If
Return outerSpan.Contains(innerSpan)
End Function
Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=True, methodLevel:=True)
Return list
End Function
Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=False, methodLevel:=True)
Return list
End Function
Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration
Return node.IsKind(SyntaxKind.ClassBlock)
End Function
Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration
Return node.IsKind(SyntaxKind.NamespaceBlock)
End Function
Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration
If IsNamespaceDeclaration(node) Then
Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name
End If
Return Nothing
End Function
Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration
Return DirectCast(typeDeclaration, TypeBlockSyntax).Members
End Function
Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration
Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members
End Function
Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit
Return DirectCast(compilationUnit, CompilationUnitSyntax).Members
End Function
Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration
'Visual Basic doesn't have namespaced imports
Return Nothing
End Function
Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit
Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports
End Function
Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers
Return TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Private Const s_dotToken As String = "."
Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName
If node Is Nothing Then
Return String.Empty
End If
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
' member keyword (if any)
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then
Dim keywordToken = memberDeclaration.GetMemberKeywordToken()
If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then
builder.Append(keywordToken.Text)
builder.Append(" "c)
End If
End If
Dim names = ArrayBuilder(Of String).GetInstance()
' containing type(s)
Dim parent = node.Parent
While TypeOf parent Is TypeBlockSyntax
names.Push(GetName(parent, options, containsGlobalKeyword:=False))
parent = parent.Parent
End While
If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then
' containing namespace(s) in source (if any)
Dim containsGlobalKeyword As Boolean = False
While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock
names.Push(GetName(parent, options, containsGlobalKeyword))
parent = parent.Parent
End While
' root namespace (if any)
If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then
builder.Append(rootNamespace)
builder.Append(s_dotToken)
End If
End If
While Not names.IsEmpty()
Dim name = names.Pop()
If name IsNot Nothing Then
builder.Append(name)
builder.Append(s_dotToken)
End If
End While
names.Free()
' name (include generic type parameters)
builder.Append(GetName(node, options, containsGlobalKeyword:=False))
' parameter list (if any)
If (options And DisplayNameOptions.IncludeParameters) <> 0 Then
builder.Append(memberDeclaration.GetParameterList())
End If
' As clause (if any)
If (options And DisplayNameOptions.IncludeType) <> 0 Then
Dim asClause = memberDeclaration.GetAsClause()
If asClause IsNot Nothing Then
builder.Append(" "c)
builder.Append(asClause)
End If
End If
Return pooled.ToStringAndFree()
End Function
Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String
Const missingTokenPlaceholder As String = "?"
Select Case node.Kind()
Case SyntaxKind.CompilationUnit
Return Nothing
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier
Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text)
Case SyntaxKind.IncompleteMember
Return missingTokenPlaceholder
Case SyntaxKind.NamespaceBlock
Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name
If nameSyntax.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return Nothing
Else
Return GetName(nameSyntax, options, containsGlobalKeyword)
End If
Case SyntaxKind.QualifiedName
Dim qualified = CType(node, QualifiedNameSyntax)
If qualified.Left.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified
Else
Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword)
End If
End Select
Dim name As String = Nothing
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If memberDeclaration IsNot Nothing Then
Dim nameToken = memberDeclaration.GetNameToken()
If nameToken <> Nothing Then
name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text)
If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
builder.Append(name)
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList())
name = pooled.ToStringAndFree()
End If
End If
End If
Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString())
Return name
End Function
Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax)
If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then
builder.Append("(Of ")
builder.Append(typeParameterList.Parameters(0).Identifier.Text)
For i = 1 To typeParameterList.Parameters.Count - 1
builder.Append(", ")
builder.Append(typeParameterList.Parameters(i).Identifier.Text)
Next
builder.Append(")"c)
End If
End Sub
Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean)
Debug.Assert(topLevel OrElse methodLevel)
For Each member In node.GetMembers()
If IsTopLevelNodeWithMembers(member) Then
If topLevel Then
list.Add(member)
End If
AppendMembers(member, list, topLevel, methodLevel)
Continue For
End If
If methodLevel AndAlso IsMethodLevelMember(member) Then
list.Add(member)
End If
Next
End Sub
Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent
Dim node = token.Parent
While node IsNot Nothing
Dim parent = node.Parent
' If this node is on the left side of a member access expression, don't ascend
' further or we'll end up binding to something else.
Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
If memberAccess.Expression Is node Then
Exit While
End If
End If
' If this node is on the left side of a qualified name, don't ascend
' further or we'll end up binding to something else.
Dim qualifiedName = TryCast(parent, QualifiedNameSyntax)
If qualifiedName IsNot Nothing Then
If qualifiedName.Left Is node Then
Exit While
End If
End If
' If this node is the type of an object creation expression, return the
' object creation expression.
Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax)
If objectCreation IsNot Nothing Then
If objectCreation.Type Is node Then
node = parent
Exit While
End If
End If
' The inside of an interpolated string is treated as its own token so we
' need to force navigation to the parent expression syntax.
If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then
node = parent
Exit While
End If
' If this node is not parented by a name, we're done.
Dim name = TryCast(parent, NameSyntax)
If name Is Nothing Then
Exit While
End If
node = parent
End While
Return node
End Function
Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors
Dim compilationUnit = TryCast(root, CompilationUnitSyntax)
If compilationUnit Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim constructors = New List(Of SyntaxNode)()
AppendConstructors(compilationUnit.Members, constructors, cancellationToken)
Return constructors
End Function
Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken)
For Each member As StatementSyntax In members
cancellationToken.ThrowIfCancellationRequested()
Dim constructor = TryCast(member, ConstructorBlockSyntax)
If constructor IsNot Nothing Then
constructors.Add(constructor)
Continue For
End If
Dim [namespace] = TryCast(member, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
AppendConstructors([namespace].Members, constructors, cancellationToken)
End If
Dim [class] = TryCast(member, ClassBlockSyntax)
If [class] IsNot Nothing Then
AppendConstructors([class].Members, constructors, cancellationToken)
End If
Dim [struct] = TryCast(member, StructureBlockSyntax)
If [struct] IsNot Nothing Then
AppendConstructors([struct].Members, constructors, cancellationToken)
End If
Next
End Sub
Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition
Dim trivia = tree.FindTriviaToLeft(position, cancellationToken)
If trivia.Kind = SyntaxKind.DisabledTextTrivia Then
Return trivia.FullSpan
End If
Return Nothing
End Function
Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument
If TryCast(argument, ArgumentSyntax)?.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End If
Return String.Empty
End Function
Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument
' All argument types are ArgumentSyntax in VB.
Return GetNameForArgument(argument)
End Function
Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot
Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot()
End Function
Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Right,
TryCast(node, MemberAccessExpressionSyntax)?.Name)
End Function
Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Left,
TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget))
End Function
Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier
Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing
End Function
Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement
End Function
Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement
End Function
Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement
End Function
Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment
Return TryCast(node, AssignmentStatementSyntax)?.Right
End Function
Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator
Return node.IsKind(SyntaxKind.InferredFieldInitializer)
End Function
Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression
Return False
End Function
Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression
Return False
End Function
Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString
Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value
End Function
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral
Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral
' VB does not have verbatim strings
Return False
End Function
Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression
Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList)
End Function
Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression
Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList)
End Function
Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList
Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments
Return If(arguments.HasValue, arguments.Value, Nothing)
End Function
Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression
Return DirectCast(node, InvocationExpressionSyntax).ArgumentList
End Function
Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression
Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList
End Function
Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine
Return node.ConvertToSingleLine(useElasticTrivia)
End Function
Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return node.IsKind(SyntaxKind.DocumentationCommentTrivia)
End Function
Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport
Return node.IsKind(SyntaxKind.ImportsStatement)
End Function
Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute
Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword)
End Function
Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute
Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword)
End Function
Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean
If node.IsKind(SyntaxKind.Attribute) Then
Dim attributeNode = CType(node, AttributeSyntax)
If attributeNode.Target IsNot Nothing Then
Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget)
End If
End If
Return False
End Function
Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration
' From the Visual Basic language spec:
' NamespaceMemberDeclaration :=
' NamespaceDeclaration |
' TypeDeclaration
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
' ClassMemberDeclaration ::=
' NonModuleDeclaration |
' EventMemberDeclaration |
' VariableMemberDeclaration |
' ConstantMemberDeclaration |
' MethodMemberDeclaration |
' PropertyMemberDeclaration |
' ConstructorMemberDeclaration |
' OperatorDeclaration
Select Case node.Kind()
' Because fields declarations can define multiple symbols "Public a, b As Integer"
' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
Case SyntaxKind.VariableDeclarator
If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then
Return True
End If
Return False
Case SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumStatement,
SyntaxKind.EnumBlock,
SyntaxKind.StructureStatement,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassStatement,
SyntaxKind.ClassBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EventStatement,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.FieldDeclaration,
SyntaxKind.SubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SubNewStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.OperatorBlock
Return True
End Select
Return False
End Function
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return True
End Select
Return False
End Function
Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer
Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer
End Function
Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType
Return DirectCast(node, ObjectCreationExpressionSyntax).Type
End Function
Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement
Return node.IsKind(SyntaxKind.SimpleAssignmentStatement)
End Function
Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement
' VB only has assignment statements, so this can just delegate to that helper
GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right)
End Sub
Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement
Dim assignment = DirectCast(statement, AssignmentStatementSyntax)
left = assignment.Left
operatorToken = assignment.OperatorToken
right = assignment.Right
End Sub
Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression
Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name
End Function
Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName
Return DirectCast(node, SimpleNameSyntax).Identifier
End Function
Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier
End Function
Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter
Return DirectCast(node, ParameterSyntax).Identifier.Identifier
End Function
Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return DirectCast(node, TypeStatementSyntax).Identifier
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier
End Select
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName
Return DirectCast(node, IdentifierNameSyntax).Identifier
End Function
Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement
' VB does not have local functions
Return False
End Function
Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement
Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators.
Contains(DirectCast(declarator, VariableDeclaratorSyntax))
End Function
Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(token1, token2)
End Function
Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(node1, node2)
End Function
Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node
End Function
Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node
End Function
Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression
Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).Expression
End Function
Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach
Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement
Return DirectCast(node, ExpressionStatementSyntax).Expression
End Function
Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression
Return TypeOf node Is BinaryExpressionSyntax
End Function
Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression
Return node.IsKind(SyntaxKind.TypeOfIsExpression)
End Function
Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression
Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax)
left = binaryExpression.Left
operatorToken = binaryExpression.OperatorToken
right = binaryExpression.Right
End Sub
Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression
Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax)
condition = conditionalExpression.Condition
whenTrue = conditionalExpression.WhenTrue
whenFalse = conditionalExpression.WhenFalse
End Sub
Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses
Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node)
End Function
Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression
Dim tupleExpr = DirectCast(node, TupleExpressionSyntax)
openParen = tupleExpr.OpenParenToken
arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax))
closeParen = tupleExpr.CloseParenToken
End Sub
Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression
Return DirectCast(node, UnaryExpressionSyntax).Operand
End Function
Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression
Return DirectCast(node, UnaryExpressionSyntax).OperatorToken
End Function
Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression
Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax)
expression = memberAccess.Expression
operatorToken = memberAccess.OperatorToken
name = memberAccess.Name
End Sub
Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement
Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax)
End Function
Public Overrides Function IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Overrides Function IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have multi-line comments.
Return False
End Function
Public Overrides Function IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Overrides Function IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have multi-line comments.
Return False
End Function
Public Overrides Function IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean
' VB does not have shebang directives.
Return False
End Function
Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean
Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind())
End Function
Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic
Return trivia.IsElastic()
End Function
Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective
Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes)
End Function
Public Function IsOnTypeHeader(
root As SyntaxNode,
position As Integer,
fullHeader As Boolean,
ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader
Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position)
If typeBlock Is Nothing Then
Return Nothing
End If
Dim typeStatement = typeBlock.BlockStatement
typeDeclaration = typeStatement
Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier)
If fullHeader Then
lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(),
If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(),
lastToken))
End If
Return IsOnHeader(root, position, typeBlock, lastToken)
End Function
Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader
Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position)
propertyDeclaration = node
If propertyDeclaration Is Nothing Then
Return False
End If
If node.AsClause IsNot Nothing Then
Return IsOnHeader(root, position, node, node.AsClause)
End If
Return IsOnHeader(root, position, node, node.Identifier)
End Function
Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader
Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position)
parameter = node
If parameter Is Nothing Then
Return False
End If
Return IsOnHeader(root, position, node, node)
End Function
Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader
Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position)
method = node
If method Is Nothing Then
Return False
End If
If node.HasReturnType() Then
Return IsOnHeader(root, position, method, node.GetReturnType())
End If
If node.ParameterList IsNot Nothing Then
Return IsOnHeader(root, position, method, node.ParameterList)
End If
Return IsOnHeader(root, position, node, node)
End Function
Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader
' No local functions in VisualBasic
Return False
End Function
Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader
Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position)
localDeclaration = node
If localDeclaration Is Nothing Then
Return False
End If
Dim initializersExpressions = node.Declarators.
Where(Function(d) d.Initializer IsNot Nothing).
SelectAsArray(Function(initialized) initialized.Initializer.Value)
Return IsOnHeader(root, position, node, node, initializersExpressions)
End Function
Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader
ifStatement = Nothing
Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position)
If multipleLineNode IsNot Nothing Then
ifStatement = multipleLineNode
Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement)
End If
Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position)
If singleLineNode IsNot Nothing Then
ifStatement = singleLineNode
Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition)
End If
Return False
End Function
Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader
whileStatement = Nothing
Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position)
If whileBlock IsNot Nothing Then
whileStatement = whileBlock
Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement)
End If
Return False
End Function
Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader
Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position)
foreachStatement = node
If foreachStatement Is Nothing Then
Return False
End If
Return IsOnHeader(root, position, node, node.ForEachStatement)
End Function
Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers
Dim token = root.FindToken(position)
Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax)
typeDeclaration = typeDecl
If typeDecl IsNot Nothing Then
Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End,
If(typeDecl.Inherits.LastOrDefault()?.Span.End,
typeDecl.BlockStatement.Span.End))
If position >= start AndAlso
position <= typeDecl.EndBlockStatement.Span.Start Then
Dim line = sourceText.Lines.GetLineFromPosition(position)
If Not line.IsEmptyOrWhitespace() Then
Return False
End If
Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position))
If member Is Nothing Then
' There are no members, Or we're after the last member.
Return True
Else
' We're within a member. Make sure we're in the leading whitespace of
' the member.
If position < member.SpanStart Then
For Each trivia In member.GetLeadingTrivia()
If Not trivia.IsWhitespaceOrEndOfLine() Then
Return False
End If
If trivia.FullSpan.Contains(position) Then
Return True
End If
Next
End If
End If
End If
End If
Return False
End Function
Private Function ISyntaxFacts_GetFileBanner(root As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner
Return GetFileBanner(root)
End Function
Private Function ISyntaxFacts_GetFileBanner(firstToken As SyntaxToken) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetFileBanner
Return GetFileBanner(firstToken)
End Function
Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean
Return token.ContainsInterleavedDirective(span, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(node, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(nodes, cancellationToken)
End Function
Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia
Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia
End Function
Private Function ISyntaxFacts_GetBannerText(documentationCommentTriviaSyntax As SyntaxNode, maxBannerLength As Integer, cancellationToken As CancellationToken) As String Implements ISyntaxFacts.GetBannerText
Return GetBannerText(documentationCommentTriviaSyntax, maxBannerLength, cancellationToken)
End Function
Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers
Return node.GetModifiers()
End Function
Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers
Return node.WithModifiers(modifiers)
End Function
Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression
Return TypeOf node Is LiteralExpressionSyntax
End Function
Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement
Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators
End Function
Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Initializer
End Function
Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type
End Function
Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause
Return DirectCast(node, EqualsValueSyntax).Value
End Function
Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock
' VB has no equivalent of curly braces.
Return False
End Function
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock
Return node.IsExecutableBlock()
End Function
Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements
Return node.GetExecutableBlockStatements()
End Function
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock
Return nodes.FindInnermostCommonExecutableBlock()
End Function
Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer
Return IsExecutableBlock(node)
End Function
Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements
Return GetExecutableBlockStatements(node)
End Function
Private Function ISyntaxFacts_GetLeadingBlankLines(node As SyntaxNode) As ImmutableArray(Of SyntaxTrivia) Implements ISyntaxFacts.GetLeadingBlankLines
Return MyBase.GetLeadingBlankLines(node)
End Function
Private Function ISyntaxFacts_GetNodeWithoutLeadingBlankLines(Of TSyntaxNode As SyntaxNode)(node As TSyntaxNode) As TSyntaxNode Implements ISyntaxFacts.GetNodeWithoutLeadingBlankLines
Return MyBase.GetNodeWithoutLeadingBlankLines(node)
End Function
Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression
Return node.Kind = SyntaxKind.CTypeExpression
End Function
Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression
Return node.Kind = SyntaxKind.DirectCastExpression
End Function
Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression
Dim cast = DirectCast(node, DirectCastExpressionSyntax)
type = cast.Type
expression = cast.Expression
End Sub
Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation
Throw New NotImplementedException()
End Function
Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride
If token.Kind() = SyntaxKind.OverridesKeyword Then
Dim parent = token.Parent
Select Case parent.Kind()
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(parent, MethodStatementSyntax)
Return method.Identifier
Case SyntaxKind.PropertyStatement
Dim [property] = DirectCast(parent, PropertyStatementSyntax)
Return [property].Identifier
End Select
End If
Return Nothing
End Function
Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective
Return MyBase.SpansPreprocessorDirective(nodes)
End Function
Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean
Return MyBase.SpansPreprocessorDirective(tokens)
End Function
Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression
Dim invocation = DirectCast(node, InvocationExpressionSyntax)
expression = invocation.Expression
argumentList = invocation.ArgumentList
End Sub
Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression
' Does not exist in VB.
Return False
End Function
Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists
Return node.GetAttributeLists()
End Function
Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective
Dim importStatement = TryCast(node, ImportsStatementSyntax)
If (importStatement IsNot Nothing) Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Return True
End If
End If
Next
End If
Return False
End Function
Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax
Dim xmlElement = TryCast(node, XmlElementSyntax)
If xmlElement IsNot Nothing Then
Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax)
Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName
End If
Return False
End Function
Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax
Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax)
If documentationCommentTrivia IsNot Nothing Then
Return documentationCommentTrivia.Content
End If
Return Nothing
End Function
Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility
Select Case declaration.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.ClassStatement,
SyntaxKind.StructureBlock,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.EnumBlock,
SyntaxKind.EnumStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.EventBlock,
SyntaxKind.EventStatement,
SyntaxKind.GetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.RaiseEventAccessorStatement
Return True
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubNewStatement
' Shared constructor cannot have modifiers in VB.
' Module constructors are implicitly Shared and can't have accessibility modifier.
Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso
Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock)
Case SyntaxKind.ModifiedIdentifier
Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator),
CanHaveAccessibility(declaration.Parent),
False)
Case SyntaxKind.VariableDeclarator
Return If(IsChildOfVariableDeclaration(declaration),
CanHaveAccessibility(declaration.Parent),
False)
Case Else
Return False
End Select
End Function
Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind)
End Function
Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean
Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement)
End Function
Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility
If Not CanHaveAccessibility(declaration) Then
Return Accessibility.NotApplicable
End If
Dim tokens = GetModifierTokens(declaration)
Dim acc As Accessibility
Dim mods As DeclarationModifiers
Dim isDefault As Boolean
GetAccessibilityAndModifiers(tokens, acc, mods, isDefault)
Return acc
End Function
Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens
Select Case declaration.Kind
Case SyntaxKind.ClassBlock
Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.ClassStatement
Return DirectCast(declaration, ClassStatementSyntax).Modifiers
Case SyntaxKind.StructureBlock
Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.StructureStatement
Return DirectCast(declaration, StructureStatementSyntax).Modifiers
Case SyntaxKind.InterfaceBlock
Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.InterfaceStatement
Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers
Case SyntaxKind.EnumBlock
Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers
Case SyntaxKind.EnumStatement
Return DirectCast(declaration, EnumStatementSyntax).Modifiers
Case SyntaxKind.ModuleBlock
Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers
Case SyntaxKind.ModuleStatement
Return DirectCast(declaration, ModuleStatementSyntax).Modifiers
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DirectCast(declaration, DelegateStatementSyntax).Modifiers
Case SyntaxKind.FieldDeclaration
Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.ConstructorBlock
Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
Return DirectCast(declaration, MethodStatementSyntax).Modifiers
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers
Case SyntaxKind.SubNewStatement
Return DirectCast(declaration, SubNewStatementSyntax).Modifiers
Case SyntaxKind.PropertyBlock
Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers
Case SyntaxKind.PropertyStatement
Return DirectCast(declaration, PropertyStatementSyntax).Modifiers
Case SyntaxKind.OperatorBlock
Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers
Case SyntaxKind.OperatorStatement
Return DirectCast(declaration, OperatorStatementSyntax).Modifiers
Case SyntaxKind.EventBlock
Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers
Case SyntaxKind.EventStatement
Return DirectCast(declaration, EventStatementSyntax).Modifiers
Case SyntaxKind.ModifiedIdentifier
If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then
Return GetModifierTokens(declaration.Parent)
End If
Case SyntaxKind.LocalDeclarationStatement
Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers
Case SyntaxKind.VariableDeclarator
If IsChildOfVariableDeclaration(declaration) Then
Return GetModifierTokens(declaration.Parent)
End If
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement)
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return DirectCast(declaration, AccessorStatementSyntax).Modifiers
Case Else
Return Nothing
End Select
End Function
Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers
accessibility = Accessibility.NotApplicable
modifiers = DeclarationModifiers.None
isDefault = False
For Each token In modifierTokens
Select Case token.Kind
Case SyntaxKind.DefaultKeyword
isDefault = True
Case SyntaxKind.PublicKeyword
accessibility = Accessibility.Public
Case SyntaxKind.PrivateKeyword
If accessibility = Accessibility.Protected Then
accessibility = Accessibility.ProtectedAndFriend
Else
accessibility = Accessibility.Private
End If
Case SyntaxKind.FriendKeyword
If accessibility = Accessibility.Protected Then
accessibility = Accessibility.ProtectedOrFriend
Else
accessibility = Accessibility.Friend
End If
Case SyntaxKind.ProtectedKeyword
If accessibility = Accessibility.Friend Then
accessibility = Accessibility.ProtectedOrFriend
ElseIf accessibility = Accessibility.Private Then
accessibility = Accessibility.ProtectedAndFriend
Else
accessibility = Accessibility.Protected
End If
Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword
modifiers = modifiers Or DeclarationModifiers.Abstract
Case SyntaxKind.ShadowsKeyword
modifiers = modifiers Or DeclarationModifiers.[New]
Case SyntaxKind.OverridesKeyword
modifiers = modifiers Or DeclarationModifiers.Override
Case SyntaxKind.OverridableKeyword
modifiers = modifiers Or DeclarationModifiers.Virtual
Case SyntaxKind.SharedKeyword
modifiers = modifiers Or DeclarationModifiers.Static
Case SyntaxKind.AsyncKeyword
modifiers = modifiers Or DeclarationModifiers.Async
Case SyntaxKind.ConstKeyword
modifiers = modifiers Or DeclarationModifiers.Const
Case SyntaxKind.ReadOnlyKeyword
modifiers = modifiers Or DeclarationModifiers.ReadOnly
Case SyntaxKind.WriteOnlyKeyword
modifiers = modifiers Or DeclarationModifiers.WriteOnly
Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword
modifiers = modifiers Or DeclarationModifiers.Sealed
Case SyntaxKind.WithEventsKeyword
modifiers = modifiers Or DeclarationModifiers.WithEvents
Case SyntaxKind.PartialKeyword
modifiers = modifiers Or DeclarationModifiers.Partial
End Select
Next
End Sub
Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind
Select Case declaration.Kind
Case SyntaxKind.CompilationUnit
Return DeclarationKind.CompilationUnit
Case SyntaxKind.NamespaceBlock
Return DeclarationKind.Namespace
Case SyntaxKind.ImportsStatement
Return DeclarationKind.NamespaceImport
Case SyntaxKind.ClassBlock
Return DeclarationKind.Class
Case SyntaxKind.StructureBlock
Return DeclarationKind.Struct
Case SyntaxKind.InterfaceBlock
Return DeclarationKind.Interface
Case SyntaxKind.EnumBlock
Return DeclarationKind.Enum
Case SyntaxKind.EnumMemberDeclaration
Return DeclarationKind.EnumMember
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return DeclarationKind.Delegate
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock
Return DeclarationKind.Method
Case SyntaxKind.FunctionStatement
If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then
Return DeclarationKind.Method
End If
Case SyntaxKind.SubStatement
If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then
Return DeclarationKind.Method
End If
Case SyntaxKind.ConstructorBlock
Return DeclarationKind.Constructor
Case SyntaxKind.PropertyBlock
If IsIndexer(declaration) Then
Return DeclarationKind.Indexer
Else
Return DeclarationKind.Property
End If
Case SyntaxKind.PropertyStatement
If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then
If IsIndexer(declaration) Then
Return DeclarationKind.Indexer
Else
Return DeclarationKind.Property
End If
End If
Case SyntaxKind.OperatorBlock
Return DeclarationKind.Operator
Case SyntaxKind.OperatorStatement
If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then
Return DeclarationKind.Operator
End If
Case SyntaxKind.EventBlock
Return DeclarationKind.CustomEvent
Case SyntaxKind.EventStatement
If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then
Return DeclarationKind.Event
End If
Case SyntaxKind.Parameter
Return DeclarationKind.Parameter
Case SyntaxKind.FieldDeclaration
Return DeclarationKind.Field
Case SyntaxKind.LocalDeclarationStatement
If GetDeclarationCount(declaration) = 1 Then
Return DeclarationKind.Variable
End If
Case SyntaxKind.ModifiedIdentifier
If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then
If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then
Return DeclarationKind.Field
ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then
Return DeclarationKind.Variable
End If
End If
Case SyntaxKind.Attribute
Dim list = TryCast(declaration.Parent, AttributeListSyntax)
If list Is Nothing OrElse list.Attributes.Count > 1 Then
Return DeclarationKind.Attribute
End If
Case SyntaxKind.AttributeList
Dim list = DirectCast(declaration, AttributeListSyntax)
If list.Attributes.Count = 1 Then
Return DeclarationKind.Attribute
End If
Case SyntaxKind.GetAccessorBlock
Return DeclarationKind.GetAccessor
Case SyntaxKind.SetAccessorBlock
Return DeclarationKind.SetAccessor
Case SyntaxKind.AddHandlerAccessorBlock
Return DeclarationKind.AddAccessor
Case SyntaxKind.RemoveHandlerAccessorBlock
Return DeclarationKind.RemoveAccessor
Case SyntaxKind.RaiseEventAccessorBlock
Return DeclarationKind.RaiseAccessor
End Select
Return DeclarationKind.None
End Function
Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer
Dim count As Integer = 0
For i = 0 To nodes.Count - 1
count = count + GetDeclarationCount(nodes(i))
Next
Return count
End Function
Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators)
Case SyntaxKind.LocalDeclarationStatement
Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators)
Case SyntaxKind.VariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Count
Case SyntaxKind.AttributesStatement
Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists)
Case SyntaxKind.AttributeList
Return DirectCast(node, AttributeListSyntax).Attributes.Count
Case SyntaxKind.ImportsStatement
Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count
End Select
Return 1
End Function
Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.PropertyBlock
Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement
Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword)
Case SyntaxKind.PropertyStatement
If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then
Dim p = DirectCast(declaration, PropertyStatementSyntax)
Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword)
End If
End Select
Return False
End Function
Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation
Return False
End Function
Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern
Return False
End Function
Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression
Return False
End Function
Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern
Return False
End Function
Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern
Return False
End Function
Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern
Return False
End Function
Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern
Return False
End Function
Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern
Return False
End Function
Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern
Return False
End Function
Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern
Return False
End Function
Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern
Return False
End Function
Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern
Return False
End Function
Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern
Return False
End Function
Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern
Return False
End Function
Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern
Return False
End Function
Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression
Throw ExceptionUtilities.Unreachable
End Sub
Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern
Throw ExceptionUtilities.Unreachable
End Function
Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern
Throw New NotImplementedException()
End Sub
Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern
Throw New NotImplementedException()
End Sub
Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern
Throw New NotImplementedException()
End Function
Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression
' ThrowExpression doesn't exist in VB
Throw New NotImplementedException()
End Function
Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement
Return node.IsKind(SyntaxKind.ThrowStatement)
End Function
Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction
Return False
End Function
Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression
Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax)
stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken
contents = interpolatedStringExpressionSyntax.Contents
stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken
End Sub
Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression
Return False
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Features/Core/Portable/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors
{
/// <summary>
/// This <see cref="CodeRefactoringProvider"/> gives users a way to generate constructors for
/// a derived type that delegate to a base type. For all accessible constructors in the base
/// type, the user will be offered to create a constructor in the derived type with the same
/// signature if they don't already have one. This way, a user can override a type and easily
/// create all the forwarding constructors.
///
/// Importantly, this type is not responsible for generating constructors when the user types
/// something like "new MyType(x, y, z)", nor is it responsible for generating constructors
/// for a type based on the fields/properties of that type. Both of those are handled by other
/// services.
/// </summary>
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared]
internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateDefaultConstructorsCodeRefactoringProvider()
{
}
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
// TODO: https://github.com/dotnet/roslyn/issues/5778
// Not supported in REPL for now.
if (document.Project.IsSubmission)
return;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var service = document.GetRequiredLanguageService<IGenerateDefaultConstructorsService>();
var actions = await service.GenerateDefaultConstructorsAsync(
document, textSpan, forRefactoring: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors
{
/// <summary>
/// This <see cref="CodeRefactoringProvider"/> gives users a way to generate constructors for
/// a derived type that delegate to a base type. For all accessible constructors in the base
/// type, the user will be offered to create a constructor in the derived type with the same
/// signature if they don't already have one. This way, a user can override a type and easily
/// create all the forwarding constructors.
///
/// Importantly, this type is not responsible for generating constructors when the user types
/// something like "new MyType(x, y, z)", nor is it responsible for generating constructors
/// for a type based on the fields/properties of that type. Both of those are handled by other
/// services.
/// </summary>
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared]
internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateDefaultConstructorsCodeRefactoringProvider()
{
}
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
// TODO: https://github.com/dotnet/roslyn/issues/5778
// Not supported in REPL for now.
if (document.Project.IsSubmission)
return;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var service = document.GetRequiredLanguageService<IGenerateDefaultConstructorsService>();
var actions = await service.GenerateDefaultConstructorsAsync(
document, textSpan, forRefactoring: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.ExecutableCodeBlockAnalyzerActions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalyzerDriver<TLanguageKindEnum> : AnalyzerDriver where TLanguageKindEnum : struct
{
[StructLayout(LayoutKind.Auto)]
private struct ExecutableCodeBlockAnalyzerActions
{
public DiagnosticAnalyzer Analyzer;
public ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> CodeBlockStartActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions;
public ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalyzerDriver<TLanguageKindEnum> : AnalyzerDriver where TLanguageKindEnum : struct
{
[StructLayout(LayoutKind.Auto)]
private struct ExecutableCodeBlockAnalyzerActions
{
public DiagnosticAnalyzer Analyzer;
public ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> CodeBlockStartActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions;
public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions;
public ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions;
public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions;
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/ImplementedByGraphQuery.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed class ImplementedByGraphQuery : IGraphQuery
{
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.GraphQuery_ImplementedBy, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken))
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
foreach (var node in context.InputNodes)
{
var symbol = graphBuilder.GetSymbol(node, cancellationToken);
if (symbol is INamedTypeSymbol ||
symbol is IMethodSymbol ||
symbol is IPropertySymbol ||
symbol is IEventSymbol)
{
var implementations = await SymbolFinder.FindImplementationsAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
var symbolNode = await graphBuilder.AddNodeAsync(
implementation, relatedNode: node, cancellationToken).ConfigureAwait(false);
graphBuilder.AddLink(
symbolNode, CodeLinkCategories.Implements, node, cancellationToken);
}
}
}
return graphBuilder;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed class ImplementedByGraphQuery : IGraphQuery
{
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.GraphQuery_ImplementedBy, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken))
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
foreach (var node in context.InputNodes)
{
var symbol = graphBuilder.GetSymbol(node, cancellationToken);
if (symbol is INamedTypeSymbol ||
symbol is IMethodSymbol ||
symbol is IPropertySymbol ||
symbol is IEventSymbol)
{
var implementations = await SymbolFinder.FindImplementationsAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
var symbolNode = await graphBuilder.AddNodeAsync(
implementation, relatedNode: node, cancellationToken).ConfigureAwait(false);
graphBuilder.AddLink(
symbolNode, CodeLinkCategories.Implements, node, cancellationToken);
}
}
}
return graphBuilder;
}
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/VisualStudio/CSharp/Impl/Utilities/BlankLineInGeneratedMethodFormattingRule.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Formatting.Rules;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Utilities
{
internal sealed class BlankLineInGeneratedMethodFormattingRule : AbstractFormattingRule
{
public static readonly BlankLineInGeneratedMethodFormattingRule Instance = new();
private BlankLineInGeneratedMethodFormattingRule()
{
}
public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
// case: insert blank line in empty method body.
if (previousToken.Kind() == SyntaxKind.OpenBraceToken &&
currentToken.Kind() == SyntaxKind.CloseBraceToken)
{
if (currentToken.Parent.Kind() == SyntaxKind.Block &&
currentToken.Parent.Parent.Kind() == SyntaxKind.MethodDeclaration)
{
return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines);
}
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Formatting.Rules;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Utilities
{
internal sealed class BlankLineInGeneratedMethodFormattingRule : AbstractFormattingRule
{
public static readonly BlankLineInGeneratedMethodFormattingRule Instance = new();
private BlankLineInGeneratedMethodFormattingRule()
{
}
public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
// case: insert blank line in empty method body.
if (previousToken.Kind() == SyntaxKind.OpenBraceToken &&
currentToken.Kind() == SyntaxKind.CloseBraceToken)
{
if (currentToken.Parent.Kind() == SyntaxKind.Block &&
currentToken.Parent.Parent.Kind() == SyntaxKind.MethodDeclaration)
{
return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines);
}
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/Options/IOption.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis.Options
{
public interface IOption
{
string Feature { get; }
string Name { get; }
Type Type { get; }
object? DefaultValue { get; }
bool IsPerLanguage { get; }
ImmutableArray<OptionStorageLocation> StorageLocations { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Options
{
public interface IOption
{
string Feature { get; }
string Name { get; }
Type Type { get; }
object? DefaultValue { get; }
bool IsPerLanguage { get; }
ImmutableArray<OptionStorageLocation> StorageLocations { get; }
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/AsyncAwait.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports System.Collections.ObjectModel
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class AsyncAwait
Inherits BasicTestBase
<Fact()>
Public Sub Basic()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Threading.Tasks
Module Program
Function Test1() As Task(Of Integer)
Return Nothing
End Function
Async Sub Test2()
Await Test1()
Dim x As Integer = Await Test1()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact, WorkItem(744146, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/744146")>
Public Sub DefaultAwaitExpressionInfo()
Dim awaitInfo As AwaitExpressionInfo = Nothing
Assert.Null(awaitInfo.GetAwaiterMethod)
Assert.Null(awaitInfo.IsCompletedProperty)
Assert.Null(awaitInfo.GetResultMethod)
End Sub
<Fact()>
Public Sub AwaitableType01()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Equal("ReadOnly Property MyTaskAwaiter(Of System.Int32).IsCompleted As System.Boolean", awaitInfo.IsCompletedProperty.ToTestDisplayString())
Assert.Equal("Function MyTaskAwaiter(Of System.Int32).GetResult() As System.Int32", awaitInfo.GetResultMethod.ToTestDisplayString())
End Sub
<Fact()>
Public Sub AwaitableType02()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter(Optional x As Integer = 0) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Null(awaitInfo.GetAwaiterMethod)
Assert.Null(awaitInfo.IsCompletedProperty)
Assert.Null(awaitInfo.GetResultMethod)
End Sub
<Fact()>
Public Sub AwaitableType03()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Sub GetAwaiter()
End Sub
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType04()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As Object
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType05()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
ReadOnly Property GetAwaiter As MyTaskAwaiter(Of T)
Get
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Get
End Property
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = (New MyTask(Of Integer)).GetAwaiter
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType06()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Protected Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType07()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter(x As Integer) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType08()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType09()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Shared Function GetAwaiter() As MyTaskAwaiter(Of T)
Return Nothing
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType10()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return Nothing
End Function
End Class
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30002: Type 'MyTaskAwaiter' is not defined.
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'MyTaskAwaiter' is not defined.
Function GetAwaiter() As MyTaskAwaiter(Of T)
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType11()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
<Extension>
Function GetAwaiter(Of T)(this As MyTask(Of T)) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = this}
End Function
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact()>
Public Sub AwaitableType12()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
<Extension>
Function GetAwaiter(Of T)(this As MyTask(Of T), Optional x As Integer = 0) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = this}
End Function
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType13()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim o As Object = New MyTask(Of Integer)
Dim x = Await o
Await o
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom))
AssertTheseDiagnostics(compilation,
<expected>
BC42017: Late bound resolution; runtime errors could occur.
Dim x = Await o
~~~~~~~
BC42017: Late bound resolution; runtime errors could occur.
Await o
~~~~~~~
</expected>)
compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.On))
AssertTheseDiagnostics(compilation,
<expected>
BC30574: Option Strict On disallows late binding.
Dim x = Await o
~~~~~~~
BC30574: Option Strict On disallows late binding.
Await o
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType14()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Module Program
Sub Test1()
End Sub
Async Sub Test2()
Dim x As Integer = Await Test1()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30491: Expression does not produce a value.
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Dim x As Integer = Await Test1()
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType15()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30456: 'IsCompleted' is not a member of 'MyTaskAwaiter(Of Integer)'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Null(awaitInfo.IsCompletedProperty)
Assert.Equal("Function MyTaskAwaiter(Of System.Int32).GetResult() As System.Int32", awaitInfo.GetResultMethod.ToTestDisplayString())
End Sub
<Fact()>
Public Sub AwaitableType16()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Private ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' BC30390: 'MyTaskAwaiter(Of T).Private ReadOnly Property IsCompleted As Boolean' is not accessible in this context because it is 'Private'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType17()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Function IsCompleted() As Boolean
Throw New NotImplementedException()
End Function
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = (New MyTask(Of Integer)).GetAwaiter().IsCompleted
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType18()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Object
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType19()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted(x As Integer) As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property IsCompleted(x As Integer) As Boolean'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType20()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted(Optional x As Integer = 0) As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = (New MyTask(Of Integer)).GetAwaiter().IsCompleted
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType21()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Shared ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = MyTaskAwaiter(Of Integer).IsCompleted
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' warning BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType22()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As DoesntExist
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30002: Type 'DoesntExist' is not defined.
AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
ReadOnly Property IsCompleted() As DoesntExist
~~~~~~~~~~~
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType23()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30456: 'GetResult' is not a member of 'MyTaskAwaiter(Of Integer)'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Equal("ReadOnly Property MyTaskAwaiter(Of System.Int32).IsCompleted As System.Boolean", awaitInfo.IsCompletedProperty.ToTestDisplayString())
Assert.Null(awaitInfo.GetResultMethod)
End Sub
<Fact()>
Public Sub AwaitableType24()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Private Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30390: 'MyTaskAwaiter(Of T).Private Function GetResult() As T' is not accessible in this context because it is 'Private'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType25()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult(x As Integer) As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30455: Argument not specified for parameter 'x' of 'Public Function GetResult(x As Integer) As T'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType26()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult(Optional x As Integer = 0) As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType27()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Shared Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' warning BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType28()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
ReadOnly Property GetResult() As T
Get
Throw New NotImplementedException()
End Get
End Property
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim Y = (New MyTask(Of Integer)).GetAwaiter().GetResult
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType29()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
End Structure
Module Program
<Extension>
Function GetResult(Of t)(X As MyTaskAwaiter(Of t)) As t
Throw New NotImplementedException()
End Function
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim Y = (New MyTask(Of Integer)).GetAwaiter().GetResult
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType30()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As DoesntExist
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30002: Type 'DoesntExist' is not defined.
AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
Function GetResult() As DoesntExist
~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType31()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Sub GetResult()
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30491: Expression does not produce a value.
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType32()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37056: 'MyTaskAwaiter(Of Integer)' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'.
AssertTheseDiagnostics(compilation,
<expected>
BC37056: 'MyTaskAwaiter(Of Integer)' does not implement 'INotifyCompletion'.
Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Equal("ReadOnly Property MyTaskAwaiter(Of System.Int32).IsCompleted As System.Boolean", awaitInfo.IsCompletedProperty.ToTestDisplayString())
Assert.Equal("Function MyTaskAwaiter(Of System.Int32).GetResult() As System.Int32", awaitInfo.GetResultMethod.ToTestDisplayString())
End Sub
<Fact()>
Public Sub AwaitableType33()
Dim source =
<compilation name="MissingINotifyCompletion">
<file name="a.vb">
<![CDATA[
Imports System
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib, TestMetadata.Net40.MicrosoftVisualBasic}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC31091: Import of type 'INotifyCompletion' from assembly or module 'MissingINotifyCompletion.exe' failed.
Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType34()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Test0()
Await Task.Delay(1)
End Sub
Async Sub Test1()
Await Test0()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC37001: 'Test0' does not return a Task and cannot be awaited. Consider changing it to an Async Function.
Await Test0()
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType35()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
#Const defined = True
<System.Diagnostics.Conditional("defined")>
Sub GetResult()
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Async Sub Test1()
Await New MyTask(Of Integer)()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Await New MyTask(Of Integer)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaiterImplementsINotifyCompletion_Constraint()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.CompilerServices
Class Awaitable(Of T)
Friend Function GetAwaiter() As T
Return Nothing
End Function
End Class
Interface IA
ReadOnly Property IsCompleted As Boolean
Function GetResult() As Object
End Interface
Interface IB
Inherits IA, INotifyCompletion
End Interface
Class A
Friend ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
Friend Function GetResult() As Object
Return Nothing
End Function
End Class
Class B
Inherits A
Implements INotifyCompletion
Private Sub OnCompleted(a As System.Action) Implements INotifyCompletion.OnCompleted
End Sub
End Class
Module M
Async Sub F(Of T1 As IA, T2 As {IA, INotifyCompletion}, T3 As IB, T4 As {T1, INotifyCompletion}, T5 As T3, T6 As A, T7 As {A, INotifyCompletion}, T8 As B, T9 As {T6, INotifyCompletion}, T10 As T8)()
Await New Awaitable(Of T1)()
Await New Awaitable(Of T2)()
Await New Awaitable(Of T3)()
Await New Awaitable(Of T4)()
Await New Awaitable(Of T5)()
Await New Awaitable(Of T6)()
Await New Awaitable(Of T7)()
Await New Awaitable(Of T8)()
Await New Awaitable(Of T9)()
Await New Awaitable(Of T10)()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929})
compilation.AssertTheseDiagnostics(
<expected>
BC37056: 'T1' does not implement 'INotifyCompletion'.
Await New Awaitable(Of T1)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37056: 'T6' does not implement 'INotifyCompletion'.
Await New Awaitable(Of T6)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
''' <summary>
''' Should call ICriticalNotifyCompletion.UnsafeOnCompleted
''' if the awaiter type implements ICriticalNotifyCompletion.
''' </summary>
<Fact()>
Public Sub AwaiterImplementsICriticalNotifyCompletion_Constraint()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class Awaitable(Of T)
Friend Function GetAwaiter() As T
Return Nothing
End Function
End Class
Class A
Implements INotifyCompletion
Private Sub OnCompleted(a As Action) Implements INotifyCompletion.OnCompleted
End Sub
Friend ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
Friend Function GetResult() As Object
Return Nothing
End Function
End Class
Class B
Inherits A
Implements ICriticalNotifyCompletion
Private Sub UnsafeOnCompleted(a As Action) Implements ICriticalNotifyCompletion.UnsafeOnCompleted
End Sub
End Class
Module M
Async Sub F(Of T1 As A, T2 As {A, ICriticalNotifyCompletion}, T3 As B, T4 As T1, T5 As T2, T6 As {T1, ICriticalNotifyCompletion})()
Await New Awaitable(Of T1)()
Await New Awaitable(Of T2)()
Await New Awaitable(Of T3)()
Await New Awaitable(Of T4)()
Await New Awaitable(Of T5)()
Await New Awaitable(Of T6)()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929})
Dim verifier = CompileAndVerify(compilation)
Dim actualIL = verifier.VisualizeIL("M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6).MoveNext()")
Dim calls = actualIL.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries).Where(Function(s) s.Contains("OnCompleted")).ToArray()
Assert.Equal(calls.Length, 6)
Assert.Equal(calls(0), <![CDATA[ IL_0058: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted(Of SM$T1, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T1, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(1), <![CDATA[ IL_00c7: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T2, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T2, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(2), <![CDATA[ IL_0136: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T3, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T3, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(3), <![CDATA[ IL_01a7: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted(Of SM$T4, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T4, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(4), <![CDATA[ IL_0219: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T5, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T5, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(5), <![CDATA[ IL_028b: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T6, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T6, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
End Sub
<Fact()>
Public Sub Assignment()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Await (New MyTask(Of Integer))=1
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30205: End of statement expected.
AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
Await (New MyTask(Of Integer))=1
~
</expected>)
End Sub
<Fact()>
Public Sub AwaitNothing()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Module Program
Async Sub Test2()
Await Nothing
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36933: Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.
AssertTheseDiagnostics(compilation,
<expected>
BC36933: Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.
Await Nothing
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitInQuery()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Linq.Enumerable
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim y = From x In {1} Where x <> Await New MyTask(Of Integer)
Dim z = From x In {Await New MyTask(Of Integer)} Where x <> 0
Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36929: 'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36929: 'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.
Dim y = From x In {1} Where x <> Await New MyTask(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub MisplacedAsyncModifier()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Public Module Program1
Sub Main()
End Sub
Async Class Test1
End Class
Async Structure Test2
End Structure
Async Enum Test3
X
End Enum
Async Interface Test4
End Interface
Class Test5
Private Async Test6 As Object
Async Property Test7 As Object
Async Event Test8(x As Object)
Async Sub Test9(ByRef x As Integer)
Await Task.Delay(x)
Dim Async Test10 As Object
End Sub
End Class
Async Delegate Sub Test11()
Async Declare Sub Test12 Lib "ddd" ()
Interface I1
Async Sub Test13()
End Interface
Enum E1
Async Test14
End Enum
Structure S1
Async Sub Test15()
Await Task.Delay(1)
Async Test16 As Object
End Sub
End Structure
Async Iterator Function Test17() As Object
End Function
End Module
Async Module Program2
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30461: Classes cannot be declared 'Async'.
Async Class Test1
~~~~~
BC30395: 'Async' is not valid on a Structure declaration.
Async Structure Test2
~~~~~
BC30396: 'Async' is not valid on an Enum declaration.
Async Enum Test3
~~~~~
BC30397: 'Async' is not valid on an Interface declaration.
Async Interface Test4
~~~~~
BC30235: 'Async' is not valid on a member variable declaration.
Private Async Test6 As Object
~~~~~
BC30639: Properties cannot be declared 'Async'.
Async Property Test7 As Object
~~~~~
BC30243: 'Async' is not valid on an event declaration.
Async Event Test8(x As Object)
~~~~~
BC36926: Async methods cannot have ByRef parameters.
Async Sub Test9(ByRef x As Integer)
~~~~~~~~~~~~~~~~~~
BC30247: 'Async' is not valid on a local variable declaration.
Dim Async Test10 As Object
~~~~~
BC42024: Unused local variable: 'Test10'.
Dim Async Test10 As Object
~~~~~~
BC30385: 'Async' is not valid on a Delegate declaration.
Async Delegate Sub Test11()
~~~~~
BC30244: 'Async' is not valid on a Declare.
Async Declare Sub Test12 Lib "ddd" ()
~~~~~
BC30270: 'Async' is not valid on an interface method declaration.
Async Sub Test13()
~~~~~
BC30205: End of statement expected.
Async Test14
~~~~~~
BC30247: 'Async' is not valid on a local variable declaration.
Async Test16 As Object
~~~~~
BC42024: Unused local variable: 'Test16'.
Async Test16 As Object
~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Async Iterator Function Test17() As Object
~~~~~
BC31052: Modules cannot be declared 'Async'.
Async Module Program2
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ReferToReturnVariable()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Test0()
Dim x = Test0
Await Task.Delay(1)
End Sub
Async Function Test1() As Task
Dim x = Test1
Await Task.Delay(1)
End Function
Async Function Test2() As Task(Of Integer)
Dim x = Test2
Await Task.Delay(1)
End Function
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Dim x = Test0
~~~~~
BC36946: The implicit return variable of an Iterator or Async method cannot be accessed.
Dim x = Test1
~~~~~
BC36946: The implicit return variable of an Iterator or Async method cannot be accessed.
Dim x = Test2
~~~~~
BC42105: Function 'Test2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ReturnStatements()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Test0()
Await Task.Delay(1)
Dim x As Integer = 1
If x = 3 Then
Return Nothing ' 0
Else
Return
End If
End Sub
Async Function Test1() As Task
Await Task.Delay(1)
Dim x As Integer = 1
If x = 3 Then
Return Nothing ' 1
ElseIf x = 2 Then
Return ' 1
Else
Return Task.Delay(1)
End If
End Function
Async Function Test2() As Task
Await Task.Delay(2)
End Function
Async Function Test3() As Task(Of Integer)
Await Task.Delay(3)
Return 3
End Function
Async Function Test4() As Task(Of Integer)
Await Task.Delay(3)
Return Test3()
End Function
Async Function Test5() As Object
Await Task.Delay(3)
Return Nothing ' 5
End Function
Async Function Test6() As Task(Of Integer)
Await Task.Delay(6)
Return New Guid()
End Function
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
Return Nothing ' 0
~~~~~~~~~~~~~~
BC36952: 'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.
Return Nothing ' 1
~~~~~~~~~~~~~~
BC36952: 'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.
Return Task.Delay(1)
~~~~~~~~~~~~~~~~~~~~
BC37055: Since this is an async method, the return expression must be of type 'Integer' rather than 'Task(Of Integer)'.
Return Test3()
~~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Async Function Test5() As Object
~~~~~~
BC30311: Value of type 'Guid' cannot be converted to 'Integer'.
Return New Guid()
~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub Lambdas()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Delegate Function D1() As Object
Delegate Sub D2(ByRef x As Integer)
Sub Main()
Dim x00 = Async Sub()
Await Task.Delay(0)
End Sub
Dim x01 = Async Iterator Function() As Object
Return Nothing
End Function ' 1
Dim x02 = Async Function() As Object
Await Task.Delay(3)
Return Nothing ' 5
End Function '2
Dim x03 As D1 = Async Function()
Await Task.Delay(3)
Return Nothing ' 5
End Function '3
Dim x04 = Async Sub(ByRef x As Integer)
Await Task.Delay(0)
End Sub
Dim x05 As D2 = Async Sub(x)
Await Task.Delay(0)
End Sub
Dim x06 As D2 = Async Sub(ByRef x)
Await Task.Delay(0)
End Sub
Dim x07 = Async Iterator Function() As Object
Await Task.Delay(0)
Return Nothing
End Function ' 4
Dim x08 = Sub()
Await Task.Delay(0) ' x08
End Sub
Dim x09 = Async Sub()
Await Task.Delay(0)
Dim x10 = Sub()
Await Task.Delay(0) ' x10
End Sub
End Sub
Dim x11 = Async Function()
Await Task.Delay(0)
Dim x As Integer = 0
If x = 0 Then
Return CByte(1)
Else
Return 1
End If
End Function ' 5
Dim x12 As Func(Of Task(Of Integer)) = x11
Dim x13 As Func(Of Task(Of Byte)) = x11
Dim x14 = Async Function() Await New Task(Of Byte)(Function() 1)
x12 = x14
x13 = x14
Dim x15 = Async Function()
Await Task.Delay(0)
End Function ' 6
Dim x16 As Func(Of Task) = x15
Dim x17 As Func(Of Integer) = x15
Dim x18 = Async Function()
Await Task.Delay(0)
Return
End Function ' 7
x16 = x18
x17 = x18
Dim x19 = Async Function()
Await Task.Delay(0)
Dim x As Integer = 0
If x = 0 Then
Return ' x19
Else
Return 1
End If
End Function ' 8
Dim x20 As Func(Of Object) = Async Function()
Await Task.Delay(0)
End Function ' 9
Dim x21 As Func(Of Object) = Async Function() Await New Task(Of Byte)(Function() 1)
Dim x22 As Func(Of Object) = Async Function()
Await Task.Delay(0)
Return 1
End Function ' 10
'Dim x23 As Action = Async Function() ' Expected BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
' Await Task.Delay(0)
' End Function ' 11
'Dim x24 As Action = Async Function() ' Expected BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
' Await Task.Delay(0)
' Return 1
' End Function ' 12
Dim x25 As Func(Of Task) = Async Function()
Await Task.Delay(0)
End Function ' 12
Dim x26 As Func(Of Task) = Async Function() Await New Task(Of Byte)(Function() 1)
Dim x27 As Func(Of Task) = Async Function()
Await Task.Delay(0)
Return 1
End Function ' 13
'Dim x28 = Async Overridable Sub()
' Await Task.Delay(0)
' End Sub
'Dim x29 = Async Iterator Overridable Sub()
' Await Task.Delay(0)
' End Sub
Dim x30 = Overridable Sub()
End Sub ' x30
'Dim x31 = Async Main
End Sub ' Main
Async Sub Test()
Await Task.Delay(0)
Dim x04 = Sub(ByRef x As Integer)
End Sub
End Sub
Sub Test2()
Dim x40 = Async Iterator Function() 1
Dim x41 = Async Iterator Function()
Yield 1
End Function ' 14
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x01 = Async Iterator Function() As Object
~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x02 = Async Function() As Object
~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x03 As D1 = Async Function()
~~~~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim x04 = Async Sub(ByRef x As Integer)
~~~~~~~~~~~~~~~~~~
BC36670: Nested sub does not have a signature that is compatible with delegate 'Delegate Sub Program.D2(ByRef x As Integer)'.
Dim x05 As D2 = Async Sub(x)
~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim x06 As D2 = Async Sub(ByRef x)
~~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x07 = Async Iterator Function() As Object
~~~~~
BC37059: 'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.
Await Task.Delay(0) ' x08
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(0) ' x08
~~~~~~~~~~~~~~
BC37059: 'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.
Await Task.Delay(0) ' x10
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(0) ' x10
~~~~~~~~~~~~~~
BC30311: Value of type 'Function <generated method>() As Task(Of Integer)' cannot be converted to 'Func(Of Task(Of Byte))'.
Dim x13 As Func(Of Task(Of Byte)) = x11
~~~
BC30311: Value of type 'Function <generated method>() As Task(Of Byte)' cannot be converted to 'Func(Of Task(Of Integer))'.
x12 = x14
~~~
BC30311: Value of type 'Function <generated method>() As Task' cannot be converted to 'Func(Of Integer)'.
Dim x17 As Func(Of Integer) = x15
~~~
BC30311: Value of type 'Function <generated method>() As Task' cannot be converted to 'Func(Of Integer)'.
x17 = x18
~~~
BC30654: 'Return' statement in a Function, Get, or Operator must return a value.
Return ' x19
~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x20 As Func(Of Object) = Async Function()
~~~~~~~~~~~~~~~~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function ' 9
~~~~~~~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x21 As Func(Of Object) = Async Function() Await New Task(Of Byte)(Function() 1)
~~~~~~~~~~~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x22 As Func(Of Object) = Async Function()
~~~~~~~~~~~~~~~~
BC30201: Expression expected.
Dim x30 = Overridable Sub()
~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End Sub ' Main
~~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x40 = Async Iterator Function() 1
~~~~~
BC36947: Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.
Dim x40 = Async Iterator Function() 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x41 = Async Iterator Function()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub LambdaRelaxation()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x = CandidateMethod(Async Function()
Await Task.Delay(1)
End Function)
End Sub
Function CandidateMethod(f As Func(Of Task)) As Object
System.Console.WriteLine("CandidateMethod(f As Func(Of Task)) As Object")
Return Nothing
End Function
Sub CandidateMethod(f As Func(Of Task(Of Integer)))
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Double)))
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
CandidateMethod(f As Func(Of Task)) As Object
]]>).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub MissingTypes()
Dim source =
<compilation name="MissingTaskTypes">
<file name="a.vb">
<![CDATA[
Imports System
Class Program
Shared Sub Main()
Dim x = Async Function()
End Function
Dim y = Async Function() 1
Dim z = Async Function()
return 1
End Function
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v20}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31091: Import of type 'Task' from assembly or module 'MissingTaskTypes.exe' failed.
Dim x = Async Function()
~~~~~~~~~~~~~~~~~
BC31091: Import of type 'Task(Of )' from assembly or module 'MissingTaskTypes.exe' failed.
Dim y = Async Function() 1
~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'Task(Of )' from assembly or module 'MissingTaskTypes.exe' failed.
Dim z = Async Function()
~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub IllegalAwait()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Await Task.Delay(1)
End Sub
Function Main2() As Integer
Await Task.Delay(2)
Return 1
End Function
Dim x = Await Task.Delay(3)
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37058: 'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.
Await Task.Delay(1)
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(1)
~~~~~~~~~~~~~
BC37057: 'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of Integer)'.
Await Task.Delay(2)
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(2)
~~~~~~~~~~~~~
BC36937: 'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.
Dim x = Await Task.Delay(3)
~~~~~
BC30205: End of statement expected.
Dim x = Await Task.Delay(3)
~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_UnobservedAwaitableExpression()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Namespace Windows.Foundation
public interface IAsyncAction
End Interface
public interface IAsyncActionWithProgress(Of T)
End Interface
public interface IAsyncOperation(Of T)
End Interface
public interface IAsyncOperationWithProgress(Of T, S)
End Interface
End Namespace
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Sub GetResult()
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Sub Main()
End Sub
Interface AsyncAction
Inherits Windows.Foundation.IAsyncAction
End Interface
Function M1() As AsyncAction
Return Nothing
End Function
Interface AsyncActionWithProgress
Inherits Windows.Foundation.IAsyncActionWithProgress(Of Integer)
End Interface
Function M2() As AsyncActionWithProgress
Return Nothing
End Function
Interface AsyncOperation
Inherits Windows.Foundation.IAsyncOperation(Of Integer)
End Interface
Function M3() As AsyncOperation
Return Nothing
End Function
Interface AsyncOperationWithProgress
Inherits Windows.Foundation.IAsyncOperationWithProgress(Of Integer, Integer)
End Interface
Function M4() As AsyncOperationWithProgress
Return Nothing
End Function
Async Sub M5()
Await Task.Delay(1)
End Sub
Async Function M6() As Task
Await Task.Delay(1)
End Function
Async Function M7() As Task(Of Integer)
Await Task.Delay(1)
Return 1
End Function
Function M8() As Object
Return Nothing
End Function
Function M9() As MyTask(Of Integer)
Return Nothing
End Function
Function M10() As Task
Return Nothing
End Function
Function M11() As Task(Of Integer)
Return Nothing
End Function
Sub Test1()
Call M1()
M1() ' 1
Dim x1 = M1()
Call M2()
M2() ' 1
Dim x2 = M2()
Call M3()
M3() ' 1
Dim x3 = M3()
Call M4()
M4() ' 1
Dim x4 = M4()
Call M5()
M5()
Call M6()
M6() ' 1
Dim x6 = M6()
Call M7()
M7() ' 1
Dim x7 = M7()
Call M8()
M8()
Dim x8 = M8()
Call M9()
M9()
Dim x9 = M9()
Call M10()
M10()
Dim x10 = M10()
Call M11()
M11()
Dim x11 = M11()
End Sub
Async Sub Test2()
Await Task.Delay(1)
Call M1()
M1() ' 2
Dim x1 = M1()
Call M2()
M2() ' 2
Dim x2 = M2()
Call M3()
M3() ' 2
Dim x3 = M3()
Call M4()
M4() ' 2
Dim x4 = M4()
Call M5()
M5()
Call M6()
M6() ' 2
Dim x6 = M6()
Call M7()
M7() ' 2
Dim x7 = M7()
Call M8()
M8()
Dim x8 = M8()
Call M9()
M9() ' 2
Dim x9 = M9()
Call M10()
M10() ' 2
Dim x10 = M10()
Call M11()
M11() ' 2
Dim x11 = M11()
End Sub
Async Function Test3() As Task
Await Task.Delay(1)
Call M1()
M1() ' 3
Dim x1 = M1()
Call M2()
M2() ' 3
Dim x2 = M2()
Call M3()
M3() ' 3
Dim x3 = M3()
Call M4()
M4() ' 3
Dim x4 = M4()
Call M5()
M5()
Call M6()
M6() ' 3
Dim x6 = M6()
Call M7()
M7() ' 3
Dim x7 = M7()
Call M8()
M8()
Dim x8 = M8()
Call M9()
M9() ' 3
Dim x9 = M9()
Call M10()
M10() ' 3
Dim x10 = M10()
Call M11()
M11() ' 3
Dim x11 = M11()
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M1() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M2() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M3() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M4() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M6() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M7() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M1() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M2() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M3() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M4() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M6() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M7() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M9() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M10() ' 2
~~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M11() ' 2
~~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M1() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M2() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M3() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M4() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M6() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M7() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M9() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M10() ' 3
~~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M11() ' 3
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_LoopControlMustNotAwait()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Dim array() As Integer
Async Sub Test1()
For x As Integer = Test3(Await Test2()) To 10
Next
For array(Test3(Await Test2())) = 0 To 10 ' 1
Next
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 1
Next
For Each array(Test4(Async Function()
Await Test2()
End Function)) In {1, 2, 3} ' 1
Next
End Sub
Async Function Test2() As Task(Of Integer)
For y As Integer = Test3(Await Test2()) To 10
Next
For array(Test3(Await Test2())) = 0 To 10 ' 2
Next
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 2
Next
For Each array(Test4(Async Function()
Await Test2()
End Function)) In {1, 2, 3} ' 2
Next
Return 2
End Function
Function Test3(x As Integer) As Integer
Return x
End Function
Function Test4(x As Func(Of Task)) As Integer
Return 0
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37060: Loop control variable cannot include an 'Await'.
For array(Test3(Await Test2())) = 0 To 10 ' 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37060: Loop control variable cannot include an 'Await'.
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37060: Loop control variable cannot include an 'Await'.
For array(Test3(Await Test2())) = 0 To 10 ' 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37060: Loop control variable cannot include an 'Await'.
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_BadStaticInitializerInResumable()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
Static x As Integer
x = 0
Static y As Integer = 0
Static a, b As Integer
a = 0
b = 1
Static c As New Integer()
Static d, e As New Integer()
End Sub
Async Function Test2() As Task(Of Integer)
Await Task.Delay(1)
Static u As Integer
u = 0
Static v As Integer = 0
Static f, g As Integer
f = 0
g = 1
Static h As New Integer()
Static i, j As New Integer()
Return 2
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static x As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static y As Integer = 0
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static a, b As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static a, b As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static c As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static d, e As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static d, e As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static u As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static v As Integer = 0
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static f, g As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static f, g As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static h As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static i, j As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static i, j As New Integer()
~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_RestrictedResumableType1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Delegate Sub D1(x As ArgIterator)
Delegate Sub D2(ByRef x As ArgIterator)
Delegate Sub D3(ByRef x As ArgIterator())
Delegate Sub D4(x As ArgIterator())
Sub Main()
Dim x = Async Sub(a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim y = Async Sub(ByRef a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim z = Async Sub(ByRef a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim u = Async Sub(a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim x1 As D1 = Async Sub(a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim y1 As D2 = Async Sub(ByRef a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim z1 As D3 = Async Sub(ByRef a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim u1 As D4 = Async Sub(a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim x2 As D1 = Async Sub(a)
Await Task.Delay(1)
End Sub
Dim y2 As D2 = Async Sub(ByRef a)
Await Task.Delay(1)
End Sub
Dim z2 As D3 = Async Sub(ByRef a)
Await Task.Delay(1)
End Sub
Dim u2 As D4 = Async Sub(a)
Await Task.Delay(1)
End Sub
End Sub
Async Sub Test1(x As ArgIterator)
Await Task.Delay(1)
End Sub
Async Sub Test2(ByRef x As ArgIterator)
Await Task.Delay(1)
End Sub
Async Sub Test3(x As ArgIterator())
Await Task.Delay(1)
End Sub
Async Sub Test4(ByRef x As ArgIterator())
Await Task.Delay(1)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Delegate Sub D2(ByRef x As ArgIterator)
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Delegate Sub D3(ByRef x As ArgIterator())
~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Delegate Sub D4(x As ArgIterator())
~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim x = Async Sub(a As ArgIterator)
~~~~~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Dim x = Async Sub(a As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim y = Async Sub(ByRef a As ArgIterator)
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim y = Async Sub(ByRef a As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim z = Async Sub(ByRef a As ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim u = Async Sub(a As ArgIterator())
~~~~~~~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Dim x1 As D1 = Async Sub(a As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim y1 As D2 = Async Sub(ByRef a As ArgIterator)
~~~~~~~~~~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim z1 As D3 = Async Sub(ByRef a As ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim u1 As D4 = Async Sub(a As ArgIterator())
~~~~~~~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Dim x2 As D1 = Async Sub(a)
~
BC36926: Async methods cannot have ByRef parameters.
Dim y2 As D2 = Async Sub(ByRef a)
~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim z2 As D3 = Async Sub(ByRef a)
~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Async Sub Test1(x As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Async Sub Test2(ByRef x As ArgIterator)
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Async Sub Test3(x As ArgIterator())
~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Async Sub Test4(ByRef x As ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_ConstructorAsync_and_ERRID_PartialMethodsMustNotBeAsync1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Class Test
Async Sub New()
End Sub
Shared Async Sub New()
End Sub
Partial Private Async Sub Part()
End Sub
Private Async Sub Part()
Await Task.Delay(1)
End Sub
End Class
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36950: Constructor must not have the 'Async' modifier.
Async Sub New()
~~~~~
BC36950: Constructor must not have the 'Async' modifier.
Shared Async Sub New()
~~~~~
BC36935: 'Part' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Part()
~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_ResumablesCannotContainOnError()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
On Error GoTo 0 ' 1
Resume Next ' 1
End Sub
Iterator Function Test2() As System.Collections.Generic.IEnumerable(Of Integer)
On Error GoTo 0 ' 2
Resume Next ' 2
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
On Error GoTo 0 ' 1
~~~~~~~~~~~~~~~
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
Resume Next ' 1
~~~~~~~~~~~
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
On Error GoTo 0 ' 2
~~~~~~~~~~~~~~~
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
Resume Next ' 2
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_ResumableLambdaInExpressionTree()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Linq.Expressions
Module Program
Sub Main()
Dim x As Expression(Of Action) = Async Sub() Await Task.Delay(1)
Dim y As Expression(Of Func(Of System.Collections.Generic.IEnumerable(Of Integer))) = Iterator Function()
End Function
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37050: Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.
Dim x As Expression(Of Action) = Async Sub() Await Task.Delay(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37050: Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.
Dim y As Expression(Of Func(Of System.Collections.Generic.IEnumerable(Of Integer))) = Iterator Function()
~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_CannotLiftRestrictedTypeResumable1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
Dim a1 As ArgIterator
Dim b1 As ArgIterator = Nothing
Dim c1 As ArgIterator, d1 As ArgIterator = Nothing
Dim e1 As New ArgIterator(Nothing)
Dim f1, g1 As New ArgIterator(Nothing)
Dim h1 = New ArgIterator()
a1=Nothing
c1=Nothing
End Sub
Iterator Function Test2() As System.Collections.Generic.IEnumerable(Of Integer)
Dim a2 As ArgIterator
Dim b2 As ArgIterator = Nothing
Dim c2 As ArgIterator, d2 As ArgIterator = Nothing
Dim e2 As New ArgIterator(Nothing)
Dim f2, g2 As New ArgIterator(Nothing)
Dim h2 = New ArgIterator()
a2=Nothing
c2=Nothing
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim a1 As ArgIterator
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim b1 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c1 As ArgIterator, d1 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c1 As ArgIterator, d1 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim e1 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim f1, g1 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim h1 = New ArgIterator()
~~~~~~~~~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim a2 As ArgIterator
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim b2 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c2 As ArgIterator, d2 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c2 As ArgIterator, d2 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim e2 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim f2, g2 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim h2 = New ArgIterator()
~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_BadAwaitInTryHandler()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x = Async Sub()
Try
Await Test2() ' Try 1
Catch ex As Exception When Await Test2() > 1 ' Filter 1
Catch
Await Test2() ' Catch 1
Finally
Await Test2() ' Finally 1
End Try
SyncLock New Lock(Await Test2()) ' SyncLock 1
Await Test2() ' SyncLock 1
End SyncLock
End Sub
End Sub
Async Sub Test1()
Try
Await Test2() ' Try 2
Catch ex As Exception When Await Test2() > 1 ' Filter 2
Catch
Await Test2() ' Catch 2
Finally
Await Test2() ' Finally 2
End Try
SyncLock New Lock(Await Test2()) ' SyncLock 2
Await Test2() ' SyncLock 2
End SyncLock
End Sub
Async Function Test2() As Task(Of Integer)
Await Task.Delay(1)
Return 1
End Function
Class Lock
Sub New(x As Integer)
End Sub
End Class
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Catch ex As Exception When Await Test2() > 1 ' Filter 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Catch 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Finally 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
SyncLock New Lock(Await Test2()) ' SyncLock 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' SyncLock 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Catch ex As Exception When Await Test2() > 1 ' Filter 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Catch 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Finally 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
SyncLock New Lock(Await Test2()) ' SyncLock 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' SyncLock 2
~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncLacksAwaits()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x = Async Sub()
End Sub
End Sub
Async Sub Test1()
End Sub
Async Function Test2() As Task(Of Integer)
Return 1
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42356: This async method lacks 'Await' operators and so 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.
Dim x = Async Sub()
~~~
BC42356: This async method lacks 'Await' operators and so 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.
Async Sub Test1()
~~~~~
BC42356: This async method lacks 'Await' operators and so 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.
Async Function Test2() As Task(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_UnobservedAwaitableDelegate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x As Action
x = AddressOf Test1
x = AddressOf Test2
x = AddressOf Test3
x = AddressOf Test4
x = AddressOf Test5
x = New Action(AddressOf Test2)
x = CType(AddressOf Test2, Action)
x = DirectCast(AddressOf Test2, Action)
x = TryCast(AddressOf Test2, Action)
x = Async Sub()
Await Task.Delay(1)
End Sub
x = Async Function()
Await Task.Delay(1)
Return 1
End Function
x = Async Function() As Task(Of Integer)
Await Task.Delay(1)
Return 1
End Function
x = Async Function()
Await Task.Delay(1)
End Function
x = Async Function() As Task
Await Task.Delay(1)
End Function
x = New Action(Async Function()
Await Task.Delay(1)
End Function)
x = CType(Async Function()
Await Task.Delay(1)
End Function, Action)
x = DirectCast(Async Function()
Await Task.Delay(1)
End Function, Action)
x = TryCast(Async Function()
Await Task.Delay(1)
End Function, Action)
x = Function() As Task(Of Integer)
Return Nothing
End Function
x = Function() As Task
Return Nothing
End Function
Dim y = Async Function()
Await Task.Delay(1)
End Function
x = y
End Sub
Async Sub Test1() Handles z.y
Await Task.Delay(1)
End Sub
Async Function Test2() As Task(Of Integer) Handles z.y
Await Task.Delay(1)
Return 1
End Function
Async Function Test3() As Task Handles z.y
Await Task.Delay(1)
End Function
WithEvents z As CWithEvents
Class CWithEvents
Public Event y As Action
End Class
Function Test4() As Task(Of Integer) Handles z.y
Return Nothing
End Function
Function Test5() As Task Handles z.y
Return Nothing
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = AddressOf Test2
~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = AddressOf Test3
~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function()
~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function() As Task(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function()
~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function() As Task
~~~~~~~~~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
Async Function Test2() As Task(Of Integer) Handles z.y
~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
Async Function Test3() As Task Handles z.y
~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SecurityCriticalAsyncInClassOrStruct_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
<Security.SecurityCritical()>
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
End Sub
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Class C1
Async Sub Test3()
Await Task.Delay(1)
End Sub
Iterator Function Test4() As Collections.Generic.IEnumerable(Of Integer)
End Function
End Class
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Async Sub Test1()
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Async Sub Test3()
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Iterator Function Test4() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SecurityCriticalAsyncInClassOrStruct_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
End Module
<Security.SecuritySafeCritical()>
Class C2
Private Async Sub Test5()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test5()
End Sub
Iterator Function Test6() As Collections.Generic.IEnumerable(Of Integer)
End Function
End Class
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Private Async Sub Test5()
~~~~~
BC36935: 'Test5' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test5()
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Iterator Function Test6() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SecurityCriticalAsync()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
<Security.SecurityCritical()> ' 1
Private Async Sub Test1()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test1()
End Sub
<Security.SecuritySafeCritical()> ' 2
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Private Async Sub Test3()
Await Task.Delay(1)
End Sub
<Security.SecurityCritical()> ' 3
Partial Private Sub Test3()
End Sub
<Security.SecurityCritical()> ' 4
Partial Private Async Sub Test4()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31006: Security attribute 'SecurityCritical' cannot be applied to an Async or Iterator method.
<Security.SecurityCritical()> ' 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36935: 'Test1' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test1()
~~~~~
BC31006: Security attribute 'SecuritySafeCritical' cannot be applied to an Async or Iterator method.
<Security.SecuritySafeCritical()> ' 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31006: Security attribute 'SecurityCritical' cannot be applied to an Async or Iterator method.
<Security.SecurityCritical()> ' 3
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36935: 'Test4' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test4()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_DllImportOnResumableMethod()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.InteropServices
Module Program
Sub Main()
End Sub
<DllImport("Test1")>
Private Async Sub Test1()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test1()
End Sub
<DllImport("Test2")>
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Private Async Sub Test3()
Await Task.Delay(1)
End Sub
<DllImport("Test3")>
Partial Private Sub Test3()
End Sub
<DllImport("Test4")>
Partial Private Async Sub Test4()
End Sub
<DllImport("Test5")>
Partial Private Sub Test5()
End Sub
Private Sub Test5()
Return
End Sub
<DllImport("Test6")>
Partial Private Sub Test6()
End Sub
Private Sub Test6()
End Sub
<DllImport("Test7")>
Partial Private Sub Test7()
End Sub
Private Async Sub Test7()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Private Async Sub Test1()
~~~~~
BC36935: 'Test1' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test1()
~~~~~
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Private Async Sub Test3()
~~~~~
BC36935: 'Test4' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test4()
~~~~~
BC31522: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.
<DllImport("Test5")>
~~~~~~~~~
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Private Async Sub Test7()
~~~~~
BC42356: This async method lacks 'Await' operators and so 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.
Private Async Sub Test7()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SynchronizedAsyncMethod()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Private Async Sub Test1()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test1()
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Private Async Sub Test3()
Await Task.Delay(1)
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Partial Private Sub Test3()
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Partial Private Async Sub Test4()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37054: 'MethodImplOptions.Synchronized' cannot be applied to an Async method.
Private Async Sub Test1()
~~~~~
BC36935: 'Test1' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test1()
~~~~~
BC37054: 'MethodImplOptions.Synchronized' cannot be applied to an Async method.
Private Async Sub Test3()
~~~~~
BC36935: 'Test4' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test4()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_AsyncSubMain()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Main()
'Await Task.Delay(1)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36934: The 'Main' method cannot be marked 'Async'.
Async Sub Main()
~~~~
BC42356: This async method lacks 'Await' operators and so 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.
Async Sub Main()
~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program1
Sub Main1()
' 1
Task.Factory.StartNew(Async Sub() ' 1
Await Task.Delay(1)
End Sub)
Task.Factory.StartNew((Async Sub() ' 1
Await Task.Delay(1)
End Sub))
' 2
Task.Run(Async Sub() ' 2
Await Task.Delay(1)
End Sub)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Task.Factory.StartNew(Async Sub() ' 1
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Task.Factory.StartNew((Async Sub() ' 1
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Task.Run(Async Sub() ' 2
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program2
Async Function f(ByVal i As Integer) As Task
Dim j As Integer = 2
Await taskrun(Sub()
Dim x = 5
Console.WriteLine(x + i + j)
End Sub)
' 3
Await taskrun(Async Sub() ' 3
Dim x = 6
Await Task.Delay(1)
End Sub)
Await taskrun((Async Sub() ' 3
Dim x = 6
Await Task.Delay(1)
End Sub))
Await taskrun(Async Function()
Dim x = 7
Await Task.Delay(1)
End Function)
Await taskrun(Async Function()
Dim x = 8
Await Task.Delay(1)
End Function)
End Function
Async Function taskrun(ByVal f As Func(Of Task)) As Task
Dim tt As Task(Of Task) = Task.Factory.StartNew(Of Task)(f)
Dim t As Task = Await tt
Await t
End Function
Async Function taskrun(ByVal f As Action) As task
Dim t As Task = Task.Factory.StartNew(f)
Await t
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Await taskrun(Async Sub() ' 3
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Await taskrun((Async Sub() ' 3
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program3
Sub Main3()
Dim t = Async Function()
Await Task.Yield()
Return "hello"
End Function()
TaskRun(Sub() Console.WriteLine("expected Action"))
TaskRun(Sub()
Console.WriteLine("expected Action")
End Sub)
' 4
TaskRun(Async Sub() Await Task.Delay(1)) ' 4
' 5
TaskRun(Async Sub() ' 5
Await Task.Delay(1)
End Sub)
TaskRun(Function() "expected Func<T>")
TaskRun(Function()
Return "expected Func<T>"
End Function)
TaskRun(Async Function()
Console.WriteLine("expected Func<Task>")
Await Task.Yield()
End Function)
TaskRun(Async Function() d(Await t, "expected Func<Task<T>>"))
TaskRun(Async Function()
Await Task.Yield()
Return "expected Func<Task<T>>"
End Function)
End Sub
Function d(Of T)(dummy As Object, x As T) As T
Return x
End Function
Sub TaskRun(f As Action)
Console.WriteLine("TaskRun: Action")
f()
Console.WriteLine()
End Sub
Sub TaskRun(f As Func(Of Task))
Console.WriteLine("TaskRun: Func<Task>")
f().Wait()
Console.WriteLine()
End Sub
Sub TaskRun(Of T)(f As Func(Of T))
Console.WriteLine("TaskRun: Func<T>")
Console.WriteLine(f())
Console.WriteLine()
End Sub
Sub TaskRun(Of T)(f As Func(Of Task(Of T)))
Console.WriteLine("TaskRun: Func<Task<T>>")
Console.WriteLine(f().Result)
Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
TaskRun(Async Sub() Await Task.Delay(1)) ' 4
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
TaskRun(Async Sub() ' 5
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_4()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program4
Function f(x As action) As Integer
Return 1
End Function
Function f(Of T)(x As Func(Of T)) As Integer
Return 2
End Function
Sub h(x As Action)
End Sub
Sub h(x As Func(Of Task))
End Sub
Sub Main4()
' 6
f(Async Sub() ' 6
Await Task.Yield()
End Sub)
' 7
Console.WriteLine(f(Async Sub() ' 7
Await Task.Yield()
End Sub))
' 8
h(Async Sub() ' 8
Await Task.Yield()
End Sub)
Dim s = ""
' 9
s.gg(Async Sub() ' 9
Await Task.Yield()
End Sub)
End Sub
<Extension()> Sub gg(this As String, x As Action)
End Sub
<Extension()> Sub gg(this As String, x As Func(Of Task))
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
f(Async Sub() ' 6
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Console.WriteLine(f(Async Sub() ' 7
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
h(Async Sub() ' 8
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
s.gg(Async Sub() ' 9
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_5()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program5
Async Function Test() As Task
Await Task.Yield()
' 10
CandidateMethod(Async Sub() ' 10
Await Task.Yield()
End Sub)
' 11
CandidateMethod(Async Sub() ' 11
Await Task.Yield()
End Sub)
' 12
CandidateMethod(Async Sub() ' 12
Console.WriteLine("fReturningTaskAsyncLambdaWithAwait")
Await Task.Yield()
End Sub)
' 13
CandidateMethod(Async Sub(i As Object) ' 13
Console.WriteLine("fTakingIntReturningTask")
Await Task.Yield()
End Sub)
End Function
Sub CandidateMethod()
Console.WriteLine("CandidateMethod()")
End Sub
Sub CandidateMethod(i As Integer)
Console.WriteLine("CandidateMethod(integer) passed {0}", i)
End Sub
Sub CandidateMethod(d As Double)
Console.WriteLine("CandidateMethod(double) passed {0}", d)
End Sub
Sub CandidateMethod(o As Object)
Console.WriteLine("CandidateMethod(object) passed {0}", o)
End Sub
Sub CandidateMethod(d As System.Delegate)
Console.WriteLine("CandidateMethod(System.Delegate) passed {0}", d)
End Sub
Sub CandidateMethod(a As action)
a()
Console.WriteLine("CandidateMethod(Action) passed {0}", a)
End Sub
Sub CandidateMethod(f As Func(Of Integer))
Console.WriteLine("CandidateMethod(Func(Of integer)) func returns {0}", f())
End Sub
Sub CandidateMethod(f As Func(Of Double))
Console.WriteLine("CandidateMethod(Func(Of double)) func returns {0}", f())
End Sub
Sub CandidateMethod(f As Func(Of Task))
f().Wait()
Console.WriteLine("CandidateMethod(Func(Of Task)) passed {0}", f)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Integer)))
Console.WriteLine("CandidateMethod(Func(Of Task(Of integer))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Double)))
Console.WriteLine("CandidateMethod(Func(Of Task(Of (Of double))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Integer, Task))
f(1).Wait()
Console.WriteLine("CandidateMethod(Func(Of integer,Task)) passed {0}", f)
End Sub
Sub CandidateMethod(f As Func(Of Integer, Task(Of Integer)))
Console.WriteLine("CandidateMethod(Func(Of integer,Task(Of integer))) task returns {0}", f(1).Result)
End Sub
Sub CandidateMethod(f As Func(Of Integer, Task(Of Double)))
Console.WriteLine("CandidateMethod(Func(Of integer,Task(Of double))) task returns {0}", f(1).Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Object)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of object))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of String)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of sting))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Integer?)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of integer?))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Double?)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of double?))) task returns {0}", f().Result)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub() ' 10
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub() ' 11
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub() ' 12
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub(i As Object) ' 13
~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact(), WorkItem(547087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547087")>
Public Sub Bug17912_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main(args As String())
End Sub
Async Function Test0() As Task
Dim x as Await
Dim y As [Await]
Await Task.Delay(1)
End Function
Async Function await() As Task
Await Task.Delay(1)
End Function
Async Sub Test1(await As Integer)
Await Task.Delay(1)
End Sub
Async Function Test2(x As Await) As Task
Await Task.Delay(1)
End Function
Async Function Test3() As Await
Await Task.Delay(1)
End Function
End Module
Class Await
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC42024: Unused local variable: 'x'.
Dim x as Await
~
BC30183: Keyword is not valid as an identifier.
Dim x as Await
~~~~~
BC42024: Unused local variable: 'y'.
Dim y As [Await]
~
BC30183: Keyword is not valid as an identifier.
Async Function await() As Task
~~~~~
BC30183: Keyword is not valid as an identifier.
Async Sub Test1(await As Integer)
~~~~~
BC30183: Keyword is not valid as an identifier.
Async Function Test2(x As Await) As Task
~~~~~
BC30183: Keyword is not valid as an identifier.
Async Function Test3() As Await
~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Async Function Test3() As Await
~~~~~
BC42105: Function 'Test3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(547087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547087")>
Public Sub Bug17912_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Class Await
End Class
Module Module2
Sub Main(args As String())
End Sub
Async Function [await]() As Task
Await Task.Delay(1)
End Function
Async Sub Test1([await] As Integer)
Await Task.Delay(1)
End Sub
Async Function Test2(x As [Await]) As Task
Await Task.Delay(1)
End Function
Async Function Test3() As [Await]
Await Task.Delay(1)
End Function
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Async Function Test3() As [Await]
~~~~~~~
BC42105: Function 'Test3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(547087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547087")>
Public Sub Bug17912_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main(args As String())
Dim test0 = Async Function() As Task
Dim x As Await
Dim y As [Await]
Await Task.Delay(1)
End Function
Dim test1 = Async Sub (await As Integer)
Await Task.Delay(1)
End Sub
Dim test2 = Async Function (x As Await) As Task
Await Task.Delay(1)
End Function
Dim test3 = Async Function() As Await
Await Task.Delay(1)
End Function ' 1
Dim test4 = Async Sub (await As Integer) Await Task.Delay(1)
Dim test5 = Async Sub (await As Integer) Await GetTask()
Dim test11 = Async Sub([await] As Integer)
Await Task.Delay(1)
End Sub
Dim test21 = Async Function(x As [Await]) As Task
Await Task.Delay(1)
End Function
Dim test31 = Async Function() As Task(Of [Await])
Await Task.Delay(1)
End Function ' 2
Dim test41 = Async Sub([await] As Integer) Await Task.Delay(1)
Dim test51 = Async Sub([await] As Integer) Await GetTask()
End Sub
Function GetTask() As Task(Of Integer)
Return Nothing
End Function
End Module
Class Await
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42024: Unused local variable: 'x'.
Dim x As Await
~
BC30183: Keyword is not valid as an identifier.
Dim x As Await
~~~~~
BC42024: Unused local variable: 'y'.
Dim y As [Await]
~
BC30183: Keyword is not valid as an identifier.
Dim test1 = Async Sub (await As Integer)
~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test2 = Async Function (x As Await) As Task
~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test3 = Async Function() As Await
~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim test3 = Async Function() As Await
~~~~~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function ' 1
~~~~~~~~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test4 = Async Sub (await As Integer) Await Task.Delay(1)
~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test5 = Async Sub (await As Integer) Await GetTask()
~~~~~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function ' 2
~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact(), WorkItem(568948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568948")>
Public Sub Bug568948()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Public Module Module1
Public Sub Main()
goo()
End Sub
Public Async Sub Goo()
Dim AwaitableLambda1 = Async Function()
Await Task.Yield
Return New List(Of Test) From {New Test With {.Async = "test2", .Await = 2}, New Test With {.Async = "test3", .Await = 3}}
End Function
Dim Query = From x2 In Await AwaitableLambda1() Select New With {.async = x2, .b = Function(Await)
Return Await.Await + 1
End Function.Invoke(x2)}
'ANOTHER EXAMPLE FAILING WITH SAME ISSUE....
'
' Dim AwaitableLambda1 = Async Function()
' Await Task.Yield
' Return New List(Of Test) From {New Test With {.Async = "test2", .Await = 2}, New Test With {.Async = "test3", .Await = 3}}
' End Function
' Dim Query = From x2 In Await AwaitableLambda1() Select New With {.async = x2, .b = Function(Await)
' Return Await.Await + 1
' End Function.Invoke(.async)}
End Sub
End Module
Public Class Test
Public Property Await As Integer = 1
Public Property Async As String = "Test"
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, LatestVbReferences, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_Errors()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
<Obsolete("Do not use!", True)>
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
<Obsolete("Do not use!", True)>
Public Function GetResult() As T
Return Nothing
End Function
<Obsolete("Do not use!", True)>
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30668: 'Public Function GetAwaiter() As MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC30668: 'Public Function GetResult() As T' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC30668: 'Public ReadOnly Property IsCompleted As Boolean' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_Warnings()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
<Obsolete("Do not use!", False)>
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
<Obsolete("Do not use!", False)>
Public Function GetResult() As T
Return Nothing
End Function
<Obsolete("Do not use!", False)>
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC40000: 'Public Function GetAwaiter() As MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC40000: 'Public Function GetResult() As T' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC40000: 'Public ReadOnly Property IsCompleted As Boolean' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_Interface()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
<Obsolete("Do not use!", True)>
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
Public Function GetResult() As T
Return Nothing
End Function
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30668: 'MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
~~~~~~~~~~~~~~~~~~~
BC30668: 'MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Return New MyTaskAwaiter(Of T)()
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_InterfaceMethod()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
<Obsolete("Do not use!", True)>
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
Public Function GetResult() As T
Return Nothing
End Function
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact()>
Public Sub Legacy_Async_Overload_Change_3()
Dim source =
<compilation>
<file name="a.vb">
<%= SemanticResourceUtil.Async_Overload_Change_3_vb %>
</file>
</compilation>
Dim warnings = New Dictionary(Of String, ReportDiagnostic)()
warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42356), ReportDiagnostic.Suppress)
Dim compilation = CreateEmptyCompilationWithReferences(source,
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929},
TestOptions.ReleaseExe.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)))
CompileAndVerify(compilation, expectedOutput:="")
End Sub
<Fact(), WorkItem(1066694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066694")>
Public Sub Bug1066694()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main()
System.Console.WriteLine("Non-Async")
System.Console.WriteLine()
TestLocal()
System.Console.WriteLine()
System.Console.WriteLine("Async")
System.Console.WriteLine()
Task.WaitAll(TestLocalAsync())
End Sub
Sub TestLocal()
Dim l = New TestClass("Unchanged")
l.M1(l, Mutate(l))
System.Console.WriteLine(l.State)
End Sub
Async Function DummyAsync(x As Object) As Task(Of Object)
Return x
End Function
Async Function TestLocalAsync() As Task
Dim l = New TestClass("Unchanged")
l.M1(l, Await DummyAsync(Mutate(l)))
System.Console.WriteLine(l.State)
End Function
Function Mutate(ByRef x As TestClass) As Object
x = New TestClass("Changed")
Return x
End Function
End Module
Class TestClass
Private ReadOnly fld1 As String
Sub New(val As String)
fld1 = val
End Sub
Function State() As String
Return fld1
End Function
Sub M1(arg1 As TestClass, arg2 As Object)
System.Console.WriteLine(Me.State)
System.Console.WriteLine(arg1.State)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
Non-Async
Unchanged
Unchanged
Changed
Async
Unchanged
Unchanged
Changed
]]>)
End Sub
<Fact(), WorkItem(1068084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068084")>
Public Sub Bug1068084()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Threading.Tasks
Class Test
Async Sub F()
Await Task.Delay(0)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626}, TestOptions.ReleaseDll)
AssertTheseEmitDiagnostics(compilation,
<expected>
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError' is not defined.
Async Sub F()
~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError' is not defined.
Async Sub F()
~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(1021941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021941")>
Public Sub Bug1021941()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Interface IMoveable
Sub M1(x As Integer, y As Integer, z As Integer)
Function M2() As Integer
End Interface
Class Item
Implements IMoveable
Public Property Name As String
Public Sub M1(x As Integer, y As Integer, z As Integer) Implements IMoveable.M1
Console.WriteLine("M1 is called for item '{0}'", Me.Name)
End Sub
Public Function M2() As Integer Implements IMoveable.M2
Console.WriteLine("M2 is called for item '{0}'", Me.Name)
Return 0
End Function
End Class
Class Program
Shared Sub Main()
Dim item = New Item With {.Name = "Goo"}
Task.WaitAll(Shift(item))
End Sub
Shared Async Function Shift(Of T As {Class, IMoveable})(item As T) As Task(Of Integer)
item.M1(item.M2(), Await DummyAsync(), GetOffset(item))
Return 0
End Function
Shared Async Function DummyAsync() As Task(Of Integer)
Return 0
End Function
Shared Function GetOffset(Of T)(ByRef item As T) As Integer
item = DirectCast(DirectCast(New Item With {.Name = "Bar"}, IMoveable), T)
Return 0
End Function
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.DebugExe)
CompileAndVerify(compilation,
<![CDATA[
M2 is called for item 'Goo'
M1 is called for item 'Bar'
]]>)
End Sub
<Fact(), WorkItem(1173166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1173166"), WorkItem(2878, "https://github.com/dotnet/roslyn/issues/2878")>
Public Sub CompoundAssignment()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class Test
Private _field As UInteger
Shared Sub Main()
Dim t as New Test()
System.Console.WriteLine(t._field)
t.EventHandler(-1).Wait()
System.Console.WriteLine(t._field)
End Sub
Private Async Function EventHandler(args As Integer) As System.Threading.Tasks.Task
Await RunAsync(Async Function()
System.Console.WriteLine(args)
_field += CUInt(1)
End Function)
End Function
Private Async Function RunAsync(x As System.Func(Of System.Threading.Tasks.Task)) As System.Threading.Tasks.Task
Await x()
End Function
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.DebugExe)
Dim expected As Xml.Linq.XCData = <![CDATA[
0
-1
1
]]>
CompileAndVerify(compilation, expected)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expected)
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.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports System.Collections.ObjectModel
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class AsyncAwait
Inherits BasicTestBase
<Fact()>
Public Sub Basic()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Threading.Tasks
Module Program
Function Test1() As Task(Of Integer)
Return Nothing
End Function
Async Sub Test2()
Await Test1()
Dim x As Integer = Await Test1()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact, WorkItem(744146, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/744146")>
Public Sub DefaultAwaitExpressionInfo()
Dim awaitInfo As AwaitExpressionInfo = Nothing
Assert.Null(awaitInfo.GetAwaiterMethod)
Assert.Null(awaitInfo.IsCompletedProperty)
Assert.Null(awaitInfo.GetResultMethod)
End Sub
<Fact()>
Public Sub AwaitableType01()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Equal("ReadOnly Property MyTaskAwaiter(Of System.Int32).IsCompleted As System.Boolean", awaitInfo.IsCompletedProperty.ToTestDisplayString())
Assert.Equal("Function MyTaskAwaiter(Of System.Int32).GetResult() As System.Int32", awaitInfo.GetResultMethod.ToTestDisplayString())
End Sub
<Fact()>
Public Sub AwaitableType02()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter(Optional x As Integer = 0) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Null(awaitInfo.GetAwaiterMethod)
Assert.Null(awaitInfo.IsCompletedProperty)
Assert.Null(awaitInfo.GetResultMethod)
End Sub
<Fact()>
Public Sub AwaitableType03()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Sub GetAwaiter()
End Sub
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType04()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As Object
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType05()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
ReadOnly Property GetAwaiter As MyTaskAwaiter(Of T)
Get
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Get
End Property
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = (New MyTask(Of Integer)).GetAwaiter
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType06()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Protected Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType07()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter(x As Integer) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType08()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType09()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Shared Function GetAwaiter() As MyTaskAwaiter(Of T)
Return Nothing
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType10()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return Nothing
End Function
End Class
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30002: Type 'MyTaskAwaiter' is not defined.
' error BC36949: Expression is of type 'MyTask(Of Integer)', which is not awaitable.
AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'MyTaskAwaiter' is not defined.
Function GetAwaiter() As MyTaskAwaiter(Of T)
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType11()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
<Extension>
Function GetAwaiter(Of T)(this As MyTask(Of T)) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = this}
End Function
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact()>
Public Sub AwaitableType12()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
<Extension>
Function GetAwaiter(Of T)(this As MyTask(Of T), Optional x As Integer = 0) As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = this}
End Function
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
AssertTheseDiagnostics(compilation,
<expected>
BC36930: 'Await' requires that the type 'MyTask(Of Integer)' have a suitable GetAwaiter method.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType13()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim o As Object = New MyTask(Of Integer)
Dim x = Await o
Await o
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.Custom))
AssertTheseDiagnostics(compilation,
<expected>
BC42017: Late bound resolution; runtime errors could occur.
Dim x = Await o
~~~~~~~
BC42017: Late bound resolution; runtime errors could occur.
Await o
~~~~~~~
</expected>)
compilation = compilation.WithOptions(compilation.Options.WithOptionStrict(OptionStrict.On))
AssertTheseDiagnostics(compilation,
<expected>
BC30574: Option Strict On disallows late binding.
Dim x = Await o
~~~~~~~
BC30574: Option Strict On disallows late binding.
Await o
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType14()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Module Program
Sub Test1()
End Sub
Async Sub Test2()
Dim x As Integer = Await Test1()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30491: Expression does not produce a value.
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Dim x As Integer = Await Test1()
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType15()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30456: 'IsCompleted' is not a member of 'MyTaskAwaiter(Of Integer)'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Null(awaitInfo.IsCompletedProperty)
Assert.Equal("Function MyTaskAwaiter(Of System.Int32).GetResult() As System.Int32", awaitInfo.GetResultMethod.ToTestDisplayString())
End Sub
<Fact()>
Public Sub AwaitableType16()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Private ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' BC30390: 'MyTaskAwaiter(Of T).Private ReadOnly Property IsCompleted As Boolean' is not accessible in this context because it is 'Private'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType17()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Function IsCompleted() As Boolean
Throw New NotImplementedException()
End Function
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = (New MyTask(Of Integer)).GetAwaiter().IsCompleted
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType18()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Object
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType19()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted(x As Integer) As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property IsCompleted(x As Integer) As Boolean'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType20()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted(Optional x As Integer = 0) As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = (New MyTask(Of Integer)).GetAwaiter().IsCompleted
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType21()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
Shared ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim y = MyTaskAwaiter(Of Integer).IsCompleted
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' warning BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType22()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As DoesntExist
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30002: Type 'DoesntExist' is not defined.
AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
ReadOnly Property IsCompleted() As DoesntExist
~~~~~~~~~~~
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType23()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30456: 'GetResult' is not a member of 'MyTaskAwaiter(Of Integer)'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Equal("ReadOnly Property MyTaskAwaiter(Of System.Int32).IsCompleted As System.Boolean", awaitInfo.IsCompletedProperty.ToTestDisplayString())
Assert.Null(awaitInfo.GetResultMethod)
End Sub
<Fact()>
Public Sub AwaitableType24()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Private Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30390: 'MyTaskAwaiter(Of T).Private Function GetResult() As T' is not accessible in this context because it is 'Private'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType25()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult(x As Integer) As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30455: Argument not specified for parameter 'x' of 'Public Function GetResult(x As Integer) As T'.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType26()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult(Optional x As Integer = 0) As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType27()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Shared Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' warning BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType28()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
ReadOnly Property GetResult() As T
Get
Throw New NotImplementedException()
End Get
End Property
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim Y = (New MyTask(Of Integer)).GetAwaiter().GetResult
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType29()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
End Structure
Module Program
<Extension>
Function GetResult(Of t)(X As MyTaskAwaiter(Of t)) As t
Throw New NotImplementedException()
End Function
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Dim Y = (New MyTask(Of Integer)).GetAwaiter().GetResult
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType30()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As DoesntExist
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30002: Type 'DoesntExist' is not defined.
AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
Function GetResult() As DoesntExist
~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType31()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Sub GetResult()
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Async Sub Test2()
Dim x As Integer = Await New MyTask(Of Integer)
Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30491: Expression does not produce a value.
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Dim x As Integer = Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType32()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC37056: 'MyTaskAwaiter(Of Integer)' does not implement 'System.Runtime.CompilerServices.INotifyCompletion'.
AssertTheseDiagnostics(compilation,
<expected>
BC37056: 'MyTaskAwaiter(Of Integer)' does not implement 'INotifyCompletion'.
Await New MyTask(Of Integer) 'BIND1:"Await New MyTask(Of Integer)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 As AwaitExpressionSyntax = CompilationUtils.FindBindingText(Of AwaitExpressionSyntax)(compilation, "a.vb", 1)
Dim awaitInfo As AwaitExpressionInfo = semanticModel.GetAwaitExpressionInfo(node1)
Assert.Equal("Function MyTask(Of System.Int32).GetAwaiter() As MyTaskAwaiter(Of System.Int32)", awaitInfo.GetAwaiterMethod.ToTestDisplayString())
Assert.Equal("ReadOnly Property MyTaskAwaiter(Of System.Int32).IsCompleted As System.Boolean", awaitInfo.IsCompletedProperty.ToTestDisplayString())
Assert.Equal("Function MyTaskAwaiter(Of System.Int32).GetResult() As System.Int32", awaitInfo.GetResultMethod.ToTestDisplayString())
End Sub
<Fact()>
Public Sub AwaitableType33()
Dim source =
<compilation name="MissingINotifyCompletion">
<file name="a.vb">
<![CDATA[
Imports System
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib, TestMetadata.Net40.MicrosoftVisualBasic}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC31091: Import of type 'INotifyCompletion' from assembly or module 'MissingINotifyCompletion.exe' failed.
Await New MyTask(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType34()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Test0()
Await Task.Delay(1)
End Sub
Async Sub Test1()
Await Test0()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC37001: 'Test0' does not return a Task and cannot be awaited. Consider changing it to an Async Function.
Await Test0()
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitableType35()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
#Const defined = True
<System.Diagnostics.Conditional("defined")>
Sub GetResult()
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Async Sub Test1()
Await New MyTask(Of Integer)()
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC37053: 'Await' requires that the return type 'MyTaskAwaiter(Of Integer)' of 'MyTask(Of Integer).GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.
Await New MyTask(Of Integer)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaiterImplementsINotifyCompletion_Constraint()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Runtime.CompilerServices
Class Awaitable(Of T)
Friend Function GetAwaiter() As T
Return Nothing
End Function
End Class
Interface IA
ReadOnly Property IsCompleted As Boolean
Function GetResult() As Object
End Interface
Interface IB
Inherits IA, INotifyCompletion
End Interface
Class A
Friend ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
Friend Function GetResult() As Object
Return Nothing
End Function
End Class
Class B
Inherits A
Implements INotifyCompletion
Private Sub OnCompleted(a As System.Action) Implements INotifyCompletion.OnCompleted
End Sub
End Class
Module M
Async Sub F(Of T1 As IA, T2 As {IA, INotifyCompletion}, T3 As IB, T4 As {T1, INotifyCompletion}, T5 As T3, T6 As A, T7 As {A, INotifyCompletion}, T8 As B, T9 As {T6, INotifyCompletion}, T10 As T8)()
Await New Awaitable(Of T1)()
Await New Awaitable(Of T2)()
Await New Awaitable(Of T3)()
Await New Awaitable(Of T4)()
Await New Awaitable(Of T5)()
Await New Awaitable(Of T6)()
Await New Awaitable(Of T7)()
Await New Awaitable(Of T8)()
Await New Awaitable(Of T9)()
Await New Awaitable(Of T10)()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929})
compilation.AssertTheseDiagnostics(
<expected>
BC37056: 'T1' does not implement 'INotifyCompletion'.
Await New Awaitable(Of T1)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37056: 'T6' does not implement 'INotifyCompletion'.
Await New Awaitable(Of T6)()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
''' <summary>
''' Should call ICriticalNotifyCompletion.UnsafeOnCompleted
''' if the awaiter type implements ICriticalNotifyCompletion.
''' </summary>
<Fact()>
Public Sub AwaiterImplementsICriticalNotifyCompletion_Constraint()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class Awaitable(Of T)
Friend Function GetAwaiter() As T
Return Nothing
End Function
End Class
Class A
Implements INotifyCompletion
Private Sub OnCompleted(a As Action) Implements INotifyCompletion.OnCompleted
End Sub
Friend ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
Friend Function GetResult() As Object
Return Nothing
End Function
End Class
Class B
Inherits A
Implements ICriticalNotifyCompletion
Private Sub UnsafeOnCompleted(a As Action) Implements ICriticalNotifyCompletion.UnsafeOnCompleted
End Sub
End Class
Module M
Async Sub F(Of T1 As A, T2 As {A, ICriticalNotifyCompletion}, T3 As B, T4 As T1, T5 As T2, T6 As {T1, ICriticalNotifyCompletion})()
Await New Awaitable(Of T1)()
Await New Awaitable(Of T2)()
Await New Awaitable(Of T3)()
Await New Awaitable(Of T4)()
Await New Awaitable(Of T5)()
Await New Awaitable(Of T6)()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929})
Dim verifier = CompileAndVerify(compilation)
Dim actualIL = verifier.VisualizeIL("M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6).MoveNext()")
Dim calls = actualIL.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries).Where(Function(s) s.Contains("OnCompleted")).ToArray()
Assert.Equal(calls.Length, 6)
Assert.Equal(calls(0), <![CDATA[ IL_0058: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted(Of SM$T1, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T1, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(1), <![CDATA[ IL_00c7: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T2, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T2, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(2), <![CDATA[ IL_0136: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T3, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T3, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(3), <![CDATA[ IL_01a7: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted(Of SM$T4, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T4, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(4), <![CDATA[ IL_0219: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T5, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T5, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
Assert.Equal(calls(5), <![CDATA[ IL_028b: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of SM$T6, M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))(ByRef SM$T6, ByRef M.VB$StateMachine_0_F(Of SM$T1, SM$T2, SM$T3, SM$T4, SM$T5, SM$T6))"]]>.Value)
End Sub
<Fact()>
Public Sub Assignment()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Await (New MyTask(Of Integer))=1
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC30205: End of statement expected.
AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
Await (New MyTask(Of Integer))=1
~
</expected>)
End Sub
<Fact()>
Public Sub AwaitNothing()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Module Program
Async Sub Test2()
Await Nothing
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36933: Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.
AssertTheseDiagnostics(compilation,
<expected>
BC36933: Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.
Await Nothing
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AwaitInQuery()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Linq.Enumerable
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As T
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim y = From x In {1} Where x <> Await New MyTask(Of Integer)
Dim z = From x In {Await New MyTask(Of Integer)} Where x <> 0
Await New MyTask(Of Integer)
End Sub
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
' error BC36929: 'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36929: 'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.
Dim y = From x In {1} Where x <> Await New MyTask(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub MisplacedAsyncModifier()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Public Module Program1
Sub Main()
End Sub
Async Class Test1
End Class
Async Structure Test2
End Structure
Async Enum Test3
X
End Enum
Async Interface Test4
End Interface
Class Test5
Private Async Test6 As Object
Async Property Test7 As Object
Async Event Test8(x As Object)
Async Sub Test9(ByRef x As Integer)
Await Task.Delay(x)
Dim Async Test10 As Object
End Sub
End Class
Async Delegate Sub Test11()
Async Declare Sub Test12 Lib "ddd" ()
Interface I1
Async Sub Test13()
End Interface
Enum E1
Async Test14
End Enum
Structure S1
Async Sub Test15()
Await Task.Delay(1)
Async Test16 As Object
End Sub
End Structure
Async Iterator Function Test17() As Object
End Function
End Module
Async Module Program2
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30461: Classes cannot be declared 'Async'.
Async Class Test1
~~~~~
BC30395: 'Async' is not valid on a Structure declaration.
Async Structure Test2
~~~~~
BC30396: 'Async' is not valid on an Enum declaration.
Async Enum Test3
~~~~~
BC30397: 'Async' is not valid on an Interface declaration.
Async Interface Test4
~~~~~
BC30235: 'Async' is not valid on a member variable declaration.
Private Async Test6 As Object
~~~~~
BC30639: Properties cannot be declared 'Async'.
Async Property Test7 As Object
~~~~~
BC30243: 'Async' is not valid on an event declaration.
Async Event Test8(x As Object)
~~~~~
BC36926: Async methods cannot have ByRef parameters.
Async Sub Test9(ByRef x As Integer)
~~~~~~~~~~~~~~~~~~
BC30247: 'Async' is not valid on a local variable declaration.
Dim Async Test10 As Object
~~~~~
BC42024: Unused local variable: 'Test10'.
Dim Async Test10 As Object
~~~~~~
BC30385: 'Async' is not valid on a Delegate declaration.
Async Delegate Sub Test11()
~~~~~
BC30244: 'Async' is not valid on a Declare.
Async Declare Sub Test12 Lib "ddd" ()
~~~~~
BC30270: 'Async' is not valid on an interface method declaration.
Async Sub Test13()
~~~~~
BC30205: End of statement expected.
Async Test14
~~~~~~
BC30247: 'Async' is not valid on a local variable declaration.
Async Test16 As Object
~~~~~
BC42024: Unused local variable: 'Test16'.
Async Test16 As Object
~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Async Iterator Function Test17() As Object
~~~~~
BC31052: Modules cannot be declared 'Async'.
Async Module Program2
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ReferToReturnVariable()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Test0()
Dim x = Test0
Await Task.Delay(1)
End Sub
Async Function Test1() As Task
Dim x = Test1
Await Task.Delay(1)
End Function
Async Function Test2() As Task(Of Integer)
Dim x = Test2
Await Task.Delay(1)
End Function
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Dim x = Test0
~~~~~
BC36946: The implicit return variable of an Iterator or Async method cannot be accessed.
Dim x = Test1
~~~~~
BC36946: The implicit return variable of an Iterator or Async method cannot be accessed.
Dim x = Test2
~~~~~
BC42105: Function 'Test2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ReturnStatements()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Test0()
Await Task.Delay(1)
Dim x As Integer = 1
If x = 3 Then
Return Nothing ' 0
Else
Return
End If
End Sub
Async Function Test1() As Task
Await Task.Delay(1)
Dim x As Integer = 1
If x = 3 Then
Return Nothing ' 1
ElseIf x = 2 Then
Return ' 1
Else
Return Task.Delay(1)
End If
End Function
Async Function Test2() As Task
Await Task.Delay(2)
End Function
Async Function Test3() As Task(Of Integer)
Await Task.Delay(3)
Return 3
End Function
Async Function Test4() As Task(Of Integer)
Await Task.Delay(3)
Return Test3()
End Function
Async Function Test5() As Object
Await Task.Delay(3)
Return Nothing ' 5
End Function
Async Function Test6() As Task(Of Integer)
Await Task.Delay(6)
Return New Guid()
End Function
Sub Main()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
Return Nothing ' 0
~~~~~~~~~~~~~~
BC36952: 'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.
Return Nothing ' 1
~~~~~~~~~~~~~~
BC36952: 'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.
Return Task.Delay(1)
~~~~~~~~~~~~~~~~~~~~
BC37055: Since this is an async method, the return expression must be of type 'Integer' rather than 'Task(Of Integer)'.
Return Test3()
~~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Async Function Test5() As Object
~~~~~~
BC30311: Value of type 'Guid' cannot be converted to 'Integer'.
Return New Guid()
~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub Lambdas()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Delegate Function D1() As Object
Delegate Sub D2(ByRef x As Integer)
Sub Main()
Dim x00 = Async Sub()
Await Task.Delay(0)
End Sub
Dim x01 = Async Iterator Function() As Object
Return Nothing
End Function ' 1
Dim x02 = Async Function() As Object
Await Task.Delay(3)
Return Nothing ' 5
End Function '2
Dim x03 As D1 = Async Function()
Await Task.Delay(3)
Return Nothing ' 5
End Function '3
Dim x04 = Async Sub(ByRef x As Integer)
Await Task.Delay(0)
End Sub
Dim x05 As D2 = Async Sub(x)
Await Task.Delay(0)
End Sub
Dim x06 As D2 = Async Sub(ByRef x)
Await Task.Delay(0)
End Sub
Dim x07 = Async Iterator Function() As Object
Await Task.Delay(0)
Return Nothing
End Function ' 4
Dim x08 = Sub()
Await Task.Delay(0) ' x08
End Sub
Dim x09 = Async Sub()
Await Task.Delay(0)
Dim x10 = Sub()
Await Task.Delay(0) ' x10
End Sub
End Sub
Dim x11 = Async Function()
Await Task.Delay(0)
Dim x As Integer = 0
If x = 0 Then
Return CByte(1)
Else
Return 1
End If
End Function ' 5
Dim x12 As Func(Of Task(Of Integer)) = x11
Dim x13 As Func(Of Task(Of Byte)) = x11
Dim x14 = Async Function() Await New Task(Of Byte)(Function() 1)
x12 = x14
x13 = x14
Dim x15 = Async Function()
Await Task.Delay(0)
End Function ' 6
Dim x16 As Func(Of Task) = x15
Dim x17 As Func(Of Integer) = x15
Dim x18 = Async Function()
Await Task.Delay(0)
Return
End Function ' 7
x16 = x18
x17 = x18
Dim x19 = Async Function()
Await Task.Delay(0)
Dim x As Integer = 0
If x = 0 Then
Return ' x19
Else
Return 1
End If
End Function ' 8
Dim x20 As Func(Of Object) = Async Function()
Await Task.Delay(0)
End Function ' 9
Dim x21 As Func(Of Object) = Async Function() Await New Task(Of Byte)(Function() 1)
Dim x22 As Func(Of Object) = Async Function()
Await Task.Delay(0)
Return 1
End Function ' 10
'Dim x23 As Action = Async Function() ' Expected BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
' Await Task.Delay(0)
' End Function ' 11
'Dim x24 As Action = Async Function() ' Expected BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
' Await Task.Delay(0)
' Return 1
' End Function ' 12
Dim x25 As Func(Of Task) = Async Function()
Await Task.Delay(0)
End Function ' 12
Dim x26 As Func(Of Task) = Async Function() Await New Task(Of Byte)(Function() 1)
Dim x27 As Func(Of Task) = Async Function()
Await Task.Delay(0)
Return 1
End Function ' 13
'Dim x28 = Async Overridable Sub()
' Await Task.Delay(0)
' End Sub
'Dim x29 = Async Iterator Overridable Sub()
' Await Task.Delay(0)
' End Sub
Dim x30 = Overridable Sub()
End Sub ' x30
'Dim x31 = Async Main
End Sub ' Main
Async Sub Test()
Await Task.Delay(0)
Dim x04 = Sub(ByRef x As Integer)
End Sub
End Sub
Sub Test2()
Dim x40 = Async Iterator Function() 1
Dim x41 = Async Iterator Function()
Yield 1
End Function ' 14
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x01 = Async Iterator Function() As Object
~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x02 = Async Function() As Object
~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x03 As D1 = Async Function()
~~~~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim x04 = Async Sub(ByRef x As Integer)
~~~~~~~~~~~~~~~~~~
BC36670: Nested sub does not have a signature that is compatible with delegate 'Delegate Sub Program.D2(ByRef x As Integer)'.
Dim x05 As D2 = Async Sub(x)
~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim x06 As D2 = Async Sub(ByRef x)
~~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x07 = Async Iterator Function() As Object
~~~~~
BC37059: 'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.
Await Task.Delay(0) ' x08
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(0) ' x08
~~~~~~~~~~~~~~
BC37059: 'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.
Await Task.Delay(0) ' x10
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(0) ' x10
~~~~~~~~~~~~~~
BC30311: Value of type 'Function <generated method>() As Task(Of Integer)' cannot be converted to 'Func(Of Task(Of Byte))'.
Dim x13 As Func(Of Task(Of Byte)) = x11
~~~
BC30311: Value of type 'Function <generated method>() As Task(Of Byte)' cannot be converted to 'Func(Of Task(Of Integer))'.
x12 = x14
~~~
BC30311: Value of type 'Function <generated method>() As Task' cannot be converted to 'Func(Of Integer)'.
Dim x17 As Func(Of Integer) = x15
~~~
BC30311: Value of type 'Function <generated method>() As Task' cannot be converted to 'Func(Of Integer)'.
x17 = x18
~~~
BC30654: 'Return' statement in a Function, Get, or Operator must return a value.
Return ' x19
~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x20 As Func(Of Object) = Async Function()
~~~~~~~~~~~~~~~~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function ' 9
~~~~~~~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x21 As Func(Of Object) = Async Function() Await New Task(Of Byte)(Function() 1)
~~~~~~~~~~~~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim x22 As Func(Of Object) = Async Function()
~~~~~~~~~~~~~~~~
BC30201: Expression expected.
Dim x30 = Overridable Sub()
~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End Sub ' Main
~~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x40 = Async Iterator Function() 1
~~~~~
BC36947: Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.
Dim x40 = Async Iterator Function() 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36936: 'Async' and 'Iterator' modifiers cannot be used together.
Dim x41 = Async Iterator Function()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub LambdaRelaxation()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x = CandidateMethod(Async Function()
Await Task.Delay(1)
End Function)
End Sub
Function CandidateMethod(f As Func(Of Task)) As Object
System.Console.WriteLine("CandidateMethod(f As Func(Of Task)) As Object")
Return Nothing
End Function
Sub CandidateMethod(f As Func(Of Task(Of Integer)))
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Double)))
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
CandidateMethod(f As Func(Of Task)) As Object
]]>).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub MissingTypes()
Dim source =
<compilation name="MissingTaskTypes">
<file name="a.vb">
<![CDATA[
Imports System
Class Program
Shared Sub Main()
Dim x = Async Function()
End Function
Dim y = Async Function() 1
Dim z = Async Function()
return 1
End Function
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v20}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31091: Import of type 'Task' from assembly or module 'MissingTaskTypes.exe' failed.
Dim x = Async Function()
~~~~~~~~~~~~~~~~~
BC31091: Import of type 'Task(Of )' from assembly or module 'MissingTaskTypes.exe' failed.
Dim y = Async Function() 1
~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'Task(Of )' from assembly or module 'MissingTaskTypes.exe' failed.
Dim z = Async Function()
~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub IllegalAwait()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Await Task.Delay(1)
End Sub
Function Main2() As Integer
Await Task.Delay(2)
Return 1
End Function
Dim x = Await Task.Delay(3)
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37058: 'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.
Await Task.Delay(1)
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(1)
~~~~~~~~~~~~~
BC37057: 'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of Integer)'.
Await Task.Delay(2)
~~~~~
BC30800: Method arguments must be enclosed in parentheses.
Await Task.Delay(2)
~~~~~~~~~~~~~
BC36937: 'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.
Dim x = Await Task.Delay(3)
~~~~~
BC30205: End of statement expected.
Dim x = Await Task.Delay(3)
~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_UnobservedAwaitableExpression()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Namespace Windows.Foundation
public interface IAsyncAction
End Interface
public interface IAsyncActionWithProgress(Of T)
End Interface
public interface IAsyncOperation(Of T)
End Interface
public interface IAsyncOperationWithProgress(Of T, S)
End Interface
End Namespace
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T) With {.m_Task = Me}
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted() As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Sub GetResult()
Throw New NotImplementedException()
End Sub
End Structure
Module Program
Sub Main()
End Sub
Interface AsyncAction
Inherits Windows.Foundation.IAsyncAction
End Interface
Function M1() As AsyncAction
Return Nothing
End Function
Interface AsyncActionWithProgress
Inherits Windows.Foundation.IAsyncActionWithProgress(Of Integer)
End Interface
Function M2() As AsyncActionWithProgress
Return Nothing
End Function
Interface AsyncOperation
Inherits Windows.Foundation.IAsyncOperation(Of Integer)
End Interface
Function M3() As AsyncOperation
Return Nothing
End Function
Interface AsyncOperationWithProgress
Inherits Windows.Foundation.IAsyncOperationWithProgress(Of Integer, Integer)
End Interface
Function M4() As AsyncOperationWithProgress
Return Nothing
End Function
Async Sub M5()
Await Task.Delay(1)
End Sub
Async Function M6() As Task
Await Task.Delay(1)
End Function
Async Function M7() As Task(Of Integer)
Await Task.Delay(1)
Return 1
End Function
Function M8() As Object
Return Nothing
End Function
Function M9() As MyTask(Of Integer)
Return Nothing
End Function
Function M10() As Task
Return Nothing
End Function
Function M11() As Task(Of Integer)
Return Nothing
End Function
Sub Test1()
Call M1()
M1() ' 1
Dim x1 = M1()
Call M2()
M2() ' 1
Dim x2 = M2()
Call M3()
M3() ' 1
Dim x3 = M3()
Call M4()
M4() ' 1
Dim x4 = M4()
Call M5()
M5()
Call M6()
M6() ' 1
Dim x6 = M6()
Call M7()
M7() ' 1
Dim x7 = M7()
Call M8()
M8()
Dim x8 = M8()
Call M9()
M9()
Dim x9 = M9()
Call M10()
M10()
Dim x10 = M10()
Call M11()
M11()
Dim x11 = M11()
End Sub
Async Sub Test2()
Await Task.Delay(1)
Call M1()
M1() ' 2
Dim x1 = M1()
Call M2()
M2() ' 2
Dim x2 = M2()
Call M3()
M3() ' 2
Dim x3 = M3()
Call M4()
M4() ' 2
Dim x4 = M4()
Call M5()
M5()
Call M6()
M6() ' 2
Dim x6 = M6()
Call M7()
M7() ' 2
Dim x7 = M7()
Call M8()
M8()
Dim x8 = M8()
Call M9()
M9() ' 2
Dim x9 = M9()
Call M10()
M10() ' 2
Dim x10 = M10()
Call M11()
M11() ' 2
Dim x11 = M11()
End Sub
Async Function Test3() As Task
Await Task.Delay(1)
Call M1()
M1() ' 3
Dim x1 = M1()
Call M2()
M2() ' 3
Dim x2 = M2()
Call M3()
M3() ' 3
Dim x3 = M3()
Call M4()
M4() ' 3
Dim x4 = M4()
Call M5()
M5()
Call M6()
M6() ' 3
Dim x6 = M6()
Call M7()
M7() ' 3
Dim x7 = M7()
Call M8()
M8()
Dim x8 = M8()
Call M9()
M9() ' 3
Dim x9 = M9()
Call M10()
M10() ' 3
Dim x10 = M10()
Call M11()
M11() ' 3
Dim x11 = M11()
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M1() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M2() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M3() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M4() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M6() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M7() ' 1
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M1() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M2() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M3() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M4() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M6() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M7() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M9() ' 2
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M10() ' 2
~~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M11() ' 2
~~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M1() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M2() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M3() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M4() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M6() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M7() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M9() ' 3
~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M10() ' 3
~~~~~
BC42358: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.
M11() ' 3
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_LoopControlMustNotAwait()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Dim array() As Integer
Async Sub Test1()
For x As Integer = Test3(Await Test2()) To 10
Next
For array(Test3(Await Test2())) = 0 To 10 ' 1
Next
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 1
Next
For Each array(Test4(Async Function()
Await Test2()
End Function)) In {1, 2, 3} ' 1
Next
End Sub
Async Function Test2() As Task(Of Integer)
For y As Integer = Test3(Await Test2()) To 10
Next
For array(Test3(Await Test2())) = 0 To 10 ' 2
Next
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 2
Next
For Each array(Test4(Async Function()
Await Test2()
End Function)) In {1, 2, 3} ' 2
Next
Return 2
End Function
Function Test3(x As Integer) As Integer
Return x
End Function
Function Test4(x As Func(Of Task)) As Integer
Return 0
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37060: Loop control variable cannot include an 'Await'.
For array(Test3(Await Test2())) = 0 To 10 ' 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37060: Loop control variable cannot include an 'Await'.
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37060: Loop control variable cannot include an 'Await'.
For array(Test3(Await Test2())) = 0 To 10 ' 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37060: Loop control variable cannot include an 'Await'.
For Each array(Test3(Await Test2())) In {1, 2, 3} ' 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_BadStaticInitializerInResumable()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
Static x As Integer
x = 0
Static y As Integer = 0
Static a, b As Integer
a = 0
b = 1
Static c As New Integer()
Static d, e As New Integer()
End Sub
Async Function Test2() As Task(Of Integer)
Await Task.Delay(1)
Static u As Integer
u = 0
Static v As Integer = 0
Static f, g As Integer
f = 0
g = 1
Static h As New Integer()
Static i, j As New Integer()
Return 2
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static x As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static y As Integer = 0
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static a, b As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static a, b As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static c As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static d, e As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static d, e As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static u As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static v As Integer = 0
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static f, g As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static f, g As Integer
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static h As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static i, j As New Integer()
~
BC36955: Static variables cannot appear inside Async or Iterator methods.
Static i, j As New Integer()
~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_RestrictedResumableType1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Delegate Sub D1(x As ArgIterator)
Delegate Sub D2(ByRef x As ArgIterator)
Delegate Sub D3(ByRef x As ArgIterator())
Delegate Sub D4(x As ArgIterator())
Sub Main()
Dim x = Async Sub(a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim y = Async Sub(ByRef a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim z = Async Sub(ByRef a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim u = Async Sub(a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim x1 As D1 = Async Sub(a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim y1 As D2 = Async Sub(ByRef a As ArgIterator)
Await Task.Delay(1)
End Sub
Dim z1 As D3 = Async Sub(ByRef a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim u1 As D4 = Async Sub(a As ArgIterator())
Await Task.Delay(1)
End Sub
Dim x2 As D1 = Async Sub(a)
Await Task.Delay(1)
End Sub
Dim y2 As D2 = Async Sub(ByRef a)
Await Task.Delay(1)
End Sub
Dim z2 As D3 = Async Sub(ByRef a)
Await Task.Delay(1)
End Sub
Dim u2 As D4 = Async Sub(a)
Await Task.Delay(1)
End Sub
End Sub
Async Sub Test1(x As ArgIterator)
Await Task.Delay(1)
End Sub
Async Sub Test2(ByRef x As ArgIterator)
Await Task.Delay(1)
End Sub
Async Sub Test3(x As ArgIterator())
Await Task.Delay(1)
End Sub
Async Sub Test4(ByRef x As ArgIterator())
Await Task.Delay(1)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Delegate Sub D2(ByRef x As ArgIterator)
~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Delegate Sub D3(ByRef x As ArgIterator())
~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Delegate Sub D4(x As ArgIterator())
~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim x = Async Sub(a As ArgIterator)
~~~~~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Dim x = Async Sub(a As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim y = Async Sub(ByRef a As ArgIterator)
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim y = Async Sub(ByRef a As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim z = Async Sub(ByRef a As ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim u = Async Sub(a As ArgIterator())
~~~~~~~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Dim x1 As D1 = Async Sub(a As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim y1 As D2 = Async Sub(ByRef a As ArgIterator)
~~~~~~~~~~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim z1 As D3 = Async Sub(ByRef a As ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim u1 As D4 = Async Sub(a As ArgIterator())
~~~~~~~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Dim x2 As D1 = Async Sub(a)
~
BC36926: Async methods cannot have ByRef parameters.
Dim y2 As D2 = Async Sub(ByRef a)
~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Dim z2 As D3 = Async Sub(ByRef a)
~~~~~~~
BC36932: 'ArgIterator' cannot be used as a parameter type for an Iterator or Async method.
Async Sub Test1(x As ArgIterator)
~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Async Sub Test2(ByRef x As ArgIterator)
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Async Sub Test3(x As ArgIterator())
~~~~~~~~~~~~~
BC36926: Async methods cannot have ByRef parameters.
Async Sub Test4(ByRef x As ArgIterator())
~~~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_ConstructorAsync_and_ERRID_PartialMethodsMustNotBeAsync1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Class Test
Async Sub New()
End Sub
Shared Async Sub New()
End Sub
Partial Private Async Sub Part()
End Sub
Private Async Sub Part()
Await Task.Delay(1)
End Sub
End Class
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36950: Constructor must not have the 'Async' modifier.
Async Sub New()
~~~~~
BC36950: Constructor must not have the 'Async' modifier.
Shared Async Sub New()
~~~~~
BC36935: 'Part' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Part()
~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_ResumablesCannotContainOnError()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
On Error GoTo 0 ' 1
Resume Next ' 1
End Sub
Iterator Function Test2() As System.Collections.Generic.IEnumerable(Of Integer)
On Error GoTo 0 ' 2
Resume Next ' 2
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
On Error GoTo 0 ' 1
~~~~~~~~~~~~~~~
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
Resume Next ' 1
~~~~~~~~~~~
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
On Error GoTo 0 ' 2
~~~~~~~~~~~~~~~
BC36956: 'On Error' and 'Resume' cannot appear inside async or iterator methods.
Resume Next ' 2
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_ResumableLambdaInExpressionTree()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Linq.Expressions
Module Program
Sub Main()
Dim x As Expression(Of Action) = Async Sub() Await Task.Delay(1)
Dim y As Expression(Of Func(Of System.Collections.Generic.IEnumerable(Of Integer))) = Iterator Function()
End Function
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37050: Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.
Dim x As Expression(Of Action) = Async Sub() Await Task.Delay(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC37050: Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.
Dim y As Expression(Of Func(Of System.Collections.Generic.IEnumerable(Of Integer))) = Iterator Function()
~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_CannotLiftRestrictedTypeResumable1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
Dim a1 As ArgIterator
Dim b1 As ArgIterator = Nothing
Dim c1 As ArgIterator, d1 As ArgIterator = Nothing
Dim e1 As New ArgIterator(Nothing)
Dim f1, g1 As New ArgIterator(Nothing)
Dim h1 = New ArgIterator()
a1=Nothing
c1=Nothing
End Sub
Iterator Function Test2() As System.Collections.Generic.IEnumerable(Of Integer)
Dim a2 As ArgIterator
Dim b2 As ArgIterator = Nothing
Dim c2 As ArgIterator, d2 As ArgIterator = Nothing
Dim e2 As New ArgIterator(Nothing)
Dim f2, g2 As New ArgIterator(Nothing)
Dim h2 = New ArgIterator()
a2=Nothing
c2=Nothing
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim a1 As ArgIterator
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim b1 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c1 As ArgIterator, d1 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c1 As ArgIterator, d1 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim e1 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim f1, g1 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim h1 = New ArgIterator()
~~~~~~~~~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim a2 As ArgIterator
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim b2 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c2 As ArgIterator, d2 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim c2 As ArgIterator, d2 As ArgIterator = Nothing
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim e2 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim f2, g2 As New ArgIterator(Nothing)
~~~~~~~~~~~
BC37052: Variable of restricted type 'ArgIterator' cannot be declared in an Async or Iterator method.
Dim h2 = New ArgIterator()
~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_BadAwaitInTryHandler()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x = Async Sub()
Try
Await Test2() ' Try 1
Catch ex As Exception When Await Test2() > 1 ' Filter 1
Catch
Await Test2() ' Catch 1
Finally
Await Test2() ' Finally 1
End Try
SyncLock New Lock(Await Test2()) ' SyncLock 1
Await Test2() ' SyncLock 1
End SyncLock
End Sub
End Sub
Async Sub Test1()
Try
Await Test2() ' Try 2
Catch ex As Exception When Await Test2() > 1 ' Filter 2
Catch
Await Test2() ' Catch 2
Finally
Await Test2() ' Finally 2
End Try
SyncLock New Lock(Await Test2()) ' SyncLock 2
Await Test2() ' SyncLock 2
End SyncLock
End Sub
Async Function Test2() As Task(Of Integer)
Await Task.Delay(1)
Return 1
End Function
Class Lock
Sub New(x As Integer)
End Sub
End Class
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Catch ex As Exception When Await Test2() > 1 ' Filter 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Catch 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Finally 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
SyncLock New Lock(Await Test2()) ' SyncLock 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' SyncLock 1
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Catch ex As Exception When Await Test2() > 1 ' Filter 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Catch 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' Finally 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
SyncLock New Lock(Await Test2()) ' SyncLock 2
~~~~~~~~~~~~~
BC36943: 'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.
Await Test2() ' SyncLock 2
~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncLacksAwaits()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x = Async Sub()
End Sub
End Sub
Async Sub Test1()
End Sub
Async Function Test2() As Task(Of Integer)
Return 1
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42356: This async method lacks 'Await' operators and so 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.
Dim x = Async Sub()
~~~
BC42356: This async method lacks 'Await' operators and so 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.
Async Sub Test1()
~~~~~
BC42356: This async method lacks 'Await' operators and so 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.
Async Function Test2() As Task(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_UnobservedAwaitableDelegate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
Dim x As Action
x = AddressOf Test1
x = AddressOf Test2
x = AddressOf Test3
x = AddressOf Test4
x = AddressOf Test5
x = New Action(AddressOf Test2)
x = CType(AddressOf Test2, Action)
x = DirectCast(AddressOf Test2, Action)
x = TryCast(AddressOf Test2, Action)
x = Async Sub()
Await Task.Delay(1)
End Sub
x = Async Function()
Await Task.Delay(1)
Return 1
End Function
x = Async Function() As Task(Of Integer)
Await Task.Delay(1)
Return 1
End Function
x = Async Function()
Await Task.Delay(1)
End Function
x = Async Function() As Task
Await Task.Delay(1)
End Function
x = New Action(Async Function()
Await Task.Delay(1)
End Function)
x = CType(Async Function()
Await Task.Delay(1)
End Function, Action)
x = DirectCast(Async Function()
Await Task.Delay(1)
End Function, Action)
x = TryCast(Async Function()
Await Task.Delay(1)
End Function, Action)
x = Function() As Task(Of Integer)
Return Nothing
End Function
x = Function() As Task
Return Nothing
End Function
Dim y = Async Function()
Await Task.Delay(1)
End Function
x = y
End Sub
Async Sub Test1() Handles z.y
Await Task.Delay(1)
End Sub
Async Function Test2() As Task(Of Integer) Handles z.y
Await Task.Delay(1)
Return 1
End Function
Async Function Test3() As Task Handles z.y
Await Task.Delay(1)
End Function
WithEvents z As CWithEvents
Class CWithEvents
Public Event y As Action
End Class
Function Test4() As Task(Of Integer) Handles z.y
Return Nothing
End Function
Function Test5() As Task Handles z.y
Return Nothing
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = AddressOf Test2
~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = AddressOf Test3
~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function()
~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function() As Task(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function()
~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
x = Async Function() As Task
~~~~~~~~~~~~~~~~~~~~~~~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
Async Function Test2() As Task(Of Integer) Handles z.y
~~~
BC42359: The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.
Async Function Test3() As Task Handles z.y
~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SecurityCriticalAsyncInClassOrStruct_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
<Security.SecurityCritical()>
Module Program
Sub Main()
End Sub
Async Sub Test1()
Await Task.Delay(1)
End Sub
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Class C1
Async Sub Test3()
Await Task.Delay(1)
End Sub
Iterator Function Test4() As Collections.Generic.IEnumerable(Of Integer)
End Function
End Class
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Async Sub Test1()
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Async Sub Test3()
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Iterator Function Test4() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SecurityCriticalAsyncInClassOrStruct_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
End Module
<Security.SecuritySafeCritical()>
Class C2
Private Async Sub Test5()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test5()
End Sub
Iterator Function Test6() As Collections.Generic.IEnumerable(Of Integer)
End Function
End Class
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Private Async Sub Test5()
~~~~~
BC36935: 'Test5' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test5()
~~~~~
BC31005: Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.
Iterator Function Test6() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SecurityCriticalAsync()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Sub Main()
End Sub
<Security.SecurityCritical()> ' 1
Private Async Sub Test1()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test1()
End Sub
<Security.SecuritySafeCritical()> ' 2
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Private Async Sub Test3()
Await Task.Delay(1)
End Sub
<Security.SecurityCritical()> ' 3
Partial Private Sub Test3()
End Sub
<Security.SecurityCritical()> ' 4
Partial Private Async Sub Test4()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC31006: Security attribute 'SecurityCritical' cannot be applied to an Async or Iterator method.
<Security.SecurityCritical()> ' 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36935: 'Test1' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test1()
~~~~~
BC31006: Security attribute 'SecuritySafeCritical' cannot be applied to an Async or Iterator method.
<Security.SecuritySafeCritical()> ' 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31006: Security attribute 'SecurityCritical' cannot be applied to an Async or Iterator method.
<Security.SecurityCritical()> ' 3
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36935: 'Test4' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test4()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_DllImportOnResumableMethod()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.InteropServices
Module Program
Sub Main()
End Sub
<DllImport("Test1")>
Private Async Sub Test1()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test1()
End Sub
<DllImport("Test2")>
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Private Async Sub Test3()
Await Task.Delay(1)
End Sub
<DllImport("Test3")>
Partial Private Sub Test3()
End Sub
<DllImport("Test4")>
Partial Private Async Sub Test4()
End Sub
<DllImport("Test5")>
Partial Private Sub Test5()
End Sub
Private Sub Test5()
Return
End Sub
<DllImport("Test6")>
Partial Private Sub Test6()
End Sub
Private Sub Test6()
End Sub
<DllImport("Test7")>
Partial Private Sub Test7()
End Sub
Private Async Sub Test7()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Private Async Sub Test1()
~~~~~
BC36935: 'Test1' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test1()
~~~~~
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
~~~~~
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Private Async Sub Test3()
~~~~~
BC36935: 'Test4' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test4()
~~~~~
BC31522: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.
<DllImport("Test5")>
~~~~~~~~~
BC37051: 'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.
Private Async Sub Test7()
~~~~~
BC42356: This async method lacks 'Await' operators and so 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.
Private Async Sub Test7()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_SynchronizedAsyncMethod()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Private Async Sub Test1()
Await Task.Delay(1)
End Sub
Partial Private Async Sub Test1()
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Iterator Function Test2() As Collections.Generic.IEnumerable(Of Integer)
End Function
Private Async Sub Test3()
Await Task.Delay(1)
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Partial Private Sub Test3()
End Sub
<MethodImpl(MethodImplOptions.Synchronized)>
Partial Private Async Sub Test4()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37054: 'MethodImplOptions.Synchronized' cannot be applied to an Async method.
Private Async Sub Test1()
~~~~~
BC36935: 'Test1' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test1()
~~~~~
BC37054: 'MethodImplOptions.Synchronized' cannot be applied to an Async method.
Private Async Sub Test3()
~~~~~
BC36935: 'Test4' cannot be declared 'Partial' because it has the 'Async' modifier.
Partial Private Async Sub Test4()
~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub ERRID_AsyncSubMain()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Async Sub Main()
'Await Task.Delay(1)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36934: The 'Main' method cannot be marked 'Async'.
Async Sub Main()
~~~~
BC42356: This async method lacks 'Await' operators and so 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.
Async Sub Main()
~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program1
Sub Main1()
' 1
Task.Factory.StartNew(Async Sub() ' 1
Await Task.Delay(1)
End Sub)
Task.Factory.StartNew((Async Sub() ' 1
Await Task.Delay(1)
End Sub))
' 2
Task.Run(Async Sub() ' 2
Await Task.Delay(1)
End Sub)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Task.Factory.StartNew(Async Sub() ' 1
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Task.Factory.StartNew((Async Sub() ' 1
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Task.Run(Async Sub() ' 2
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program2
Async Function f(ByVal i As Integer) As Task
Dim j As Integer = 2
Await taskrun(Sub()
Dim x = 5
Console.WriteLine(x + i + j)
End Sub)
' 3
Await taskrun(Async Sub() ' 3
Dim x = 6
Await Task.Delay(1)
End Sub)
Await taskrun((Async Sub() ' 3
Dim x = 6
Await Task.Delay(1)
End Sub))
Await taskrun(Async Function()
Dim x = 7
Await Task.Delay(1)
End Function)
Await taskrun(Async Function()
Dim x = 8
Await Task.Delay(1)
End Function)
End Function
Async Function taskrun(ByVal f As Func(Of Task)) As Task
Dim tt As Task(Of Task) = Task.Factory.StartNew(Of Task)(f)
Dim t As Task = Await tt
Await t
End Function
Async Function taskrun(ByVal f As Action) As task
Dim t As Task = Task.Factory.StartNew(f)
Await t
End Function
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Await taskrun(Async Sub() ' 3
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Await taskrun((Async Sub() ' 3
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program3
Sub Main3()
Dim t = Async Function()
Await Task.Yield()
Return "hello"
End Function()
TaskRun(Sub() Console.WriteLine("expected Action"))
TaskRun(Sub()
Console.WriteLine("expected Action")
End Sub)
' 4
TaskRun(Async Sub() Await Task.Delay(1)) ' 4
' 5
TaskRun(Async Sub() ' 5
Await Task.Delay(1)
End Sub)
TaskRun(Function() "expected Func<T>")
TaskRun(Function()
Return "expected Func<T>"
End Function)
TaskRun(Async Function()
Console.WriteLine("expected Func<Task>")
Await Task.Yield()
End Function)
TaskRun(Async Function() d(Await t, "expected Func<Task<T>>"))
TaskRun(Async Function()
Await Task.Yield()
Return "expected Func<Task<T>>"
End Function)
End Sub
Function d(Of T)(dummy As Object, x As T) As T
Return x
End Function
Sub TaskRun(f As Action)
Console.WriteLine("TaskRun: Action")
f()
Console.WriteLine()
End Sub
Sub TaskRun(f As Func(Of Task))
Console.WriteLine("TaskRun: Func<Task>")
f().Wait()
Console.WriteLine()
End Sub
Sub TaskRun(Of T)(f As Func(Of T))
Console.WriteLine("TaskRun: Func<T>")
Console.WriteLine(f())
Console.WriteLine()
End Sub
Sub TaskRun(Of T)(f As Func(Of Task(Of T)))
Console.WriteLine("TaskRun: Func<Task<T>>")
Console.WriteLine(f().Result)
Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
TaskRun(Async Sub() Await Task.Delay(1)) ' 4
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
TaskRun(Async Sub() ' 5
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_4()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program4
Function f(x As action) As Integer
Return 1
End Function
Function f(Of T)(x As Func(Of T)) As Integer
Return 2
End Function
Sub h(x As Action)
End Sub
Sub h(x As Func(Of Task))
End Sub
Sub Main4()
' 6
f(Async Sub() ' 6
Await Task.Yield()
End Sub)
' 7
Console.WriteLine(f(Async Sub() ' 7
Await Task.Yield()
End Sub))
' 8
h(Async Sub() ' 8
Await Task.Yield()
End Sub)
Dim s = ""
' 9
s.gg(Async Sub() ' 9
Await Task.Yield()
End Sub)
End Sub
<Extension()> Sub gg(this As String, x As Action)
End Sub
<Extension()> Sub gg(this As String, x As Func(Of Task))
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
f(Async Sub() ' 6
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
Console.WriteLine(f(Async Sub() ' 7
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
h(Async Sub() ' 8
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
s.gg(Async Sub() ' 9
~~~~~~~~~~~
]]></expected>)
End Sub
<Fact()>
Public Sub WRNID_AsyncSubCouldBeFunction_5()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Program
Sub Main()
End Sub
End Module
Module Program5
Async Function Test() As Task
Await Task.Yield()
' 10
CandidateMethod(Async Sub() ' 10
Await Task.Yield()
End Sub)
' 11
CandidateMethod(Async Sub() ' 11
Await Task.Yield()
End Sub)
' 12
CandidateMethod(Async Sub() ' 12
Console.WriteLine("fReturningTaskAsyncLambdaWithAwait")
Await Task.Yield()
End Sub)
' 13
CandidateMethod(Async Sub(i As Object) ' 13
Console.WriteLine("fTakingIntReturningTask")
Await Task.Yield()
End Sub)
End Function
Sub CandidateMethod()
Console.WriteLine("CandidateMethod()")
End Sub
Sub CandidateMethod(i As Integer)
Console.WriteLine("CandidateMethod(integer) passed {0}", i)
End Sub
Sub CandidateMethod(d As Double)
Console.WriteLine("CandidateMethod(double) passed {0}", d)
End Sub
Sub CandidateMethod(o As Object)
Console.WriteLine("CandidateMethod(object) passed {0}", o)
End Sub
Sub CandidateMethod(d As System.Delegate)
Console.WriteLine("CandidateMethod(System.Delegate) passed {0}", d)
End Sub
Sub CandidateMethod(a As action)
a()
Console.WriteLine("CandidateMethod(Action) passed {0}", a)
End Sub
Sub CandidateMethod(f As Func(Of Integer))
Console.WriteLine("CandidateMethod(Func(Of integer)) func returns {0}", f())
End Sub
Sub CandidateMethod(f As Func(Of Double))
Console.WriteLine("CandidateMethod(Func(Of double)) func returns {0}", f())
End Sub
Sub CandidateMethod(f As Func(Of Task))
f().Wait()
Console.WriteLine("CandidateMethod(Func(Of Task)) passed {0}", f)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Integer)))
Console.WriteLine("CandidateMethod(Func(Of Task(Of integer))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Double)))
Console.WriteLine("CandidateMethod(Func(Of Task(Of (Of double))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Integer, Task))
f(1).Wait()
Console.WriteLine("CandidateMethod(Func(Of integer,Task)) passed {0}", f)
End Sub
Sub CandidateMethod(f As Func(Of Integer, Task(Of Integer)))
Console.WriteLine("CandidateMethod(Func(Of integer,Task(Of integer))) task returns {0}", f(1).Result)
End Sub
Sub CandidateMethod(f As Func(Of Integer, Task(Of Double)))
Console.WriteLine("CandidateMethod(Func(Of integer,Task(Of double))) task returns {0}", f(1).Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Object)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of object))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of String)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of sting))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Integer?)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of integer?))) task returns {0}", f().Result)
End Sub
Sub CandidateMethod(f As Func(Of Task(Of Double?)))
Console.WriteLine("CandidateMethod(f As Func(Of Task(Of double?))) task returns {0}", f().Result)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub() ' 10
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub() ' 11
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub() ' 12
~~~~~~~~~~~
BC42357: Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.
CandidateMethod(Async Sub(i As Object) ' 13
~~~~~~~~~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact(), WorkItem(547087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547087")>
Public Sub Bug17912_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main(args As String())
End Sub
Async Function Test0() As Task
Dim x as Await
Dim y As [Await]
Await Task.Delay(1)
End Function
Async Function await() As Task
Await Task.Delay(1)
End Function
Async Sub Test1(await As Integer)
Await Task.Delay(1)
End Sub
Async Function Test2(x As Await) As Task
Await Task.Delay(1)
End Function
Async Function Test3() As Await
Await Task.Delay(1)
End Function
End Module
Class Await
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC42024: Unused local variable: 'x'.
Dim x as Await
~
BC30183: Keyword is not valid as an identifier.
Dim x as Await
~~~~~
BC42024: Unused local variable: 'y'.
Dim y As [Await]
~
BC30183: Keyword is not valid as an identifier.
Async Function await() As Task
~~~~~
BC30183: Keyword is not valid as an identifier.
Async Sub Test1(await As Integer)
~~~~~
BC30183: Keyword is not valid as an identifier.
Async Function Test2(x As Await) As Task
~~~~~
BC30183: Keyword is not valid as an identifier.
Async Function Test3() As Await
~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Async Function Test3() As Await
~~~~~
BC42105: Function 'Test3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(547087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547087")>
Public Sub Bug17912_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Class Await
End Class
Module Module2
Sub Main(args As String())
End Sub
Async Function [await]() As Task
Await Task.Delay(1)
End Function
Async Sub Test1([await] As Integer)
Await Task.Delay(1)
End Sub
Async Function Test2(x As [Await]) As Task
Await Task.Delay(1)
End Function
Async Function Test3() As [Await]
Await Task.Delay(1)
End Function
End Module
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Async Function Test3() As [Await]
~~~~~~~
BC42105: Function 'Test3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(547087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547087")>
Public Sub Bug17912_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main(args As String())
Dim test0 = Async Function() As Task
Dim x As Await
Dim y As [Await]
Await Task.Delay(1)
End Function
Dim test1 = Async Sub (await As Integer)
Await Task.Delay(1)
End Sub
Dim test2 = Async Function (x As Await) As Task
Await Task.Delay(1)
End Function
Dim test3 = Async Function() As Await
Await Task.Delay(1)
End Function ' 1
Dim test4 = Async Sub (await As Integer) Await Task.Delay(1)
Dim test5 = Async Sub (await As Integer) Await GetTask()
Dim test11 = Async Sub([await] As Integer)
Await Task.Delay(1)
End Sub
Dim test21 = Async Function(x As [Await]) As Task
Await Task.Delay(1)
End Function
Dim test31 = Async Function() As Task(Of [Await])
Await Task.Delay(1)
End Function ' 2
Dim test41 = Async Sub([await] As Integer) Await Task.Delay(1)
Dim test51 = Async Sub([await] As Integer) Await GetTask()
End Sub
Function GetTask() As Task(Of Integer)
Return Nothing
End Function
End Module
Class Await
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC42024: Unused local variable: 'x'.
Dim x As Await
~
BC30183: Keyword is not valid as an identifier.
Dim x As Await
~~~~~
BC42024: Unused local variable: 'y'.
Dim y As [Await]
~
BC30183: Keyword is not valid as an identifier.
Dim test1 = Async Sub (await As Integer)
~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test2 = Async Function (x As Await) As Task
~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test3 = Async Function() As Await
~~~~~
BC36945: The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).
Dim test3 = Async Function() As Await
~~~~~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function ' 1
~~~~~~~~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test4 = Async Sub (await As Integer) Await Task.Delay(1)
~~~~~
BC30183: Keyword is not valid as an identifier.
Dim test5 = Async Sub (await As Integer) Await GetTask()
~~~~~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function ' 2
~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact(), WorkItem(568948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568948")>
Public Sub Bug568948()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Public Module Module1
Public Sub Main()
goo()
End Sub
Public Async Sub Goo()
Dim AwaitableLambda1 = Async Function()
Await Task.Yield
Return New List(Of Test) From {New Test With {.Async = "test2", .Await = 2}, New Test With {.Async = "test3", .Await = 3}}
End Function
Dim Query = From x2 In Await AwaitableLambda1() Select New With {.async = x2, .b = Function(Await)
Return Await.Await + 1
End Function.Invoke(x2)}
'ANOTHER EXAMPLE FAILING WITH SAME ISSUE....
'
' Dim AwaitableLambda1 = Async Function()
' Await Task.Yield
' Return New List(Of Test) From {New Test With {.Async = "test2", .Await = 2}, New Test With {.Async = "test3", .Await = 3}}
' End Function
' Dim Query = From x2 In Await AwaitableLambda1() Select New With {.async = x2, .b = Function(Await)
' Return Await.Await + 1
' End Function.Invoke(.async)}
End Sub
End Module
Public Class Test
Public Property Await As Integer = 1
Public Property Async As String = "Test"
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, LatestVbReferences, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_Errors()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
<Obsolete("Do not use!", True)>
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
<Obsolete("Do not use!", True)>
Public Function GetResult() As T
Return Nothing
End Function
<Obsolete("Do not use!", True)>
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30668: 'Public Function GetAwaiter() As MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC30668: 'Public Function GetResult() As T' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC30668: 'Public ReadOnly Property IsCompleted As Boolean' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_Warnings()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
<Obsolete("Do not use!", False)>
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
<Obsolete("Do not use!", False)>
Public Function GetResult() As T
Return Nothing
End Function
<Obsolete("Do not use!", False)>
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC40000: 'Public Function GetAwaiter() As MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC40000: 'Public Function GetResult() As T' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
BC40000: 'Public ReadOnly Property IsCompleted As Boolean' is obsolete: 'Do not use!'.
Await Me
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_Interface()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
<Obsolete("Do not use!", True)>
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
Public Function GetResult() As T
Return Nothing
End Function
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30668: 'MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
~~~~~~~~~~~~~~~~~~~
BC30668: 'MyTaskAwaiter(Of T)' is obsolete: 'Do not use!'.
Return New MyTaskAwaiter(Of T)()
~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AsyncWithObsolete_InterfaceMethod()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Async Function Test() As Task
Await Me
End Function
End Class
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
<Obsolete("Do not use!", True)>
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
Public Function GetResult() As T
Return Nothing
End Function
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact()>
Public Sub Legacy_Async_Overload_Change_3()
Dim source =
<compilation>
<file name="a.vb">
<%= SemanticResourceUtil.Async_Overload_Change_3_vb %>
</file>
</compilation>
Dim warnings = New Dictionary(Of String, ReportDiagnostic)()
warnings.Add(MessageProvider.Instance.GetIdForErrorCode(42356), ReportDiagnostic.Suppress)
Dim compilation = CreateEmptyCompilationWithReferences(source,
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929},
TestOptions.ReleaseExe.WithSpecificDiagnosticOptions(New ReadOnlyDictionary(Of String, ReportDiagnostic)(warnings)))
CompileAndVerify(compilation, expectedOutput:="")
End Sub
<Fact(), WorkItem(1066694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066694")>
Public Sub Bug1066694()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main()
System.Console.WriteLine("Non-Async")
System.Console.WriteLine()
TestLocal()
System.Console.WriteLine()
System.Console.WriteLine("Async")
System.Console.WriteLine()
Task.WaitAll(TestLocalAsync())
End Sub
Sub TestLocal()
Dim l = New TestClass("Unchanged")
l.M1(l, Mutate(l))
System.Console.WriteLine(l.State)
End Sub
Async Function DummyAsync(x As Object) As Task(Of Object)
Return x
End Function
Async Function TestLocalAsync() As Task
Dim l = New TestClass("Unchanged")
l.M1(l, Await DummyAsync(Mutate(l)))
System.Console.WriteLine(l.State)
End Function
Function Mutate(ByRef x As TestClass) As Object
x = New TestClass("Changed")
Return x
End Function
End Module
Class TestClass
Private ReadOnly fld1 As String
Sub New(val As String)
fld1 = val
End Sub
Function State() As String
Return fld1
End Function
Sub M1(arg1 As TestClass, arg2 As Object)
System.Console.WriteLine(Me.State)
System.Console.WriteLine(arg1.State)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
Non-Async
Unchanged
Unchanged
Changed
Async
Unchanged
Unchanged
Changed
]]>)
End Sub
<Fact(), WorkItem(1068084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068084")>
Public Sub Bug1068084()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System.Threading.Tasks
Class Test
Async Sub F()
Await Task.Delay(0)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626}, TestOptions.ReleaseDll)
AssertTheseEmitDiagnostics(compilation,
<expected>
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError' is not defined.
Async Sub F()
~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError' is not defined.
Async Sub F()
~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(1021941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021941")>
Public Sub Bug1021941()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Interface IMoveable
Sub M1(x As Integer, y As Integer, z As Integer)
Function M2() As Integer
End Interface
Class Item
Implements IMoveable
Public Property Name As String
Public Sub M1(x As Integer, y As Integer, z As Integer) Implements IMoveable.M1
Console.WriteLine("M1 is called for item '{0}'", Me.Name)
End Sub
Public Function M2() As Integer Implements IMoveable.M2
Console.WriteLine("M2 is called for item '{0}'", Me.Name)
Return 0
End Function
End Class
Class Program
Shared Sub Main()
Dim item = New Item With {.Name = "Goo"}
Task.WaitAll(Shift(item))
End Sub
Shared Async Function Shift(Of T As {Class, IMoveable})(item As T) As Task(Of Integer)
item.M1(item.M2(), Await DummyAsync(), GetOffset(item))
Return 0
End Function
Shared Async Function DummyAsync() As Task(Of Integer)
Return 0
End Function
Shared Function GetOffset(Of T)(ByRef item As T) As Integer
item = DirectCast(DirectCast(New Item With {.Name = "Bar"}, IMoveable), T)
Return 0
End Function
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.DebugExe)
CompileAndVerify(compilation,
<![CDATA[
M2 is called for item 'Goo'
M1 is called for item 'Bar'
]]>)
End Sub
<Fact(), WorkItem(1173166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1173166"), WorkItem(2878, "https://github.com/dotnet/roslyn/issues/2878")>
Public Sub CompoundAssignment()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class Test
Private _field As UInteger
Shared Sub Main()
Dim t as New Test()
System.Console.WriteLine(t._field)
t.EventHandler(-1).Wait()
System.Console.WriteLine(t._field)
End Sub
Private Async Function EventHandler(args As Integer) As System.Threading.Tasks.Task
Await RunAsync(Async Function()
System.Console.WriteLine(args)
_field += CUInt(1)
End Function)
End Function
Private Async Function RunAsync(x As System.Func(Of System.Threading.Tasks.Task)) As System.Threading.Tasks.Task
Await x()
End Function
End Class
]]>
</file>
</compilation>
Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.DebugExe)
Dim expected As Xml.Linq.XCData = <![CDATA[
0
-1
1
]]>
CompileAndVerify(compilation, expected)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expected)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./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 | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.ModuleSymbolKey.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class ModuleSymbolKey
{
public static void Create(IModuleSymbol symbol, SymbolKeyWriter visitor)
=> visitor.WriteSymbolKey(symbol.ContainingSymbol);
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(ModuleSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})";
return default;
}
using var result = PooledArrayBuilder<IModuleSymbol>.GetInstance();
foreach (var assembly in containingSymbolResolution.OfType<IAssemblySymbol>())
{
// Don't check ModuleIds for equality because in practice, no-one uses them,
// and there is no way to set netmodule name programmatically using Roslyn
result.AddValuesIfNotNull(assembly.Modules);
}
return CreateResolution(result, $"({nameof(ModuleSymbolKey)} failed)", out failureReason);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class ModuleSymbolKey
{
public static void Create(IModuleSymbol symbol, SymbolKeyWriter visitor)
=> visitor.WriteSymbolKey(symbol.ContainingSymbol);
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(ModuleSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})";
return default;
}
using var result = PooledArrayBuilder<IModuleSymbol>.GetInstance();
foreach (var assembly in containingSymbolResolution.OfType<IAssemblySymbol>())
{
// Don't check ModuleIds for equality because in practice, no-one uses them,
// and there is no way to set netmodule name programmatically using Roslyn
result.AddValuesIfNotNull(assembly.Modules);
}
return CreateResolution(result, $"({nameof(ModuleSymbolKey)} failed)", out failureReason);
}
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class QueryExpressions
Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub ImplicitSelectClause_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q'BIND:"From s In q"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'From s In q')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'From s In q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'From s In q')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'From s In q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'From s In q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'From s In q')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Where s > 0 Where 10 > s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
-----
Where
Where
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub WhereClause_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Where s > 0 Where 10 > s'BIND:"From s In q Where s > 0 Where 10 > s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... here 10 > s')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where 10 > s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '10 > s')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: '10 > s')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10 > s')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10 > s')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10 > s')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: '10 > s')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T, U)(x As Func(Of T, U)) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.Boolean]
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Test4()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T)(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s > 0')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32050: Type parameter 'T' for 'Public Function Where(Of T)(x As Func(Of Integer, Boolean)) As QueryAble' cannot be inferred.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Test5()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T, U)(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s > 0')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32050: Type parameter 'T' for 'Public Function Where(Of T, U)(x As Func(Of Integer, Boolean)) As QueryAble' cannot be inferred.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC32050: Type parameter 'U' for 'Public Function Where(Of T, U)(x As Func(Of Integer, Boolean)) As QueryAble' cannot be inferred.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Test6()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T, U)(x As Func(Of T, Action(Of U))) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s > 0')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC36648: Data type(s) of the type parameter(s) in method 'Public Function Where(Of T, U)(x As Func(Of T, Action(Of U))) As QueryAble' cannot be inferred from these arguments.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test7()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function AsQueryable() As QueryAble1
System.Console.WriteLine("AsQueryable")
Return New QueryAble1()
End Function
Function AsEnumerable() As QueryAble1
System.Console.WriteLine("AsEnumerable")
Return New QueryAble1()
End Function
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
End Class
Class C
Function [Select](ByRef f As Func(Of String, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of String, String))")
Return Me
End Function
Function [Select](ByRef f As Func(Of Integer, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of Integer, String))")
Return Me
End Function
Function [Select](ByVal f As Func(Of Integer, Integer)) As C
System.Console.WriteLine("[Select](ByVal f As Func(Of Integer, Integer))")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
Dim y = From z In New C Select z Select z = z.ToString() Select z.ToUpper()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<)
[Select](ByRef f As Func(Of Integer, String))
[Select](ByRef f As Func(Of String, String))
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub MultipleSelectClauses_IOperation()
Dim source = <) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function AsQueryable() As QueryAble1
System.Console.WriteLine("AsQueryable")
Return New QueryAble1()
End Function
Function AsEnumerable() As QueryAble1
System.Console.WriteLine("AsEnumerable")
Return New QueryAble1()
End Function
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
End Class
Class C
Function [Select](ByRef f As Func(Of String, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of String, String))")
Return Me
End Function
Function [Select](ByRef f As Func(Of Integer, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of Integer, String))")
Return Me
End Function
Function [Select](ByVal f As Func(Of Integer, Integer)) As C
System.Console.WriteLine("[Select](ByVal f As Func(Of Integer, Integer))")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim y = From z In New C Select z Select z = z.ToString() Select z.ToUpper()'BIND:"From z In New C Select z Select z = z.ToString() Select z.ToUpper()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: C) (Syntax: 'From z In N ... z.ToUpper()')
Expression:
IInvocationOperation ( Function C.Select(ByRef f As System.Func(Of System.String, System.String)) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Select z.ToUpper()')
Instance Receiver:
IInvocationOperation ( Function C.Select(ByRef f As System.Func(Of System.Int32, System.String)) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Select z = z.ToString()')
Instance Receiver:
IInvocationOperation ( Function C.Select(f As System.Func(Of System.Int32, System.Int32)) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Select z')
Instance Receiver:
IObjectCreationOperation (Constructor: Sub C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'z')
Target:
IAnonymousFunctionOperation (Symbol: Function (z As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z')
ReturnedValue:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z.ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.String), IsImplicit) (Syntax: 'z.ToString()')
Target:
IAnonymousFunctionOperation (Symbol: Function (z As System.Int32) As System.String) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z.ToString()')
ReturnedValue:
IInvocationOperation (virtual Function System.Int32.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: 'z.ToString()')
Instance Receiver:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String, System.String), IsImplicit) (Syntax: 'z.ToUpper()')
Target:
IAnonymousFunctionOperation (Symbol: Function (z As System.String) As System.String) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
ReturnedValue:
IInvocationOperation ( Function System.String.ToUpper() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: 'z.ToUpper()')
Instance Receiver:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.String) (Syntax: 'z')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test8()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function AsEnumerable() As QueryAble1
System.Console.WriteLine("AsEnumerable")
Return New QueryAble1()
End Function
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
AsEnumerable
]]>)
End Sub
<Fact>
Public Sub Test9()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
Public Function Where(Of T)(x As Func(Of T, Boolean)) As QueryAble2
System.Console.WriteLine("Where {0}", x.GetType())
x.Invoke(CType(CObj(1), T))
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Where s > 0
System.Console.WriteLine("-----")
Dim x as Object = new Object()
Dim q3 As Object = From s In q Where DirectCast(Function() s > 0 AndAlso x IsNot Nothing, Func(Of Boolean)).Invoke()
System.Console.WriteLine("-----")
Dim q4 As Object = From s In q Where (From s1 In q Where s > s1 ) IsNot Nothing
System.Console.WriteLine("-----")
Dim q5 As Object = From s In q Where DirectCast(Function()
System.Console.WriteLine(s)
System.Console.WriteLine(PassByRef1(s))
System.Console.WriteLine(s)
System.Console.WriteLine(PassByRef2(s))
System.Console.WriteLine(s)
return True
End Function, Func(Of Boolean)).Invoke()
End Sub
Function PassByRef1(ByRef x as Object) As Integer
x=x+1
Return x
End Function
Function PassByRef2(ByRef x as Short) As Integer
x=x+1
Return x
End Function
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Cast
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
Cast
Where System.Func`2[System.Object,System.Boolean]
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
1
2
1
2
1
]]>)
End Sub
<Fact>
Public Sub Test10()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble2
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
Dim q2 As Object = From s In q Where s.Goo()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble2' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q
~
BC36593: Expression of type 'QueryAble2' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q2 As Object = From s In q Where s.Goo()
~
</expected>)
End Sub
<Fact>
Public Sub Test11()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Integer) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Integer)) As QueryAble
Return Nothing
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
]]>)
End Sub
<Fact>
Public Sub Test12()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](Of T)(x As Func(Of T, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Class Test1(Of T)
Class Test2
End Class
End Class
Class QueryAble2
Public Function [Select](Of T)(x As Func(Of Test1(Of T).Test2, Integer)) As QueryAble2
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Integer)) As QueryAble
Return Nothing
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
Dim q2 As Object = From s In New QueryAble2()
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
BC36593: Expression of type 'QueryAble2' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q2 As Object = From s In New QueryAble2()
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test13()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select]() As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Integer)) As QueryAble
Return Nothing
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Long, Integer)) As QueryAble
Return Nothing
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
</expected>)
End Sub
<Fact>
Public Sub Test14()
Dim customIL = <![CDATA[
.class public auto ansi sealed WithOpt
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname
instance void .ctor(object TargetObject,
native int TargetMethod) runtime managed
{
} // end of method WithOpt::.ctor
.method public newslot strict virtual instance class [mscorlib]System.IAsyncResult
BeginInvoke(int32 x,
class [mscorlib]System.AsyncCallback DelegateCallback,
object DelegateAsyncState) runtime managed
{
} // end of method WithOpt::BeginInvoke
.method public newslot strict virtual instance int32
EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed
{
} // end of method WithOpt::EndInvoke
.method public newslot strict virtual instance int32
Invoke([opt] int32 x) runtime managed
{
} // end of method WithOpt::Invoke
} // end of class WithOpt
.class public auto ansi sealed WithParamArray
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname
instance void .ctor(object TargetObject,
native int TargetMethod) runtime managed
{
} // end of method WithParamArray::.ctor
.method public newslot strict virtual instance class [mscorlib]System.IAsyncResult
BeginInvoke(int32 x,
class [mscorlib]System.AsyncCallback DelegateCallback,
object DelegateAsyncState) runtime managed
{
} // end of method WithParamArray::BeginInvoke
.method public newslot strict virtual instance int32
EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed
{
} // end of method WithParamArray::EndInvoke
.method public newslot strict virtual instance int32
Invoke(int32 x) runtime managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
} // end of method WithParamArray::Invoke
} // end of class WithParamArray
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Delegate Function WithByRef(ByRef x As Integer) As Integer
Class QueryAble
Public Sub [Select](x As Func(Of Integer, Integer))
System.Console.WriteLine("Select")
End Sub
Public Function [Select](x As Action(Of Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As Func(Of Integer, Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As WithByRef) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As WithOpt) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As WithParamArray) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
</expected>)
End Sub
<Fact>
Public Sub Test15()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test16()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q5 As Object = From s In q Where DirectCast(Function()
s = 1
return True
End Function, Func(Of Boolean)).Invoke()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
s = 1
~
</expected>)
End Sub
<Fact>
Public Sub Test17()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](Of T)(x As Func(Of Func(Of T()), Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
</expected>)
End Sub
<Fact>
Public Sub Test18()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As System.Delegate) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As System.MulticastDelegate) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Object) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Action(Of Integer)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Delegate Function WithByRef(ByRef x As Integer) As Boolean
Public Function Where(x As WithByRef) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Func(Of Byte, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Where' can be called with these arguments:
'Public Function Where(x As [Delegate]) As QueryAble': Lambda expression cannot be converted to '[Delegate]' because type '[Delegate]' is declared 'MustInherit' and cannot be created.
'Public Function Where(x As MulticastDelegate) As QueryAble': Lambda expression cannot be converted to 'MulticastDelegate' because type 'MulticastDelegate' is declared 'MustInherit' and cannot be created.
'Public Function Where(x As Object) As QueryAble': Lambda expression cannot be converted to 'Object' because 'Object' is not a delegate type.
'Public Function Where(x As Action(Of Integer)) As QueryAble': Nested function does not have the same signature as delegate 'Action(Of Integer)'.
'Public Function Where(x As Func(Of Integer, Integer, Boolean)) As QueryAble': Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Boolean)'.
'Public Function Where(x As QueryAble.WithByRef) As QueryAble': Nested function does not have the same signature as delegate 'QueryAble.WithByRef'.
'Public Function Where(x As Func(Of Byte, Boolean)) As QueryAble': Nested function does not have the same signature as delegate 'Func(Of Byte, Boolean)'.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test19()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Sub Where(x As Func(Of Integer, Boolean))
End Sub
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test20()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where() As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC30057: Too many arguments to 'Public Function Where() As QueryAble'.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test21()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean), Optional y As Integer = 0) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'Where' accepts this number of arguments.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test22()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean), Optional y As Integer = 0) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where() As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'Where' accepts this number of arguments.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test23()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean), ParamArray y As Integer()) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'Where' accepts this number of arguments.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test24()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(ParamArray x As Func(Of Integer, Boolean)()) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC30589: Argument cannot match a ParamArray parameter.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test25()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public ReadOnly Property Where As QueryAble
Get
Return Nothing
End Get
End Property
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
]]>)
End Sub
<Fact>
Public Sub Test26()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Where As QueryAble
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
]]>)
End Sub
<Fact>
Public Sub Test27()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test28()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As IQueryAble1, x As Func(Of Integer, Boolean)) As IQueryAble1
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, options:=TestOptions.ReleaseExe, includeVbRuntime:=True)
CompileAndVerify(compilation, expectedOutput:="Where")
End Sub
<Fact>
Public Sub Test29()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public hidebysig newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test30()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public hidebysig newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As IQueryAble1, x As Func(Of Integer, Boolean)) As IQueryAble1
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, TestOptions.ReleaseExe, includeVbRuntime:=True)
CompileAndVerify(compilation, expectedOutput:="Where")
End Sub
<Fact>
Public Sub Select1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Select")
System.Console.Write(x(1))
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Where")
System.Console.Write(x(2))
Return Me
End Function
End Class
Module Module1
Function Num1() As Integer
System.Console.WriteLine("Num1")
Return -10
End Function
Function Num2() As Integer
System.Console.WriteLine("Num2")
Return -20
End Function
Class Index
Default Property Item(x As String) As Integer
Get
System.Console.WriteLine("Item {0}", x)
Return 100
End Get
Set(value As Integer)
End Set
End Property
End Class
Sub Main()
Dim q As New QueryAble()
System.Console.WriteLine("-----")
Dim q1 As Object = From s In q Select t = s * 2 Select t
System.Console.WriteLine()
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Select s * 3 Where 100 Select -1
System.Console.WriteLine()
System.Console.WriteLine("-----")
Dim ind As New Index()
Dim q3 As Object = From s In q
Select s
Where s > 0
Select Num1
Where Num1 = -10
Select Module1.Num2()
Where Num2 = -10 + Num1()
Select ind!Two
Where Two > 0
System.Console.WriteLine()
System.Console.WriteLine("-----")
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
-----
Select
2
Select
1
-----
Select
3
Where
True
Select
-1
-----
Select
1
Where
True
Select
Num1
-10
Where
False
Select
Num2
-20
Where
Num1
False
Select
Item Two
100
Where
True
-----
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Select1_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Select")
System.Console.Write(x(1))
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Where")
System.Console.Write(x(2))
Return Me
End Function
End Class
Module Module1
Function Num1() As Integer
System.Console.WriteLine("Num1")
Return -10
End Function
Function Num2() As Integer
System.Console.WriteLine("Num2")
Return -20
End Function
Class Index
Default Property Item(x As String) As Integer
Get
System.Console.WriteLine("Item {0}", x)
Return 100
End Get
Set(value As Integer)
End Set
End Property
End Class
Sub Main()
Dim q As New QueryAble()
Dim ind As New Index()
Dim q3 As Object = From s In q'BIND:"From s In q"
Select s
Where s > 0
Select Num1()
Where Num1 = -10
Select Module1.Num2()
Where Num2 = -10 + Num1()
Select ind!Two
Where Two > 0
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... ere Two > 0')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where Two > 0')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select ind!Two')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where Num2 ... 10 + Num1()')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select Module1.Num2()')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where Num1 = -10')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select Num1()')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Num1()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'Num1()')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Num1()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Num1()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Num1()')
ReturnedValue:
IInvocationOperation (Function Module1.Num1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Num1()')
Instance Receiver:
null
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 'Num1 = -10')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num1 As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'Num1 = -10')
Left:
IParameterReferenceOperation: Num1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Num1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -10) (Syntax: '-10')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'Module1.Num2()')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
ReturnedValue:
IInvocationOperation (Function Module1.Num2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Module1.Num2()')
Instance Receiver:
null
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num2 As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'Num2 = -10 + Num1()')
Left:
IParameterReferenceOperation: Num2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Num2')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '-10 + Num1()')
Left:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -10) (Syntax: '-10')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IInvocationOperation (Function Module1.Num1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Num1()')
Instance Receiver:
null
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'ind!Two')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'ind!Two')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'ind!Two')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'ind!Two')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'ind!Two')
ReturnedValue:
IPropertyReferenceOperation: Property Module1.Index.Item(x As System.String) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'ind!Two')
Instance Receiver:
ILocalReferenceOperation: ind (OperationKind.LocalReference, Type: Module1.Index) (Syntax: 'ind')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Two')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Two") (Syntax: 'Two')
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)
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Two > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 'Two > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (Two As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Two > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Two > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Two > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'Two > 0')
Left:
IParameterReferenceOperation: Two (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Two')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Select2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(ParamArray x As Func(Of Integer, Boolean)()) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
End Sub
End Module
Class TestClass(Of Name1)
Sub Name5()
End Sub
Sub Test(Of Name2)(name3 As Object)
Dim q As New QueryAble()
Dim name4 As Integer = 0
name7% = 1
Dim q1 As Object = From x In q Select name1 = x
Dim q2 As Object = From x In q Select name2 = x
Dim q3 As Object = From x In q Select name3 = x
Dim q4 As Object = From x In q Select name4 = x
Dim q5 As Object = From x In q Select name5 = x
Dim q6 As Object = From x In q Select getHashcode = x
Dim q7 As Object = From x In q Select x.GetHashCode()
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
Dim q9 As Object = From x In q Select name7 = x
Dim q10 As Object = From x In q Select name8 = x + name8%
Dim q11 As Object = From x In q Select name9 = x
Dim q12 As Object = From x In q Select x1 As Integer = x
name9% = 1
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
Assert.True(compilation.Options.OptionExplicit)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'name7' is not declared. It may be inaccessible due to its protection level.
name7% = 1
~~~~~~
BC32089: 'name2' is already declared as a type parameter of this method.
Dim q2 As Object = From x In q Select name2 = x
~~~~~
BC30978: Range variable 'name3' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q3 As Object = From x In q Select name3 = x
~~~~~
BC30978: Range variable 'name4' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q4 As Object = From x In q Select name4 = x
~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q6 As Object = From x In q Select getHashcode = x
~~~~~~~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q7 As Object = From x In q Select x.GetHashCode()
~~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30978: Range variable 'name6' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~
BC36610: Name 'name8' is either not declared or not in the current scope.
Dim q10 As Object = From x In q Select name8 = x + name8%
~~~~~~
BC36610: Name 'x1' is either not declared or not in the current scope.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC30205: End of statement expected.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC30451: 'name9' is not declared. It may be inaccessible due to its protection level.
name9% = 1
~~~~~~
</expected>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionExplicit(False))
Assert.False(compilation.Options.OptionExplicit)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32089: 'name2' is already declared as a type parameter of this method.
Dim q2 As Object = From x In q Select name2 = x
~~~~~
BC36633: Range variable 'name3' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q3 As Object = From x In q Select name3 = x
~~~~~
BC36633: Range variable 'name4' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q4 As Object = From x In q Select name4 = x
~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q6 As Object = From x In q Select getHashcode = x
~~~~~~~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q7 As Object = From x In q Select x.GetHashCode()
~~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36633: Range variable 'name6' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~
BC36633: Range variable 'name7' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q9 As Object = From x In q Select name7 = x
~~~~~
BC36633: Range variable 'name8' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q10 As Object = From x In q Select name8 = x + name8%
~~~~~
BC36633: Range variable 'name9' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q11 As Object = From x In q Select name9 = x
~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC36633: Range variable 'x1' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC42104: Variable 'x1' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC30205: End of statement expected.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
</expected>)
End Sub
<Fact>
Public Sub Select3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
End Sub
End Module
Structure TestStruct
Dim q As QueryAble
Dim y As Integer
Delegate Function DD(ByRef z As Integer) As Boolean
Sub New(ByRef x As Integer)
Dim q01 As Object = From i In q Select i + x
Dim q02 As Object = From i In q Select i + y
Dim q1 As New QueryAble()
Dim q03 As Object = From s In q
Where (DirectCast(Function(ByRef z As Integer)
System.Console.WriteLine(z)
System.Console.WriteLine(x)
System.Console.WriteLine(y)
Dim ff As Func(Of Integer) = Function()
Dim q04 As Object = From i In q1 Select i + z
Return x + y + z
End Function
Dim q05 As Object = From i In q1 Select i + z
Return True
End Function, DD).Invoke(1))
Dim gg As DD = Function(ByRef z As Integer)
System.Console.WriteLine(y)
Dim q06 As Object = From i In q1 Select i + y
System.Console.WriteLine(x)
Dim q07 As Object = From i In q1 Select i + x
Return True
End Function
For ii As Integer = 1 To 1
Dim q101 As Object = From i In q Select ii + i
Next
End Sub
End Structure
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36533: 'ByRef' parameter 'x' cannot be used in a query expression.
Dim q01 As Object = From i In q Select i + x
~
BC36535: Instance members and 'Me' cannot be used within query expressions in structures.
Dim q02 As Object = From i In q Select i + y
~
BC36533: 'ByRef' parameter 'x' cannot be used in a query expression.
System.Console.WriteLine(x)
~
BC36535: Instance members and 'Me' cannot be used within query expressions in structures.
System.Console.WriteLine(y)
~
BC36639: 'ByRef' parameter 'z' cannot be used in a lambda expression.
Dim q04 As Object = From i In q1 Select i + z
~
BC36533: 'ByRef' parameter 'x' cannot be used in a query expression.
Return x + y + z
~
BC36535: Instance members and 'Me' cannot be used within query expressions in structures.
Return x + y + z
~
BC36639: 'ByRef' parameter 'z' cannot be used in a lambda expression.
Return x + y + z
~
BC36533: 'ByRef' parameter 'z' cannot be used in a query expression.
Dim q05 As Object = From i In q1 Select i + z
~
BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures.
System.Console.WriteLine(y)
~
BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures.
Dim q06 As Object = From i In q1 Select i + y
~
BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression.
System.Console.WriteLine(x)
~
BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression.
Dim q07 As Object = From i In q1 Select i + x
~
BC42327: Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.
Dim q101 As Object = From i In q Select ii + i
~~
</expected>)
End Sub
<Fact>
<CompilerTrait(CompilerFeature.IOperation)>
Public Sub Select4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Module1
Function Goo(x As Integer) As Integer
Return x
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Select x% = s
Dim q2 As Object = From s In q Select Goo(s)
Dim q3 As Object = From s In q Select = s
Dim q4 As Object = From s In q Where Date.Now() Select s
Dim q5 As Object = From s In q Select s.Equals(0)
Dim q6 As Object = From s In q Select DoesntExist
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36601: Type characters cannot be used in range variable declarations.
Dim q1 As Object = From s In q Select x% = s
~~
BC30201: Expression expected.
Dim q3 As Object = From s In q Select = s
~
BC30311: Value of type 'Date' cannot be converted to 'Boolean'.
Dim q4 As Object = From s In q Where Date.Now() Select s
~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q5 As Object = From s In q Select s.Equals(0)
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q5 As Object = From s In q Select s.Equals(0)
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q6 As Object = From s In q Select DoesntExist
~~~~~~~~~~~
</expected>)
Dim tree = compilation.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of WhereClauseSyntax)().Single()
Assert.Equal("Date.Now()", node.Condition.ToString())
compilation.VerifyOperationTree(node.Condition, expectedOperationTree:=
<![CDATA[
IPropertyReferenceOperation: ReadOnly Property System.DateTime.Now As System.DateTime (Static) (OperationKind.PropertyReference, Type: System.DateTime, IsInvalid) (Syntax: 'Date.Now()')
Instance Receiver:
null
]]>.Value)
End Sub
<Fact>
Public Sub Select5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0 Select s
Dim q2 As Object = From s In q Select
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0 Select s
~~~~~
BC30201: Expression expected.
Dim q2 As Object = From s In q Select
~
</expected>)
End Sub
<Fact>
Public Sub From1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s? In q Select s
Dim q2 As Object = From s() In q Select s
Dim q3 As Object = From s? As Integer In q Select s
Dim q4 As Object = From s% In q Select s
Dim q5 As Object = From s% As Integer In q Select s
Dim q6 As Object = From s As DoesntExist In q Select s
Dim q7 As Object = From s As DoesntExist In q Where s > 0
Dim q8 As Object = From s As DoesntExist In q Select s Where s > 0
Dim q9 As Object = From s As DoesntExist In q Where s > 0 Select s
Dim q10 As Object = From s As DoesntExist In q
Dim q11 As Object = From s In Nothing
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36629: Nullable type inference is not supported in this context.
Dim q1 As Object = From s? In q Select s
~
BC36607: 'In' expected.
Dim q2 As Object = From s() In q Select s
~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q3 As Object = From s? As Integer In q Select s
~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q3 As Object = From s? As Integer In q Select s
~~~~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q3 As Object = From s? As Integer In q Select s
~
BC36601: Type characters cannot be used in range variable declarations.
Dim q4 As Object = From s% In q Select s
~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q5 As Object = From s% As Integer In q Select s
~~
BC30002: Type 'DoesntExist' is not defined.
Dim q6 As Object = From s As DoesntExist In q Select s
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q7 As Object = From s As DoesntExist In q Where s > 0
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q8 As Object = From s As DoesntExist In q Select s Where s > 0
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q9 As Object = From s As DoesntExist In q Where s > 0 Select s
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q10 As Object = From s As DoesntExist In q
~~~~~~~~~~~
BC36593: Expression of type 'Object' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q11 As Object = From s In Nothing
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub From2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As DoesntExist
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q10 As Object = From s In q
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
Public Function [Select](x As Func(Of Integer, Integer)) As DoesntExist
~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Byte In q
Dim q2 As Object = From s As Byte In q Select s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~
</expected>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte'.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte'.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
Public Function Cast(Of T)() As DoesntExist
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q10 As Object = From s As Guid In q
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
Public Function Cast(Of T)() As DoesntExist
~~~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Guid'.
Dim q10 As Object = From s As Guid In q
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q10 As Object = From s As Integer In q Select CType(s, Guid)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q10 As Object = From s As Integer In q Select CType(s, Guid)
~
BC30311: Value of type 'Integer' cannot be converted to 'Guid'.
Dim q10 As Object = From s As Integer In q Select CType(s, Guid)
~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Integer In q Where s > 1
System.Console.WriteLine("------")
Dim q2 As Object = From s As Long In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
------
[Select]
[Where]
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Where1()
Dim source = <) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer?, Boolean?)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s'BIND:"From s In q Where s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Nullable(Of System.Int32)) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsInvalid) (Syntax: 's')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s'BIND:"From s In q Where s"
~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Boolean?'.
Dim q1 As Object = From s In q Where s'BIND:"From s In q Where s"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Where2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Date' cannot be converted to 'Boolean'.
Dim q1 As Object = From s In q Where s
~
</expected>)
End Sub
<Fact>
Public Sub Where3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Boolean?)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Date' cannot be converted to 'Boolean'.
Dim q1 As Object = From s In q Where s
~
</expected>)
End Sub
<Fact>
Public Sub Where4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
BC30311: Value of type 'Boolean' cannot be converted to 'Date'.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Object)) As QueryAble
System.Console.WriteLine("Where Object")
Return Me
End Function
Public Function Where(x As Func(Of Date, Boolean)) As QueryAble
System.Console.WriteLine("Where Boolean")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where Boolean
]]>)
End Sub
<Fact>
Public Sub Where6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("Where Byte")
Return Me
End Function
Public Function Where(x As Func(Of Integer, SByte)) As QueryAble
System.Console.WriteLine("Where SByte")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where Byte
]]>)
End Sub
<Fact>
Public Sub Where7()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("Where Long")
Return Me
End Function
Public Function Where(x As Func(Of Integer, System.DateTimeKind)) As QueryAble
System.Console.WriteLine("Where System.DateTimeKind")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
q.Where(Function(s) 0)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where Long
Where Long
]]>)
End Sub
<Fact>
Public Sub Where8()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("Where Byte")
Return Me
End Function
Public Function Where(x As Func(Of Integer, System.DateTimeKind)) As QueryAble
System.Console.WriteLine("Where System.DateTimeKind")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.DateTimeKind
]]>)
End Sub
<Fact>
Public Sub Where9()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, System.DateTimeKind)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
q.Where(Function(s) 0)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30521: Overload resolution failed because no accessible 'Where' is most specific for these arguments:
'Public Function Where(x As Func(Of Integer, Byte)) As QueryAble': Not most specific.
'Public Function Where(x As Func(Of Integer, DateTimeKind)) As QueryAble': Not most specific.
q.Where(Function(s) 0)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where10()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, SByte)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30519: Overload resolution failed because no accessible 'Where' can be called without a narrowing conversion:
'Public Function Where(x As Func(Of Integer, Byte)) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'Byte'.
'Public Function Where(x As Func(Of Integer, SByte)) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'SByte'.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where10b()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Linq.Expressions
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Expression(Of Func(Of Integer, Byte))) As QueryAble
Return Me
End Function
Public Function Where(x As Expression(Of Func(Of Integer, SByte))) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30519: Overload resolution failed because no accessible 'Where' can be called without a narrowing conversion:
'Public Function Where(x As Expression(Of Func(Of Integer, Byte))) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'Byte'.
'Public Function Where(x As Expression(Of Func(Of Integer, SByte))) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'SByte'.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where11()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Where Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.Boolean]
]]>)
End Sub
<Fact>
Public Sub Where12()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
Public Function Where(x As Func(Of T, Object)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
Public Function Where(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Where Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.Boolean]
]]>)
End Sub
<Fact>
Public Sub Where13()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(x As Func(Of T, String)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Where Nothing
End Sub
End Module
</file>
</compilation>
Dim verifier = CompileAndVerify(compilationDef, options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom),
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.String]
]]>)
CompilationUtils.AssertTheseDiagnostics(verifier.Compilation,
<expected>
BC42016: Implicit conversion from 'Boolean' to 'String'.
q = From s In q1 Where Nothing
~~~~~~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub While1_TakeWhile()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Take While s > 1'BIND:"From s In q Take While s > 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... While s > 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Take While s > 1')
Children(2):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 1')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'TakeWhile' is not accessible in this context.
Dim q1 As Object = From s In q Take While s > 1'BIND:"From s In q Take While s > 1"
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub While1_SkipWhile()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Skip While s > 1'BIND:"From s In q Skip While s > 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... While s > 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Skip While s > 1')
Children(2):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 1')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q2 As Object = From s In q Skip While s > 1'BIND:"From s In q Skip While s > 1"
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub While2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip While s > 0
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Take While s > 0
System.Console.WriteLine("-----")
Dim q3 As Object = From s In q Skip While s > 0 Take While 10 > s Skip While s > 0 Select s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
SkipWhile
-----
TakeWhile
-----
SkipWhile
TakeWhile
SkipWhile
Select
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub SkipWhile_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip While s > 0'BIND:"From s In q Skip While s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... While s > 0')
Expression:
IInvocationOperation ( Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip While s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub TakeWhile_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Take While s > 0'BIND:"From s In q Take While s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... While s > 0')
Expression:
IInvocationOperation ( Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Take While s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub TakeWhileAndSkipWhile_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q3 As Object = From s In q Skip While s > 0 Take While 10 > s Skip While s > 0 Select s'BIND:"From s In q Skip While s > 0 Take While 10 > s Skip While s > 0 Select s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... 0 Select s')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip While s > 0')
Instance Receiver:
IInvocationOperation ( Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Take While 10 > s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip While s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '10 > s')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: '10 > s')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10 > s')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10 > s')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10 > s')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: '10 > s')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Distinct1()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Distinct'BIND:"From s In q Distinct"
Dim q2 As Object = From s In q Skip While s > 1 Distinct
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q Distinct')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Distinct')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Distinct' is not accessible in this context.
Dim q1 As Object = From s In q Distinct'BIND:"From s In q Distinct"
~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q2 As Object = From s In q Skip While s > 1 Distinct
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Distinct2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Distinct() As QueryAble
System.Console.WriteLine("Distinct")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Distinct
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Select s + 1 Distinct Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Distinct
-----
Select
Distinct
Distinct
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Distinct2_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Distinct() As QueryAble
System.Console.WriteLine("Distinct")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Distinct'BIND:"From s In q Distinct"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q Distinct')
Expression:
IInvocationOperation ( Function QueryAble.Distinct() As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub MultipleDistinct_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Distinct() As QueryAble
System.Console.WriteLine("Distinct")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Select s + 1 Distinct Distinct'BIND:"From s In q Select s + 1 Distinct Distinct"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... ct Distinct')
Expression:
IInvocationOperation ( Function QueryAble.Distinct() As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Distinct() As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s + 1')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's + 1')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(0)
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub SkipTake1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip 1
Dim q2 As Object = From s In q Skip While s > 1 Take 2
Dim q3 As Object = From s In q Skip While s > 1 Take DoesntExist
Dim q4 As Object = From s In q Take s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Skip' is not accessible in this context.
Dim q1 As Object = From s In q Skip 1
~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q2 As Object = From s In q Skip While s > 1 Take 2
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q3 As Object = From s In q Skip While s > 1 Take DoesntExist
~~~~~~~~~~
BC30451: 'DoesntExist' is not declared. It may be inaccessible due to its protection level.
Dim q3 As Object = From s In q Skip While s > 1 Take DoesntExist
~~~~~~~~~~~
BC30451: 's' is not declared. It may be inaccessible due to its protection level.
Dim q4 As Object = From s In q Take s
~
</expected>)
End Sub
<Fact>
Public Sub SkipTake2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Skip(count As Date) As QueryAble
System.Console.WriteLine("Skip {0}", count.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
Return Me
End Function
Public Function Take(count As Integer) As QueryAble
System.Console.WriteLine("Skip {0}", count)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip #12:00:00 AM#
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Take 1 Select s
System.Console.WriteLine("-----")
Dim q3 As Object = From s In q Select s + 1 Take 2
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Skip 1/1/0001 12:00:00 AM
-----
Skip 1
Select
-----
Select
Skip 2
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Skip_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Skip(count As Date) As QueryAble
System.Console.WriteLine("Skip {0}", count.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
Return Me
End Function
Public Function Take(count As Integer) As QueryAble
System.Console.WriteLine("Skip {0}", count)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip #12:00:00 AM#'BIND:"From s In q Skip #12:00:00 AM#"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... 2:00:00 AM#')
Expression:
IInvocationOperation ( Function QueryAble.Skip(count As System.DateTime) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip #12:00:00 AM#')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '#12:00:00 AM#')
ILiteralOperation (OperationKind.Literal, Type: System.DateTime, Constant: 01/01/0001 00:00:00) (Syntax: '#12:00:00 AM#')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Take_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Skip(count As Date) As QueryAble
System.Console.WriteLine("Skip {0}", count.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
Return Me
End Function
Public Function Take(count As Integer) As QueryAble
System.Console.WriteLine("Skip {0}", count)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Take 1 Select s'BIND:"From s In q Take 1 Select s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... 1 Select s')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Take(count As System.Int32) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Take 1')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub SkipTake3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Skip(x As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Skip Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Skip 0
]]>)
End Sub
<Fact>
Public Sub OrderBy1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Order s
Dim q2 As Object = From s In q Order By s Descending
Dim q3 As Object = From s In q Order By s Ascending
Dim q4 As Object = From s In q Skip While s > 1 Order By s
Dim q5 As Object = From s In q Skip While s > 1 Order By s Descending
Dim q6 As Object = From s In q Skip While s > 1 Order By s Ascending
Dim q7 As Object = From s In q Skip While s > 1 Order By DoesntExist
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
Dim q9 As Object = From s In q Order By s, s
Dim q10 As Object = From s In q Order By s, DoesntExist
Dim q11 As Object = From s In q Order By :
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q1 As Object = From s In q Order s
~~~~~
BC36605: 'By' expected.
Dim q1 As Object = From s In q Order s
~
BC36594: Definition of method 'OrderByDescending' is not accessible in this context.
Dim q2 As Object = From s In q Order By s Descending
~~~~~~~~
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q3 As Object = From s In q Order By s Ascending
~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q4 As Object = From s In q Skip While s > 1 Order By s
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q5 As Object = From s In q Skip While s > 1 Order By s Descending
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q6 As Object = From s In q Skip While s > 1 Order By s Ascending
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q7 As Object = From s In q Skip While s > 1 Order By DoesntExist
~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q7 As Object = From s In q Skip While s > 1 Order By DoesntExist
~~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q9 As Object = From s In q Order By s, s
~~~~~~~~
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q10 As Object = From s In q Order By s, DoesntExist
~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q10 As Object = From s In q Order By s, DoesntExist
~~~~~~~~~~~
BC30201: Expression expected.
Dim q11 As Object = From s In q Order By :
~
</expected>)
End Sub
<Fact>
Public Sub OrderBy2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Order By s, s
Dim q2 As Object = From s In q Order By s, s Descending
Dim q3 As Object = From s In q Order By s, s Ascending
Dim q4 As Object = From s In q Order By s, s, s
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
Dim q7 As Object = From s In q Order By s, s, DoesntExist
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q1 As Object = From s In q Order By s, s
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q2 As Object = From s In q Order By s, s Descending
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q3 As Object = From s In q Order By s, s Ascending
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q4 As Object = From s In q Order By s, s, s
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q7 As Object = From s In q Order By s, s, DoesntExist
~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q7 As Object = From s In q Order By s, s, DoesntExist
~~~~~~~~~~~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
~~~~~~~~~~~~
BC36610: Name 'DoesntExist3' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub OrderBy3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Order By s, s
Dim q2 As Object = From s In q Order By s, s Descending
Dim q3 As Object = From s In q Order By s, s Ascending
Dim q4 As Object = From s In q Order By s, s, s
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
Dim q7 As Object = From s In q Order By s, s, DoesntExist
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
Dim q9 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2 Descending
Dim q10 As Object = From s In q Select s + 1 Order By s
Dim q11 As Object = From s In q Order By :
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q2 As Object = From s In q Order By s, s Descending
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q7 As Object = From s In q Order By s, s, DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2 Descending
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2 Descending
~~~~~~~~~~~~
BC36610: Name 's' is either not declared or not in the current scope.
Dim q10 As Object = From s In q Select s + 1 Order By s
~
BC30201: Expression expected.
Dim q11 As Object = From s In q Order By :
~
</expected>)
End Sub
<Fact>
Public Sub OrderBy4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q1 As Object = From s In q
Order By s, s, s Descending, s Ascending
Order By s Descending, s Descending, s
Order By s Ascending
Select s
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Select s + 1 Order By 0
System.Console.WriteLine("-----")
Dim q3 As Object = From s In q Order By s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
OrderBy 0
ThenBy 1
ThenByDescending 2
ThenBy 3
OrderByDescending 4
ThenByDescending 5
ThenBy 6
OrderBy 7
Select 8
-----
Select 0
OrderBy 1
-----
OrderBy 0
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub OrderByAscending_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q3 As Object = From s In q Order By s'BIND:"From s In q Order By s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q Order By s')
Expression:
IInvocationOperation ( Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub OrderByDescending_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q3 As Object = From s In q Order By s Descending'BIND:"From s In q Order By s Descending"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... Descending')
Expression:
IInvocationOperation ( Function QueryAble.OrderByDescending(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub OrderByAscendingDescending_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q1 As Object = From s In q'BIND:"From s In q"
Order By s, s, s Descending, s Ascending
Order By s Descending, s Descending, s
Order By s Ascending
Select s
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... Select s')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Ascending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenByDescending(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.OrderByDescending(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Ascending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenByDescending(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
IInvocationOperation ( Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub OrderBy5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function OrderBy(Of S)(x As Func(Of T, S)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Order By Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
OrderBy System.Func`2[System.Int32,System.Object]
]]>)
End Sub
<Fact>
Public Sub OrderBy6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Order By Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
OrderBy System.Func`2[System.Int32,System.Int32]
]]>)
End Sub
<Fact>
Public Sub Select6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q1 As IEnumerable = From s In New Integer() {1,-1} Select s, t=s*2 Where s > t
For Each v In q1
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q2 As IEnumerable = From s In New Integer() {1,-1} Select s, t=s*2 Select t, s
For Each v In q2
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s = 1, t = 2 }
{ s = 2, t = 3 }
------
{ s = -1, t = -2 }
------
{ t = 2, s = 1 }
{ t = -2, s = -1 }
]]>)
End Sub
<Fact>
Public Sub Select7()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim s As Integer = 0
Dim t As Integer = 0
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
Dim q1 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1, s1=s1+1
Dim q2 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1+1
Dim q3 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s2%=s1+1
Dim q4 As IEnumerable = From s1 In New Integer() {1,2} Select s1, GetHashCode=s1+1
Dim q5 As Object = From s1 In New Integer() {1,2} Select x1 = s1, x2 = x1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
~
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
~
BC30978: Range variable 't' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
~
BC36600: Range variable 's1' is already declared.
Dim q1 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1, s1=s1+1
~~
BC36600: Range variable 's1' is already declared.
Dim q1 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1, s1=s1+1
~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
Dim q2 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1+1
~~~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q3 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s2%=s1+1
~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q4 As IEnumerable = From s1 In New Integer() {1,2} Select s1, GetHashCode=s1+1
~~~~~~~~~~~
BC36610: Name 'x1' is either not declared or not in the current scope.
Dim q5 As Object = From s1 In New Integer() {1,2} Select x1 = s1, x2 = x1
~~
</expected>)
End Sub
<Fact>
Public Sub Select8()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s In q Select x1 = s, x2 = s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q0 As Object = From s In q Select x1 = s, x2 = s
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q0 As Object = From s In q Select x1 = s, x2 = s
~
</expected>)
End Sub
<Fact>
Public Sub Select9()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = From s In New Integer() {1, 2} Select s + 1
q0 = From s In New Integer() {1, 2} Select s + 1 Join s1 In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0 Join s1 In New Integer() {1, 2} On s Equals s1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
q0 = From s In New Integer() {1, 2} Select s + 1 Join s1 In New Integer() {1, 2} On s Equals s1
~~~~~
BC36610: Name 's' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Select s + 1 Join s1 In New Integer() {1, 2} On s Equals s1
~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0 Join s1 In New Integer() {1, 2} On s Equals s1
~~~~~
BC36610: Name 's' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0 Join s1 In New Integer() {1, 2} On s Equals s1
~
</expected>)
End Sub
<Fact>
Public Sub Select10()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Select Nothing
q = From s In q1 Select x=Nothing, y=Nothing
q = From s In q1 Let x = Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select System.Func`2[System.Int32,System.Object]
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Object,System.Object]]
Select System.Func`2[System.Int32,VB$AnonymousType_1`2[System.Int32,System.Object]]
]]>)
End Sub
<Fact>
Public Sub Let1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q1 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1, s3 = s2+s1
For Each v In q1
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q2 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1, s3 = s2+s1, s4 = s1+s2+s3
For Each v In q2
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q3 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1, s3 = s2+s1, s4 = s1+s2+s3, s5 = s1+s2+s3+s4
For Each v In q3
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q4 As IEnumerable = From s1 In New Integer() {2} Let s2 = s1+1 Let s3 = s2+s1, s4 = s1+s2+s3, s5 = s1+s2+s3+s4
For Each v In q4
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q5 As IEnumerable = From s1 In New Integer() {3} Let s2 = s1+1, s3 = s2+s1 Let s4 = s1+s2+s3, s5 = s1+s2+s3+s4
For Each v In q5
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q6 As IEnumerable = From s1 In New Integer() {4} Let s2 = s1+1, s3 = s2+s1, s4 = s1+s2+s3 Let s5 = s1+s2+s3+s4
For Each v In q6
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q7 As IEnumerable = From s1 In New Integer() {5} Select s1+1 Let s2 = 7
For Each v In q7
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q8 As IEnumerable = From s1 In New Integer() {5} Select s1+1 Let s2 = 7, s3 = 8
For Each v In q8
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, s2 = 2 }
------
{ s1 = 1, s2 = 2, s3 = 3 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 6 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 6, s5 = 12 }
------
{ s1 = 2, s2 = 3, s3 = 5, s4 = 10, s5 = 20 }
------
{ s1 = 3, s2 = 4, s3 = 7, s4 = 14, s5 = 28 }
------
{ s1 = 4, s2 = 5, s3 = 9, s4 = 18, s5 = 36 }
------
7
------
{ s2 = 7, s3 = 8 }
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Let_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1 + 1'BIND:"From s1 In New Integer() {1} Let s2 = s1 + 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (Syntax: 'From s1 In ... s2 = s1 + 1')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(selector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's2 = s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub LetMultipleVariables_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q1 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1 + 1, s3 = s2 + s1'BIND:"From s1 In New Integer() {1} Let s2 = s1 + 1, s3 = s2 + s1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (Syntax: 'From s1 In ... 3 = s2 + s1')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 's3 = s2 + s1')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(selector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's2 = s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 + s1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 's2 + s1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2 + s1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2 + s1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2 + s1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 = s2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2 + s1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub LetMultipleClauses_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q5 As IEnumerable = From s1 In New Integer() {3} Let s2 = s1 + 1, s3 = s2 + s1 Let s4 = s1 + s2 + s3, s5 = s1 + s2 + s3 + s4'BIND:"From s1 In New Integer() {3} Let s2 = s1 + 1, s3 = s2 + s1 Let s4 = s1 + s2 + s3, s5 = s1 + s2 + s3 + s4"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)) (Syntax: 'From s1 In ... 2 + s3 + s4')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)(selector As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>), IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>)(selector As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>), IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>)(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>), IsImplicit) (Syntax: 's3 = s2 + s1')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(selector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's2 = s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {3}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 + s1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>), IsImplicit) (Syntax: 's2 + s1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2 + s1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2 + s1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2 + s1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Let s2 = s1 ... 3 = s2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 = s2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2 + s1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>), IsImplicit) (Syntax: 's1 + s2 + s3')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>) As <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Let s4 = s1 ... 2 + s3 + s4')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Right:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + s2 + s3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2 + s3')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's3')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>), IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Initializers(5):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's4 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s5 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2 + s3 + s4')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2 + s3')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's3')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Let2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object = From s In New Integer() {1, 2} Let s.GetHashCode
Dim q1 As Object = From s In New Integer() {1, 2} Let =s.GetHashCode
Dim q2 As Object = From s In New Integer() {1, 2} Let _=s.GetHashCode
Dim q3 As Object = From s In New Integer() {1, 2} Let
Dim q4 As Object = From s In New Integer() {1, 2} Let t
Dim q5 As Object = From s In New Integer() {1, 2} Let t=
Dim q6 As Object = From s In New Integer() {1, 2} Let t1=, t2=s
Dim q7 As Object = From s In New Integer() {1, 2} Let t% = s
Dim q8 As Object = From s In New Integer() {1, 2} Let t% As Integer = s
Dim q9 As Object = From s In New Integer() {1, 2} Let t? As Integer = s
Dim q10 As Object = From s In New Integer() {1, 2} Let t? = s
Dim q11 As Object = From s In New Integer() {1, 2} Select t? As Integer = s
Dim q12 As Object = From s In New Integer() {1, 2} Select t As Integer = s
Dim q13 As Object = From s In New Integer() {1, 2} Let q0 = s + 1
Dim q14 As Object = From s In New Integer() {1, 2} Let s1 = s + 1, s1 = s + 2
Dim q15 As Object = From s In New Integer() {1, 2} Let s = s + 1
Dim q16 As Object = From s In New Integer() {1, 2} Let s1 As Date = s
Dim q17 As Object = From s In New Integer() {1, 2} Let s1? As Byte = s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As Object = From s In New Integer() {1, 2} Let s.GetHashCode
~
BC32020: '=' expected.
Dim q0 As Object = From s In New Integer() {1, 2} Let s.GetHashCode
~
BC30203: Identifier expected.
Dim q1 As Object = From s In New Integer() {1, 2} Let =s.GetHashCode
~
BC30203: Identifier expected.
Dim q2 As Object = From s In New Integer() {1, 2} Let _=s.GetHashCode
~
BC30203: Identifier expected.
Dim q3 As Object = From s In New Integer() {1, 2} Let
~
BC32020: '=' expected.
Dim q3 As Object = From s In New Integer() {1, 2} Let
~
BC32020: '=' expected.
Dim q4 As Object = From s In New Integer() {1, 2} Let t
~
BC30201: Expression expected.
Dim q5 As Object = From s In New Integer() {1, 2} Let t=
~
BC30201: Expression expected.
Dim q6 As Object = From s In New Integer() {1, 2} Let t1=, t2=s
~
BC36601: Type characters cannot be used in range variable declarations.
Dim q7 As Object = From s In New Integer() {1, 2} Let t% = s
~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q8 As Object = From s In New Integer() {1, 2} Let t% As Integer = s
~~
BC36629: Nullable type inference is not supported in this context.
Dim q10 As Object = From s In New Integer() {1, 2} Let t? = s
~
BC36610: Name 't' is either not declared or not in the current scope.
Dim q11 As Object = From s In New Integer() {1, 2} Select t? As Integer = s
~
BC36637: The '?' character cannot be used here.
Dim q11 As Object = From s In New Integer() {1, 2} Select t? As Integer = s
~
BC36610: Name 't' is either not declared or not in the current scope.
Dim q12 As Object = From s In New Integer() {1, 2} Select t As Integer = s
~
BC30205: End of statement expected.
Dim q12 As Object = From s In New Integer() {1, 2} Select t As Integer = s
~~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q13 As Object = From s In New Integer() {1, 2} Let q0 = s + 1
~~
BC30978: Range variable 's1' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q14 As Object = From s In New Integer() {1, 2} Let s1 = s + 1, s1 = s + 2
~~
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q15 As Object = From s In New Integer() {1, 2} Let s = s + 1
~
BC30311: Value of type 'Integer' cannot be converted to 'Date'.
Dim q16 As Object = From s In New Integer() {1, 2} Let s1 As Date = s
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
Dim q17 As Object = From s In New Integer() {1, 2} Let s1? As Byte = s
~
</expected>)
End Sub
<Fact>
Public Sub Let3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
'Inherits Base
'Public Shadows [Select] As Byte
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s In q Let t1 = s + 1
System.Console.WriteLine("------")
Dim q1 As Object = From s In q Let t1 = s + 1, t2 = t1
System.Console.WriteLine("------")
Dim q2 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
System.Console.WriteLine("------")
Dim q3 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2, t4 = t3
System.Console.WriteLine("------")
Dim q4 As Object = From s In q Let t1 = s + 1 Let t2 = t1, t3 = t2, t4 = t3
System.Console.WriteLine("------")
Dim q5 As Object = From s In q Let t1 = s + 1, t2 = t1 Let t3 = t2, t4 = t3
System.Console.WriteLine("------")
Dim q6 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Let t4 = t3
System.Console.WriteLine("------")
Dim q7 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Select s, t1, t2, t3, t4 = t3
System.Console.WriteLine("------")
Dim q8 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
Dim q9 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0 Select s, t1, t2, t3, t4 = t3
System.Console.WriteLine("------")
Dim q10 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0 Let t4 = 1
System.Console.WriteLine("------")
Dim q11 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0 From t4 In q
System.Console.WriteLine("------")
Dim q12 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Join t4 in q On t3 Equals t4
System.Console.WriteLine("------")
Dim q13 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group s By t3 Into Group
System.Console.WriteLine("------")
Dim q14 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group By t3 Into Group
System.Console.WriteLine("------")
Dim q15 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group Join t4 in q On t3 Equals t4 Into Group
System.Console.WriteLine("------")
Dim q16 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 in q Into Where(True)
System.Console.WriteLine("------")
Dim q17 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 in q Into Where(True), Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_1`3[System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
Skip 0
Take 0
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32,VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32,VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
Skip 0
Take 0
GroupBy
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],QueryAble`1[System.Int32],VB$AnonymousType_7`5[System.Int32,System.Int32,System.Int32,System.Int32,QueryAble`1[System.Int32]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_8`5[System.Int32,System.Int32,System.Int32,System.Int32,QueryAble`1[System.Int32]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_9`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],QueryAble`1[System.Int32]]]
Select System.Func`2[VB$AnonymousType_9`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],QueryAble`1[System.Int32]],VB$AnonymousType_10`6[System.Int32,System.Int32,System.Int32,System.Int32,QueryAble`1[System.Int32],QueryAble`1[System.Int32]]]
]]>)
End Sub
<Fact>
Public Sub Let4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble1
Return nothing
End Function
End Class
Class QueryAble1
Public Function [Select](Of T, S)(x As Func(Of T, S)) As QueryAble2
Return Nothing
End Function
End Class
Class QueryAble2
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s In q Let t1 = s + 1
Dim q1 As Object = From s In q Where s>0 Let t1 = s + 1, t2 = t1
Dim q2 As Object = From s In q Select s1 Let t1 = s1 + 1
Dim q3 As Object = From s In q Where s>0 Let s1 + 1, t2 = t12
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q0 As Object = From s In q Let t1 = s + 1
~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q0 As Object = From s In q Let t1 = s + 1
~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q1 As Object = From s In q Where s>0 Let t1 = s + 1, t2 = t1
~
BC36610: Name 's1' is either not declared or not in the current scope.
Dim q2 As Object = From s In q Select s1 Let t1 = s1 + 1
~~
BC32020: '=' expected.
Dim q3 As Object = From s In q Where s>0 Let s1 + 1, t2 = t12
~
BC36610: Name 't12' is either not declared or not in the current scope.
Dim q3 As Object = From s In q Where s>0 Let s1 + 1, t2 = t12
~~~
</expected>)
End Sub
<Fact>
Public Sub From3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3}, s3 In New Integer() {4, 5}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} From s2 In New Integer() {2, 3}, s3 In New Integer() {6, 7}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} From s3 In New Integer() {8, 9}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, -1} Select s1 + 1 From s2 In New Integer() {2, 3}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, -1} Select s1 + 1 From s2 In New Integer() {2, 3}, s3 In New Integer() {4, 5}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} Select s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} Let s3 = s1 + s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} Let s3 = s1 + s2, s4 = s3 + 1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 2} Select s1 + 1 From s2 In New Integer() {2, 3} Select s3 = 4, s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 2} Select s1 + 1 From s2 In New Integer() {2, 3} Let s3 = 5
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer()() {New Integer() {1, 2}, New Integer() {2, 3}}, s2 In s1 Select s3 = s1(0), s2
For Each v In q0
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, s2 = 2 }
{ s1 = 1, s2 = 3 }
------
{ s1 = 1, s2 = 2, s3 = 4 }
{ s1 = 1, s2 = 2, s3 = 5 }
{ s1 = 1, s2 = 3, s3 = 4 }
{ s1 = 1, s2 = 3, s3 = 5 }
------
{ s1 = 1, s2 = 2, s3 = 6 }
{ s1 = 1, s2 = 2, s3 = 7 }
{ s1 = 1, s2 = 3, s3 = 6 }
{ s1 = 1, s2 = 3, s3 = 7 }
------
{ s1 = 1, s2 = 2, s3 = 8 }
{ s1 = 1, s2 = 2, s3 = 9 }
{ s1 = 1, s2 = 3, s3 = 8 }
{ s1 = 1, s2 = 3, s3 = 9 }
------
2
3
2
3
------
{ s2 = 2, s3 = 4 }
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 4 }
{ s2 = 3, s3 = 5 }
{ s2 = 2, s3 = 4 }
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 4 }
{ s2 = 3, s3 = 5 }
------
{ s2 = 2, s1 = 1 }
{ s2 = 3, s1 = 1 }
------
{ s1 = 1, s2 = 2, s3 = 3 }
{ s1 = 1, s2 = 3, s3 = 4 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4 }
{ s1 = 1, s2 = 3, s3 = 4, s4 = 5 }
------
{ s3 = 4, s2 = 2 }
{ s3 = 4, s2 = 3 }
{ s3 = 4, s2 = 2 }
{ s3 = 4, s2 = 3 }
------
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 5 }
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 5 }
------
{ s3 = 1, s2 = 1 }
{ s3 = 1, s2 = 2 }
{ s3 = 2, s2 = 2 }
{ s3 = 2, s2 = 3 }
]]>)
End Sub
<Fact>
Public Sub From4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object = From s In New Integer() {1, 2} From GetHashCode
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
Dim q2 As Object = From s In New Integer() {1, 2} From _ In New Integer() {1, 2}
Dim q3 As Object = From s In New Integer() {1, 2} From
Dim q4 As Object = From s In New Integer() {1, 2} From t
Dim q5 As Object = From s In New Integer() {1, 2} From t In
Dim q6 As Object = From s In New Integer() {1, 2} From t1 In , t2 In New Integer() {1, 2}
Dim q7 As Object = From s In New Integer() {1, 2} From t% In New Integer() {1, 2}
Dim q8 As Object = From s In New Integer() {1, 2} From t% As Integer In New Integer() {1, 2}
Dim q9 As Object = From s In New Integer() {1, 2} From t? As Integer In New Integer() {1, 2}
Dim q10 As Object = From s In New Integer() {1, 2} From t? In New Integer() {1, 2}
Dim q11 As Object = From s In New Integer() {1, 2} From t In New Integer() {1, 2},
Dim q12 As Object = From s In New Integer() {1, 2} From t1 In New Integer() {1, 2}, t2 In
Dim q13 As Object = From s In New Integer() {1, 2} From q0 In New Integer() {1, 2}
Dim q14 As Object = From s In New Integer() {1, 2} From s1 In New Integer() {1, 2}, s1 In New Integer() {1, 2}
Dim q15 As Object = From s In New Integer() {1, 2} From s In New Integer() {1, 2}
Dim q16 As Object = From s In New Integer() {1, 2} From s1 As Date In New Integer() {1, 2}
Dim q17 As Object = From s In New Integer() {1, 2} From s1? As Byte In New Integer() {1, 2}
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q0 As Object = From s In New Integer() {1, 2} From GetHashCode
~~~~~~~~~~~
BC36607: 'In' expected.
Dim q0 As Object = From s In New Integer() {1, 2} From GetHashCode
~
BC30183: Keyword is not valid as an identifier.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~~
BC36607: 'In' expected.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~
BC36607: 'In' expected.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q2 As Object = From s In New Integer() {1, 2} From _ In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q3 As Object = From s In New Integer() {1, 2} From
~
BC36607: 'In' expected.
Dim q3 As Object = From s In New Integer() {1, 2} From
~
BC36607: 'In' expected.
Dim q4 As Object = From s In New Integer() {1, 2} From t
~
BC30201: Expression expected.
Dim q5 As Object = From s In New Integer() {1, 2} From t In
~
BC30201: Expression expected.
Dim q6 As Object = From s In New Integer() {1, 2} From t1 In , t2 In New Integer() {1, 2}
~
BC36601: Type characters cannot be used in range variable declarations.
Dim q7 As Object = From s In New Integer() {1, 2} From t% In New Integer() {1, 2}
~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q8 As Object = From s In New Integer() {1, 2} From t% As Integer In New Integer() {1, 2}
~~
BC36629: Nullable type inference is not supported in this context.
Dim q10 As Object = From s In New Integer() {1, 2} From t? In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q11 As Object = From s In New Integer() {1, 2} From t In New Integer() {1, 2},
~
BC36607: 'In' expected.
Dim q11 As Object = From s In New Integer() {1, 2} From t In New Integer() {1, 2},
~
BC30201: Expression expected.
Dim q12 As Object = From s In New Integer() {1, 2} From t1 In New Integer() {1, 2}, t2 In
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q13 As Object = From s In New Integer() {1, 2} From q0 In New Integer() {1, 2}
~~
BC30978: Range variable 's1' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q14 As Object = From s In New Integer() {1, 2} From s1 In New Integer() {1, 2}, s1 In New Integer() {1, 2}
~~
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q15 As Object = From s In New Integer() {1, 2} From s In New Integer() {1, 2}
~
BC30311: Value of type 'Integer' cannot be converted to 'Date'.
Dim q16 As Object = From s In New Integer() {1, 2} From s1 As Date In New Integer() {1, 2}
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
Dim q17 As Object = From s In New Integer() {1, 2} From s1? As Byte In New Integer() {1, 2}
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub From5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q0 As Object
q0 = From s1 In qi From s2 In qb
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu, s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb From s3 In qs, s4 In qu, s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs From s4 In qu, s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu From s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0 From s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0 Let s5 = 1L
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0 Select s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Select s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Select s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Let s3 = 1L
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Let s5 = 1L
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Let s3 = 1S, s4 = 1UI
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Let s3 = 1S Let s4 = 1UI
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Let s5 = 1L Select s5, s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi Select s1 + 1 From s2 In qb
System.Console.WriteLine("------")
q0 = From s1 In qi Select s1 + 1 From s2 In qb Select s2, s3 = 1S
System.Console.WriteLine("------")
q0 = From s1 In qi Select s1 + 1 From s2 In qb Let s3 = 1S
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Join s5 In ql On s1 Equals s5
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group s1 By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group Join s5 In ql On s1 Equals s5 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s5 In ql Into Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s5 In ql Into Where(True), Distinct
System.Console.WriteLine("------")
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
Skip 0
Take 0
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_6`4[System.UInt32,System.Int16,System.Byte,System.Int32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_7`2[System.Byte,System.Int32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_6`4[System.UInt32,System.Int16,System.Byte,System.Int32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16]]
Select System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16],VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16]]
Select System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16],VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_8`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,System.Int64]]
Select System.Func`2[VB$AnonymousType_8`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,System.Int64],VB$AnonymousType_9`5[System.Int64,System.UInt32,System.Int16,System.Byte,System.Int32]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,System.Byte]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_10`2[System.Byte,System.Int16]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_10`2[System.Byte,System.Int16]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
Skip 0
Take 0
GroupBy
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],QueryAble`1[System.Int64],VB$AnonymousType_12`5[System.Int32,System.Byte,System.Int16,System.UInt32,QueryAble`1[System.Int64]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_13`5[System.Int32,System.Byte,System.Int16,System.UInt32,QueryAble`1[System.Int64]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_14`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],QueryAble`1[System.Int64]]]
Select System.Func`2[VB$AnonymousType_14`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],QueryAble`1[System.Int64]],VB$AnonymousType_15`6[System.Int32,System.Byte,System.Int16,System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Int64]]]
------
]]>)
End Sub
<Fact>
Public Sub From6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble1
Return nothing
End Function
End Class
Class QueryAble1
Public Function SelectMany(Of S)(x As Func(Of Integer, QueryAble), y As Func(Of Integer, Integer, S)) As QueryAble2
Return Nothing
End Function
End Class
Class QueryAble2
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s In q From t1 In q
Dim q1 As Object = From s In q Where s>0 From t1 In q, t2 In q
Dim q2 As Object = From s In q Select s1 From t1 In q
Dim q3 As Object = From s In q Where s>0 From _ In q, t2 In q
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'SelectMany' is not accessible in this context.
Dim q0 As Object = From s In q From t1 In q
~~~~
BC36594: Definition of method 'SelectMany' is not accessible in this context.
Dim q1 As Object = From s In q Where s>0 From t1 In q, t2 In q
~
BC36610: Name 's1' is either not declared or not in the current scope.
Dim q2 As Object = From s In q Select s1 From t1 In q
~~
BC30203: Identifier expected.
Dim q3 As Object = From s In q Where s>0 From _ In q, t2 In q
~
BC36594: Definition of method 'SelectMany' is not accessible in this context.
Dim q3 As Object = From s In q Where s>0 From _ In q, t2 In q
~
</expected>)
End Sub
<Fact>
Public Sub Join1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
q0 = From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s1 Equals s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s2 + 1 Equals s1 + 2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 On s1 + 1 Equals s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Select s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 Select s3, s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 On s1 + 1 Equals s2 Select s3, s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Let s3 = s1 + s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 Let s4 = s1 + s2 + s3
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 On s1 + 1 Equals s2 Let s4 = s1 + s2 + s3
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Let s3 = s1 + s2, s4 = s3 + 1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s3 + 1 Equals s4
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s3 + 1 Equals s4
Select s1 + s2 + s3 + s4 + s5 + s6
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s3 + 1 Equals s4
Let s7 = s1 + s2 + s3 + s4 + s5 + s6
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New IComparable() {New Guid("F31A2538-E129-437E-AD69-B484F979246E")}
Join s2 In New Guid() {New Guid("F31A2538-E129-437E-AD69-B484F979246E")} On s1 Equals s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New String() {"1", "2"}
Join s2 In New Integer() {2, 3} On s1 Equals s2 - 1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 2, 3, 4, 5}
Join s2 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 * 2 Equals s2
Join s3 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 + 1 Equals s3 And s2 - 1 Equals s3 + 1
For Each v In q0
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 3, s2 = 3 }
------
{ s1 = 1, s2 = 2 }
------
{ s1 = 1, s2 = 2, s3 = 4 }
------
{ s1 = 1, s2 = 2, s3 = 4 }
------
{ s2 = 2, s1 = 1 }
------
{ s3 = 4, s2 = 2, s1 = 1 }
------
{ s3 = 4, s2 = 2, s1 = 1 }
------
{ s1 = 1, s2 = 2, s3 = 3 }
------
{ s1 = 1, s2 = 2, s3 = 4, s4 = 7 }
------
{ s1 = 1, s2 = 2, s3 = 4, s4 = 7 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4, s5 = 5, s6 = 6 }
------
21
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4, s5 = 5, s6 = 6, s7 = 21 }
------
{ s1 = f31a2538-e129-437e-ad69-b484f979246e, s2 = f31a2538-e129-437e-ad69-b484f979246e }
------
{ s1 = 1, s2 = 2 }
{ s1 = 2, s2 = 3 }
------
{ s1 = 3, s2 = 6, s3 = 4 }
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Join_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s1 Equals s2'BIND:"From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s1 Equals s2"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (Syntax: 'From s1 In ... 1 Equals s2')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, s2 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub JoinMultiple_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2'BIND:"From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (Syntax: 'From s1 In ... uals s2 * 2')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>).Join(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, s2 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {4, 5}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {4, 5}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{4, 5}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32), IsImplicit) (Syntax: 's3')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's3')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's2 * 2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 * 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2 * 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s3 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2 * 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2 * 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2 * 2')
ReturnedValue:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's3')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, s3 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Join2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = From s In New Integer() {1, 2} Join GetHashCode
q0 = From s In New Integer() {1, 2} Join s1 In
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s Equals
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join _ In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join
q0 = From s In New Integer() {1, 2} Join t
q0 = From s In New Integer() {1, 2} Join t1 In Join t2 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join t% In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t% As Integer In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t? As Integer In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t? In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
q0 = From s In New Integer() {1, 2} Join q0 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1 As Date In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1? As Byte In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1 In New String() {"1"} On s Equals s1
q0 = From s In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 Join s1 In New Integer() {1, 2} On s Equals s1
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 Equals s2 + s1
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s2
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s1
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 Equals 0 + 1 + 2
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 Equals 0
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 Equals 0
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s1 + s4 + s6 Equals s2 + s5 + s3
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s1 + s4 + s3 Equals s2 + s5 + s6
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals 0 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 + DoesntExist Equals 0 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals 0 + 1 + 2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals 0 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + s2 + DoesntExist
q0 = From s1 In New Date() {} Join s2 In New Guid() {} On s1 Equals s2
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
q0 = From s1 In New Integer() {1, 2, 3, 4, 5}
Join s2 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 * 2 Equals s2
Join s3 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 + 1 Equals s3 And s2 - 1 Equals s3 + s1
q0 = From s1 In New Integer() {1}
Join s1 In New Integer() {10} On s1 * 2 Equals 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
q0 = From s In New Integer() {1, 2} Join GetHashCode
~~~~~~~~~~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join GetHashCode
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join GetHashCode
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s Equals
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
~
BC30183: Keyword is not valid as an identifier.
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join _ In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join _ In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join t
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t
~
BC30451: 'Join' is not declared. It may be inaccessible due to its protection level.
q0 = From s In New Integer() {1, 2} Join t1 In Join t2 In New Integer() {1, 2}
~~~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t1 In Join t2 In New Integer() {1, 2}
~
BC36601: Type characters cannot be used in range variable declarations.
q0 = From s In New Integer() {1, 2} Join t% In New Integer() {1, 2} On s Equals t
~~
BC36601: Type characters cannot be used in range variable declarations.
q0 = From s In New Integer() {1, 2} Join t% As Integer In New Integer() {1, 2} On s Equals t
~~
BC36629: Nullable type inference is not supported in this context.
q0 = From s In New Integer() {1, 2} Join t? In New Integer() {1, 2} On s Equals t
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = From s In New Integer() {1, 2} Join q0 In New Integer() {1, 2}
~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join q0 In New Integer() {1, 2}
~
BC36600: Range variable 's1' is already declared.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 On s Equals s1
~
BC36610: Name 's' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 On s Equals s1
~
BC30311: Value of type 'Integer' cannot be converted to 'Date'.
q0 = From s In New Integer() {1, 2} Join s1 As Date In New Integer() {1, 2} On s Equals s1
~~~~~~~
BC36621: 'Equals' cannot compare a value of type 'Integer' with a value of type 'Date'.
q0 = From s In New Integer() {1, 2} Join s1 As Date In New Integer() {1, 2} On s Equals s1
~~~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
q0 = From s In New Integer() {1, 2} Join s1? As Byte In New Integer() {1, 2} On s Equals s1
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'String' to 'Double'.
q0 = From s In New Integer() {1, 2} Join s1 In New String() {"1"} On s Equals s1
~~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 Join s1 In New Integer() {1, 2} On s Equals s1
~
BC36610: Name 's1' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 Join s1 In New Integer() {1, 2} On s Equals s1
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 Equals s2 + s1
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 Equals s2 + s1
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s2
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s1
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 Equals 0 + 1 + 2
~~~~~~~~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 Equals 0
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 Equals 0
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 Equals 0
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s3 Equals s2 + s5 + s6
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s3 Equals s2 + s5 + s6
~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals 0 + 1 + 2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals 0 + 1 + 2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36621: 'Equals' cannot compare a value of type 'Date' with a value of type 'Guid'.
q0 = From s1 In New Date() {} Join s2 In New Guid() {} On s1 Equals s2
~~~~~~~~~~~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2' must appear on one side of the 'Equals' operator, and range variable(s) 's3' must appear on the other.
Join s3 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 + 1 Equals s3 And s2 - 1 Equals s3 + s1
~~
BC36600: Range variable 's1' is already declared.
Join s1 In New Integer() {10} On s1 * 2 Equals 0
~~
</expected>)
End Sub
<Fact>
Public Sub Join3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim qd As New QueryAble(Of Double)(0)
Dim q0 As Object
q0 = From s1 In qi Join s2 In qb On s1 Equals s2
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Select s6, s5, s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Let s7 = s6 + s5 + s4 + s3 + s2 + s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Select s6, s5, s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Let s7 = s6 + s5 + s4 + s3 + s2 + s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Join s7 In qd On s1 Equals s7
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
From s7 In qd
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group s1 By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group Join s7 In qd On s1 Equals s7 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True), Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_5`6[System.Double,System.Int64,System.UInt32,System.Int16,System.Byte,System.Int32]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double]]
Where System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
Skip 0
Take 0
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_5`6[System.Double,System.Int64,System.UInt32,System.Int16,System.Byte,System.Int32]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Double,VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Double,VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double]]
Where System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
Skip 0
Take 0
GroupBy
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],QueryAble`1[System.Double],VB$AnonymousType_9`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,QueryAble`1[System.Double]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_10`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,QueryAble`1[System.Double]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_11`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],QueryAble`1[System.Double]]]
Select System.Func`2[VB$AnonymousType_11`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],QueryAble`1[System.Double]],VB$AnonymousType_12`8[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,QueryAble`1[System.Double],QueryAble`1[System.Double]]]
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Join4()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s1 In q Join t1 In q On s1 Equals t1'BIND:"From s1 In q Join t1 In q On s1 Equals t1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s1 In ... 1 Equals t1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Children(5):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
IAnonymousFunctionOperation (Symbol: Function (t1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 't1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 't1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 't1')
ReturnedValue:
IParameterReferenceOperation: t1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 't1')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, t1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In q')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 't1 In q')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>.t1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 't1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Right:
IParameterReferenceOperation: t1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 't1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Join' is not accessible in this context.
Dim q0 As Object = From s1 In q Join t1 In q On s1 Equals t1'BIND:"From s1 In q Join t1 In q On s1 Equals t1"
~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupBy1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1, s1str = CStr(s1) By s1 = s1 Mod 2, s2 = s1 Mod 3 Into gr = Group, c = Count(), Max(s1)
System.Console.WriteLine(v)
For Each gv In v.gr
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group Join s1 In New Integer() {1, 2} On key Equals s1
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Count(s1 - 2)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, Group = System.Int32[] }
1
{ s1 = 2, Group = System.Int32[] }
2
2
{ s1 = 3, Group = System.Int32[] }
3
3
{ s1 = 4, Group = System.Int32[] }
4
------
{ s1 = 1, Count = 1 }
{ s1 = 2, Count = 2 }
{ s1 = 3, Count = 2 }
{ s1 = 4, Count = 1 }
------
{ s1 = 1, Group = System.Int32[] }
1
{ s1 = 2, Group = System.Int32[] }
2
2
{ s1 = 3, Group = System.Int32[] }
3
3
{ s1 = 4, Group = System.Int32[] }
4
------
{ s1 = 1, Count = 1 }
{ s1 = 2, Count = 2 }
{ s1 = 3, Count = 2 }
{ s1 = 4, Count = 1 }
------
{ s1 = 1, s2 = 1, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 1, Max = 1 }
{ s1 = 1, s1str = 1 }
{ s1 = 0, s2 = 2, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 2, Max = 2 }
{ s1 = 2, s1str = 2 }
{ s1 = 2, s1str = 2 }
{ s1 = 1, s2 = 0, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 2, Max = 3 }
{ s1 = 3, s1str = 3 }
{ s1 = 3, s1str = 3 }
{ s1 = 0, s2 = 1, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 1, Max = 4 }
{ s1 = 4, s1str = 4 }
------
{ key = 1, Group = System.Int32[] }
2
3
------
{ key = 1, Group = System.Int32[], s1 = 1 }
2
3
------
{ s1 = 1, Count = 1 }
{ s1 = 2, Count = 0 }
{ s1 = 3, Count = 2 }
{ s1 = 4, Count = 1 }
------
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_GroupAggregation_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Group'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Group"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(keySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By s1 Into Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By s1 Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By s1 Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By s1 Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By s1 Into Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_FunctionAggregation_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Count()'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Count()"
System.Console.WriteLine(v)
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)) (Syntax: 'From s1 In ... nto Count()')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)(keySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>), IsImplicit) (Syntax: 'Group By s1 Into Count()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>), IsImplicit) (Syntax: 'Group By s1 Into Count()')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>, IsImplicit) (Syntax: 'Group By s1 Into Count()')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>, IsImplicit) (Syntax: 'Group By s1 Into Count()')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>, IsImplicit) (Syntax: 'Group By s1 Into Count()')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By s1 Into Count()')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_WithOptionalGroupClause_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Group'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Group"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(keySelector As System.Func(Of System.Int32, System.Int32), elementSelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: elementSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_MultipleAggregations_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1, s1str = CStr(s1) By s1 = s1 Mod 2, s2 = s1 Mod 3 Into gr = Group, c = Count(), Max(s1)'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1, s1str = CStr(s1) By s1 = s1 Mod 2, s2 = s1 Mod 3 Into gr = Group, c = Count(), Max(s1)"
System.Console.WriteLine(v)
For Each gv In v.gr
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)) (Syntax: 'From s1 In ... (), Max(s1)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)(keySelector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), elementSelector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), resultSelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 Mod 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 = s1 Mod 2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 Mod 2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 Mod 2')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 Mod 3')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 Mod 3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 Mod 3')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: elementSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s1str As System.String>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s1str As System.String>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 's1str = CStr(s1)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s1str As System.String>.s1str As System.String (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'CStr(s1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String) (Syntax: 'CStr(s1)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>)) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Initializers(5):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'From s1 In ... (), Max(s1)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = Count()')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.c As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Max(s1)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.Max As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Max(s1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>).Max(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, System.Int32)) As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Max(s1)')
Instance Receiver:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s1str As System.String>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s1str As System.String>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 's1')
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)
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_WithJoin_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group Join s1 In New Integer() {1, 2} On key Equals s1'BIND:"From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group Join s1 In New Integer() {1, 2} On key Equals s1"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)) (Syntax: 'From s1 In ... y Equals s1')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>).Join(Of System.Int32, System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>), IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(keySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By ke ... Into Group')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of System.Int32)(selector As System.Func(Of System.Int32, System.Int32)) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Select s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 2}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: '1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$ItAnonymous As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By ke ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (key As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By ke ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'key =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By ke ... Into Group')
Right:
IParameterReferenceOperation: key (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... y Equals s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By ke ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By ke ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By ke ... Into Group')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 2}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'key')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), IsImplicit) (Syntax: 'key')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'key')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'key')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'key')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'key')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'key')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>), IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, s1 As System.Int32) As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'key =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupBy2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
1: q0 = From s1 In New Integer() {1} Group By Into Group
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
3: q0 = From s1 In New Integer() {1} Group s1 By s2 As Integer =s1 Into Group
4: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 As Integer =Group
5: q0 = From s1 In New Integer() {1} Group By s1 Into
6: q0 = From s1 In New Integer() {1} Group q0 = s1 By s1 Into Group
7: q0 = From s1 In New Integer() {1} Group s1 By q0 = s1 Into Group
8: q0 = From s1 In New Integer() {1} Group s1 By s1 Into q0 = Group
9: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s1 = Group
10: Dim count As Integer = 0
11: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count()
12: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count
If count > 0 Then
Dim group As String = ""
13: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Group
End If
14: q0 = From s1 In New Integer() {1} Group
15: q0 = From s1 In New Integer() {1} Group By
16: q0 = From s1 In New Integer() {1} Group s1 By s1 Into
17: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 =
18: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into Max(s1 + s2)
19: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s3 = Max(), s3 = Min()
20: q0 = From s1 In New Integer() {1} Group s2 = s1, s2 = s1 By s1, s1 Into s3 = Max()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36610: Name 'Into' is either not declared or not in the current scope.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~~~~
BC36615: 'Into' expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC30201: Expression expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC36605: 'By' expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC36615: 'Into' expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC36610: Name 's2' is either not declared or not in the current scope.
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
~~
BC36605: 'By' expected.
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
~
BC36615: 'Into' expected.
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
~
BC36610: Name 's2' is either not declared or not in the current scope.
3: q0 = From s1 In New Integer() {1} Group s1 By s2 As Integer =s1 Into Group
~~
BC36615: 'Into' expected.
3: q0 = From s1 In New Integer() {1} Group s1 By s2 As Integer =s1 Into Group
~
BC36594: Definition of method 's2' is not accessible in this context.
4: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 As Integer =Group
~~
BC30205: End of statement expected.
4: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 As Integer =Group
~~
BC36707: 'Group' or an identifier expected.
5: q0 = From s1 In New Integer() {1} Group By s1 Into
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
6: q0 = From s1 In New Integer() {1} Group q0 = s1 By s1 Into Group
~~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
7: q0 = From s1 In New Integer() {1} Group s1 By q0 = s1 Into Group
~~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
8: q0 = From s1 In New Integer() {1} Group s1 By s1 Into q0 = Group
~~
BC36600: Range variable 's1' is already declared.
9: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s1 = Group
~~
BC30978: Range variable 'Count' hides a variable in an enclosing block or a range variable previously defined in the query expression.
11: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count()
~~~~~
BC30978: Range variable 'Count' hides a variable in an enclosing block or a range variable previously defined in the query expression.
12: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count
~~~~~
BC30978: Range variable 'Group' hides a variable in an enclosing block or a range variable previously defined in the query expression.
13: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Group
~~~~~
BC30201: Expression expected.
14: q0 = From s1 In New Integer() {1} Group
~
BC36605: 'By' expected.
14: q0 = From s1 In New Integer() {1} Group
~
BC36615: 'Into' expected.
14: q0 = From s1 In New Integer() {1} Group
~
BC30201: Expression expected.
15: q0 = From s1 In New Integer() {1} Group By
~
BC36615: 'Into' expected.
15: q0 = From s1 In New Integer() {1} Group By
~
BC36707: 'Group' or an identifier expected.
16: q0 = From s1 In New Integer() {1} Group s1 By s1 Into
~
BC36707: 'Group' or an identifier expected.
17: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 =
~
BC36610: Name 's1' is either not declared or not in the current scope.
18: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into Max(s1 + s2)
~~
BC36600: Range variable 's3' is already declared.
19: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s3 = Max(), s3 = Min()
~~
BC36600: Range variable 's2' is already declared.
20: q0 = From s1 In New Integer() {1} Group s2 = s1, s2 = s1 By s1, s1 Into s3 = Max()
~~
BC36600: Range variable 's1' is already declared.
20: q0 = From s1 In New Integer() {1} Group s2 = s1, s2 = s1 By s1, s1 Into s3 = Max()
~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy3()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s1 In q Group By s1 Into Group'BIND:"From s1 In q Group By s1 Into Group"
Dim q1 As Object = From s1 In q Group s2 = s1 By s1 Into Group
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Children(3):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As ?) As <anonymous type: Key s1 As System.Int32, Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q0 As Object = From s1 In q Group By s1 Into Group'BIND:"From s1 In q Group By s1 Into Group"
~~~~~~~~
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q1 As Object = From s1 In q Group s2 = s1 By s1 Into Group
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupBy4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Action(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Func(Of Byte, Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Func(Of Integer, Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s1 In q Group By s1 Into Group
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q0 As Object = From s1 In q Group By s1 Into Group
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub GroupBy5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
System.Console.WriteLine(" {0}", key)
System.Console.WriteLine(" {0}", into)
Return New QueryAble(Of R)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Group Nothing By key = Nothing Into Group
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
GroupBy System.Func`2[System.Int32,System.Object]
System.Func`2[System.Int32,System.Object]
System.Func`3[System.Object,QueryAble`1[System.Object],VB$AnonymousType_0`2[System.Object,QueryAble`1[System.Object]]]
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)>
Public Sub GroupJoin1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s1 Equals s2 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s2 + 1 Equals s1 + 2 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Into gr1 = Group Group Join s3 In New Integer() {4, 5} On s3 Equals (s1 + 1) * 2 Into gr2 = Group
System.Console.WriteLine(v)
For Each gv In v.gr1
System.Console.WriteLine(" {0}", gv)
Next
For Each gv In v.gr2
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} Group Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 Into gr1 = Group On s1 + 1 Equals s2 Into gr2 = Group
System.Console.WriteLine(v)
For Each gr2 In v.gr2
System.Console.WriteLine(" {0}", gr2)
For Each gr1 In gr2.gr1
System.Console.WriteLine(" {0}", gr1)
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1}
Group Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In New Integer() {3, 4}
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In New Integer() {4, 5}
Group Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In New Integer() {6, 7}
On s4 + 2 Equals s6 Into g4 = Group
On s1 + 3 Equals s4 Into g5 = Group
System.Console.WriteLine(v)
For Each gr1 In v.g1
System.Console.WriteLine(" {0}", gr1)
Next
For Each gr2 In v.g2
System.Console.WriteLine(" {0}", gr2)
Next
For Each gr5 In v.g5
System.Console.WriteLine(" {0}", gr5)
For Each gr3 In gr5.g3
System.Console.WriteLine(" {0}", gr3)
Next
For Each gr4 In gr5.g4
System.Console.WriteLine(" {0}", gr4)
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In From s1 In New Integer() {1}
Group Join
s2 In New Integer() {1}
Join
s3 In New Integer() {1}
On s2 Equals s3
Join
s4 In New Integer() {1}
On s2 Equals s4
On s1 Equals s2 Into s3 = Group
System.Console.WriteLine(v)
For Each gv In v.s3
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
System.Console.WriteLine(v)
For Each g1 In v.Group
System.Console.WriteLine(" {0}", g1)
For Each g2 In g1.Group
System.Console.WriteLine(" {0}", g2)
For Each g3 In g2.Group
System.Console.WriteLine(" {0}", g3)
For Each g4 In g3.Group
System.Console.WriteLine(" {0}", g4)
Next
Next
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From s In New Integer() {1, 2}
Join
s1 In New Integer() {1, 2}
Join
s2 In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s2 Equals s1 Into Group
On s2 Equals s1
On s Equals s1
System.Console.WriteLine(v)
For Each g1 In v.Group
System.Console.WriteLine(" {0}", g1)
For Each g2 In g1.Group
System.Console.WriteLine(" {0}", g2)
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {1, 2} Group Join y In New Integer() {0, 3, 4} On x + 1 Equals y Into Count(y + x), Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, Group = System.Int32[] }
{ s1 = 3, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
3
------
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
{ s1 = 3, Group = System.Int32[] }
------
{ s1 = 1, gr1 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], gr2 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
4
------
{ s1 = 1, gr2 = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_4`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s2 = 2, gr1 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
4
------
{ s1 = 1, g1 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], g2 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], g5 = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_9`3[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32],System.Collections.Generic.IEnumerable`1[System.Int32]]] }
2
3
{ s4 = 4, g3 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], g4 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
5
6
------
{ s1 = 1, s3 = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_12`3[System.Int32,System.Int32,System.Int32]] }
{ s2 = 1, s3 = 1, s4 = 1 }
------
{ s = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]]]] }
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]] }
{ s = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
1
{ s = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]]]] }
{ s1 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]] }
{ s = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
------
{ s = 1, s1 = 1, s2 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
1
{ s = 2, s1 = 2, s2 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
------
{ x = 1, Count = 0, Group = System.Int32[] }
{ x = 2, Count = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
3
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s1 Equals s2 Into Group'BIND:"From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s1 Equals s2 Into Group"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupJoin(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... Into Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin_Nested_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Into gr1 = Group Group Join s3 In New Integer() {4, 5} On s3 Equals (s1 + 1) * 2 Into gr2 = Group'BIND:"From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Into gr1 = Group Group Join s3 In New Integer() {4, 5} On s3 Equals (s1 + 1) * 2 Into gr2 = Group"
System.Console.WriteLine(v)
For Each gv In v.gr1
System.Console.WriteLine(" {0}", gv)
Next
For Each gv In v.gr2
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... gr2 = Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>).GroupJoin(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupJoin(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... gr2 = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr1 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {4, 5}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {4, 5}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{4, 5}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), IsImplicit) (Syntax: 's3')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's3')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '(s1 + 1) * 2')
Left:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Int32) (Syntax: '(s1 + 1)')
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 's3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: '(s1 + 1) * 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s3 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
ReturnedValue:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's3')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'gr1 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr1 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'gr1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr1 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'gr1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... gr2 = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr2 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin_NestedJoin_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In From s1 In New Integer() {1}'BIND:"From s1 In From s1 In New Integer() {1}"
Group Join
s2 In New Integer() {1}
Join
s3 In New Integer() {1}
On s2 Equals s3
Join
s4 In New Integer() {1}
On s2 Equals s4
On s1 Equals s2 Into s3 = Group
System.Console.WriteLine(v)
For Each gv In v.s3
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (Syntax: 'From s1 In ... s3 = Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>).Select(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
Instance Receiver:
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (Syntax: 'From s1 In ... s3 = Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupJoin(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, System.Int32, <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)(inner As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>).Join(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3 In New Integer() {1}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's3 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's3')
Target:
IAnonymousFunctionOperation (Symbol: Function (s3 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's3')
ReturnedValue:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's3')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32, s3 As System.Int32) As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's4 In New Integer() {1}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's4 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's2')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's4')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's4')
Target:
IAnonymousFunctionOperation (Symbol: Function (s4 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's4')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's4')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's4')
ReturnedValue:
IParameterReferenceOperation: s4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's4')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, s4 As System.Int32) As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's4 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Right:
IParameterReferenceOperation: s4 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
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)
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: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)) As <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>.s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>) As <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 's1')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupJoin2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join
q0 = From s In New Integer() {1, 2} Group Join t
q0 = From s In New Integer() {1, 2} Group Join s1 In
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into Group,
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join s In New Integer() {1, 2} On s Equals s1 Into Group
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into s = Group
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
q0 = From s1 In New Integer() {1}
Group Join
s2 In New Integer() {1}
On s1 Equals s2 Into s1 = Group
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {1}
Group Join
s1 In New Integer() {1}
On s1 Equals s2 Into s1 = Group
On s1 Equals s2
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {1}
Group Join
s1 In New Integer() {1}
On s1 Equals s2 Into s2 = Group
On s1 Equals s2
q0 = From s In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s2 In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
q0 = From s In New Integer() {1, 2}
Join
s1 In New Integer() {1, 2}
Group Join
s2 In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Group s2 In New Integer() {1, 2} On s1 Equals s2 Into group On s Equals s1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~~~~~~~~~~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC30183: Keyword is not valid as an identifier.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join t
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1
~
BC36707: 'Group' or an identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into
~
BC36707: 'Group' or an identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into Group,
~
BC30451: 'Group' is not declared. It may be inaccessible due to its protection level.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~~~~~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
~~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
~
BC36600: Range variable 's1' is already declared.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Group Join s In New Integer() {1, 2} On s Equals s1 Into Group
~
BC36610: Name 's1' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Group Join s In New Integer() {1, 2} On s Equals s1 Into Group
~~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into s = Group
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
~
BC36600: Range variable 's1' is already declared.
On s1 Equals s2 Into s1 = Group
~~
BC36600: Range variable 's1' is already declared.
On s1 Equals s2 Into s1 = Group
~~
BC36600: Range variable 's2' is already declared.
On s1 Equals s2 Into s2 = Group
~~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36631: 'Join' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Group s2 In New Integer() {1, 2} On s1 Equals s2 Into group On s Equals s1
~
</expected>)
End Sub
<Fact>
Public Sub GroupJoin3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim qd As New QueryAble(Of Double)(0)
Dim q0 As Object
q0 = From s1 In qi Group Join s2 In qb On s1 Equals s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Select g1, g2, g5, s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Let s7 = s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Join s7 In qd On s1 Equals s7
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
From s7 In qd
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group s1 By s2 = s1 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group By s2 = s1 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group Join s7 In qd On s1 Equals s7 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
Group Join s3 In qd
On s4 Equals s3 Into g2 = Group
On s1 Equals s4 Into g5 = Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s4 + 2 Equals s6
Join s3 In qd
On s4 Equals s3
On s1 Equals s4 Into g5 = Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True), Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_0`2[System.Int32,QueryAble`1[System.Byte]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_7`4[QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Int32]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_8`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Int32]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Double,VB$AnonymousType_8`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Double]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Double,VB$AnonymousType_8`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Double]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
GroupBy
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],QueryAble`1[System.Double],VB$AnonymousType_10`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],QueryAble`1[System.Double]]]
------
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_12`2[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_12`2[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double]],QueryAble`1[System.Double],VB$AnonymousType_13`4[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[System.Int32,QueryAble`1[VB$AnonymousType_13`4[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double],QueryAble`1[System.Double]]],VB$AnonymousType_11`2[System.Int32,QueryAble`1[VB$AnonymousType_13`4[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double],QueryAble`1[System.Double]]]]]
------
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_14`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_14`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_15`2[VB$AnonymousType_14`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_15`2[VB$AnonymousType_14`2[System.UInt32,System.Int64],System.Double],System.Double,VB$AnonymousType_16`4[System.UInt32,System.Int64,System.Double,System.Double]]
GroupJoin System.Func`3[System.Int32,QueryAble`1[VB$AnonymousType_16`4[System.UInt32,System.Int64,System.Double,System.Double]],VB$AnonymousType_11`2[System.Int32,QueryAble`1[VB$AnonymousType_16`4[System.UInt32,System.Int64,System.Double,System.Double]]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_17`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],QueryAble`1[System.Double]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_18`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],QueryAble`1[System.Double]]]
Select System.Func`2[VB$AnonymousType_18`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],QueryAble`1[System.Double]],VB$AnonymousType_19`6[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],QueryAble`1[System.Double],QueryAble`1[System.Double]]]
]]>)
End Sub
<Fact>
Public Sub GroupJoin4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group
Dim q1 As Object = From s1 In q Join t1 In q Group Join t2 In q On t1 Equals t2 Into Group On s1 Equals t1
Dim q2 As Object = From s1 In q Join t1 In q Group t2 In q On t1 Equals t2 Into Group On s1 Equals t1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group
~~~~~~~~~~
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q1 As Object = From s1 In q Join t1 In q Group Join t2 In q On t1 Equals t2 Into Group On s1 Equals t1
~~~~~~~~~~
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q2 As Object = From s1 In q Join t1 In q Group t2 In q On t1 Equals t2 Into Group On s1 Equals t1
~~~~~
BC36631: 'Join' expected.
Dim q2 As Object = From s1 In q Join t1 In q Group t2 In q On t1 Equals t2 Into Group On s1 Equals t1
~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin5()
Dim source = <(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of I, R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group'BIND:"From s1 In q Group Join t1 In q On s1 Equals t1 Into Group"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(5):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'q')
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
IAnonymousFunctionOperation (Symbol: Function (t1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 't1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 't1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 't1')
ReturnedValue:
IParameterReferenceOperation: t1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 't1')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As ?) As <anonymous type: Key s1 As System.Int32, Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In q')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group'BIND:"From s1 In q Group Join t1 In q On s1 Equals t1 Into Group"
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Aggregate1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count())
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2))
System.Console.WriteLine(Aggregate x In New Integer() {3, 4}, y In New Integer() {1, 3} Where x > y Into Sum(x + y))
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1 Aggregate y In New Integer() {3, 4} Into Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1 Aggregate y In New Integer() {3, 4} Into Count(), Sum()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} Aggregate y In x Into Sum()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} Aggregate y In x Into Sum(), Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} From z In x Aggregate y In x Into Sum(z + y)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} From z In x Aggregate y In x Into Sum(z + y), Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1 Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)
For Each vv In v
System.Console.WriteLine(vv)
Next
Next
System.Console.WriteLine("------")
For Each v In Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3}
Where True Order By x Distinct Take While True Skip While False Skip 0 Take 100
Select x, y, z Let w = x + y + z
Into Where(True)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1
Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3}
Where True Order By x Distinct Take While True Skip While False Skip 0 Take 100
Select x, y, z Let w = x + y + z
Into Where(True)
For Each vv In v
System.Console.WriteLine(vv)
Next
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
2
{ Count = 2, Sum = 3 }
16
------
2
2
------
{ Count = 2, Sum = 7 }
{ Count = 2, Sum = 7 }
------
{ x = System.Int32[], Sum = 7 }
------
{ x = System.Int32[], Sum = 7, Count = 2 }
------
{ x = System.Int32[], z = 3, Sum = 13 }
{ x = System.Int32[], z = 4, Sum = 15 }
------
{ x = System.Int32[], z = 3, Sum = 13, Count = 2 }
{ x = System.Int32[], z = 4, Sum = 15, Count = 2 }
------
{ x = 1, y = 2, z = 3 }
------
{ x = 1, y = 2, z = 3 }
{ x = 1, y = 2, z = 3 }
------
{ x = 1, y = 2, z = 3, w = 6 }
------
{ x = 1, y = 2, z = 3, w = 6 }
{ x = 1, y = 2, z = 3, w = 6 }
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count())'BIND:"Aggregate y In New Integer() {3, 4} Into Count()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Int32) (Syntax: 'Aggregate y ... nto Count()')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New In ... er() {3, 4}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_MultipleAggregations_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2)) 'BIND:"Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2)"'BIND:"Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Expression:
IAggregateQueryOperation (OperationKind.None, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Group:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Aggregation:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>, IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>, IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPlaceholderOperation (OperationKind.None, Type: System.Int32(), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Sum(y \ 2)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>.Sum As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Sum(y \ 2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>, IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Sum(selector As System.Func(Of System.Int32, System.Int32)) As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Sum(y \ 2)')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPlaceholderOperation (OperationKind.None, Type: System.Int32(), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y \ 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'y \ 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (y As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y \ 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y \ 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y \ 2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.IntegerDivide, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y \ 2')
Left:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_WithWhereFilter_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate x In New Integer() {3, 4}, y In New Integer() {1, 3} Where x > y Into Sum(x + y))'BIND:"Aggregate x In New Integer() {3, 4}, y In New Integer() {1, 3} Where x > y Into Sum(x + y)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Int32) (Syntax: 'Aggregate x ... Sum(x + y)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).Sum(selector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32)) As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Sum(x + y)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Where x > y')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)(collectionSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New In ... er() {3, 4}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {1, 3}')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, y As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New In ... er() {3, 4}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x > y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'x > y')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x > y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x > y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x > y')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x > y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x > y')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x > y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32), IsImplicit) (Syntax: 'x + y')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x + y')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x + y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_MultipleRangeVariableDeclarations_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)'BIND:"Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)"
System.Console.WriteLine(v)
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (Syntax: 'Aggregate x ... Where(True)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'Where(True)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)(collectionSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'z In New Integer() {3}')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)(collectionSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'y In New Integer() {2}')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {2}')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New Integer() {2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {2}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, y As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New Integer() {2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {3}')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'z In New Integer() {3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {3}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, z As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New Integer() {2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_WithDifferentClauses_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From x In New Integer() {3, 4} Select x + 1'BIND:"From x In New Integer() {3, 4} Select x + 1"
Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3}
Where True Order By x Distinct Take While True Skip While False Skip 0 Take 100
Select x, y, z Let w = x + y + z
Into Where(True)
For Each vv In v
System.Console.WriteLine(vv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))) (Syntax: 'From x In N ... Where(True)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))(selector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))) As System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of System.Int32)(selector As System.Func(Of System.Int32, System.Int32)) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Select x + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New In ... er() {3, 4}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'x + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)), IsImplicit) (Syntax: 'New Integer() {1}')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$ItAnonymous As System.Int32) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
ReturnedValue:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>), IsImplicit) (Syntax: 'Where(True)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>).Select(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)(selector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>), IsImplicit) (Syntax: 'w = x + y + z')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Select(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)(selector As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'Select x, y, z')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Take(count As System.Int32) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Take 100')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Skip(count As System.Int32) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Skip 0')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).SkipWhile(predicate As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Skip While False')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).TakeWhile(predicate As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Take While True')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Distinct() As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Order By x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).OrderBy(Of System.Int32)(keySelector As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Int32)) As System.Linq.IOrderedEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'x')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Where True')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).SelectMany(Of System.Int32, <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)(collectionSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'z In New Integer() {3}')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)(collectionSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'y In New Integer() {2}')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {2}')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New Integer() {2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {2}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, y As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New Integer() {2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {3}')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'z In New Integer() {3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {3}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, z As System.Int32) As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Int32), IsImplicit) (Syntax: 'x')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(0)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'False')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'False')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'False')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'False')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'False')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'False')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '100')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'x')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>), IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Initializers(4):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'w = x + y + z')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.w As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Aggregate2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = Aggregate
q0 = Aggregate s
q0 = Aggregate s In
q0 = Aggregate s In New Integer() {1, 2}
q0 = Aggregate s In New Integer() {1, 2} Into
q0 = Aggregate s In New Integer() {1, 2} Into Group
q0 = Aggregate s In New Integer() {1, 2} Into [Group]
q0 = Aggregate s In New Integer() {1, 2} Into s
q0 = Aggregate s In New Integer() {1, 2} Into n=
q0 = Aggregate s In New Integer() {1, 2} Into n= ,
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2=
q0 = Aggregate s In New Integer() {1, 2} Into q0 = Count()
q0 = Aggregate s In New Integer() {1, 2} Into s = Count()
q0 = Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
q0 = From x In New Integer() {3, 4} Aggregate
q0 = From x In New Integer() {3, 4} Aggregate s
q0 = From x In New Integer() {3, 4} Aggregate s In
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2}
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into [Group]
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n=
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n= ,
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2=
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into q0 = Count()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s = Count()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x = Count()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
q0 = Aggregate s In New Integer() {1, 2} Into Count() Where True
q0 = Aggregate s In New Integer() {1, 2} Into Where(DoesntExist)
q0 = From x In New Integer() {3, 4} Select x + 1 Aggregate s In New Integer() {1, 2}
q0 = Aggregate s In New Integer() {1, 2} Into Group()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group()
q0 = Aggregate x In "" Into c = Count%
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'Aggregate' is not declared. It may be inaccessible due to its protection level.
q0 = Aggregate
~~~~~~~~~
BC36607: 'In' expected.
q0 = Aggregate s
~
BC36615: 'Into' expected.
q0 = Aggregate s
~
BC30201: Expression expected.
q0 = Aggregate s In
~
BC36615: 'Into' expected.
q0 = Aggregate s In
~
BC36615: 'Into' expected.
q0 = Aggregate s In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into
~
BC36708: 'Group' not allowed in this context; identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into Group
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into [Group]
~~~~~~~
BC36594: Definition of method 's' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into s
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n=
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2
~
BC36594: Definition of method 'n2' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2
~~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = Aggregate s In New Integer() {1, 2} Into q0 = Count()
~~
BC36600: Range variable 's' is already declared.
q0 = Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate
~
BC36607: 'In' expected.
q0 = From x In New Integer() {3, 4} Aggregate
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate
~
BC36607: 'In' expected.
q0 = From x In New Integer() {3, 4} Aggregate s
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate s
~
BC30201: Expression expected.
q0 = From x In New Integer() {3, 4} Aggregate s In
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate s In
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into
~
BC36708: 'Group' not allowed in this context; identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into [Group]
~~~~~~~
BC36594: Definition of method 's' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s
~
BC36594: Definition of method 'x' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x
~
BC36600: Range variable 'x' is already declared.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n=
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2
~
BC36594: Definition of method 'n2' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2
~~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into q0 = Count()
~~
BC36600: Range variable 'x' is already declared.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x = Count()
~
BC36600: Range variable 's' is already declared.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
~
BC30205: End of statement expected.
q0 = Aggregate s In New Integer() {1, 2} Into Count() Where True
~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = Aggregate s In New Integer() {1, 2} Into Where(DoesntExist)
~~~~~~~~~~~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Select x + 1 Aggregate s In New Integer() {1, 2}
~
BC30183: Keyword is not valid as an identifier.
q0 = Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC30183: Keyword is not valid as an identifier.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC36617: Aggregate function name cannot be used with a type character.
q0 = Aggregate x In "" Into c = Count%
~~~~~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Aggregate2b()
Dim source = <(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'Aggregate i ... aggr10(10)')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'aggr10(10)')
Children(2):
ILocalReferenceOperation: colm (OperationKind.LocalReference, Type: cls1) (Syntax: 'colm')
IAnonymousFunctionOperation (Symbol: Function (i As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'aggr10' is not accessible in this context.
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Aggregate2c()
Dim source = <(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Double)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'Aggregate i ... aggr10(10)')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'aggr10(10)')
Children(2):
ILocalReferenceOperation: colm (OperationKind.LocalReference, Type: cls1) (Syntax: 'colm')
IAnonymousFunctionOperation (Symbol: Function (i As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'aggr10' is not accessible in this context.
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Aggregate2d()
Dim compilationDef =
<compilation name="Aggregate2d">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class cls1
Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function aggr10(ByVal sel As Func(Of Integer, Double)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub Aggregate2e()
Dim compilationDef =
<compilation name="Aggregate2e">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Public Module UserDefinedAggregates
<System.Runtime.CompilerServices.Extension()>
Public Function Aggr10(ByVal values As cls1, ByVal selector As Func(Of Integer, Integer)) As Double
Return 1
End Function
End Module
Public Class cls1
Public Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Public Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub Aggregate2f()
Dim compilationDef =
<compilation name="Aggregate2f">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Public Module UserDefinedAggregates
<System.Runtime.CompilerServices.Extension()>
Public Function Aggr10(ByVal values As cls1, ByVal selector As Func(Of Integer, Integer)) As Double
Return 1
End Function
End Module
Public Class cls1
Public Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Private Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub Aggregate2g()
Dim compilationDef =
<compilation name="Aggregate2g">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class cls1
Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Private Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'cls1.Private Function aggr10(sel As Func(Of Integer, Integer)) As Object' is not accessible in this context because it is 'Private'.
Dim q10m = Aggregate i In colm Into aggr10(10)
~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Aggregate3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
'Inherits Base
'Public Shadows [Select] As Byte
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q0 As Object
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Select Where, t, s
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Select Distinct, Where, t, s
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Let t4 = 1
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Let t4 = 1
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
From t4 In qs
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
From t4 In qs
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Join t4 In qs On s Equals t4
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Join t4 In qs On s Equals t4
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group s By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group s By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group Join t4 In qs On t Equals t4 Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group Join t4 In qs On t Equals t4 Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True)
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True)
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True), d = Distinct()
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True), d = Distinct()
System.Console.WriteLine("------")
q0 = From i In qi, b In qb
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b)
System.Console.WriteLine("------")
q0 = From i In qi, b In qb
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b), Distinct()
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b)
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b), Distinct()
System.Console.WriteLine("------")
q0 = From i In qi Select i + 1 From b In qb
Aggregate s In qs Where s < b Into Where(s < b)
System.Console.WriteLine("------")
q0 = From i In qi Select i + 1 From b In qb
Aggregate s In qs Where s < b Into Where(s < b), Distinct()
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i From ii As Long In qi
Aggregate s In qs Where s < b Into Where(s < b)
Select Where, ii, b, i
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i From ii As Long In qi
Aggregate s In qs Where s < b Into Where(s < b), Distinct()
Select Distinct, Where, ii, b, i
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb Join ii As Long In qi On b Equals ii On b Equals i
Aggregate s In qs Where s < b Into Where(s < b)
Select Where, ii, b, i
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb Join ii As Long In qi On b Equals ii On b Equals i
Aggregate s In qs Where s < b Into Where(s < b), Distinct()
Select Distinct, Where, ii, b, i
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_5`3[QueryAble`1[System.Byte],System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_7`4[QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_8`4[System.Int32,System.Int32,QueryAble`1[System.Byte],System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_9`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_8`4[System.Int32,System.Int32,QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_9`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_8`4[System.Int32,System.Int32,QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_9`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_11`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_12`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_13`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_14`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_2`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],VB$AnonymousType_15`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_2`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],VB$AnonymousType_16`6[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_17`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]],VB$AnonymousType_19`4[System.Int32,System.Byte,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_17`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]],VB$AnonymousType_19`4[System.Int32,System.Byte,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_20`2[System.Byte,QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_21`2[System.Byte,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_21`2[System.Byte,QueryAble`1[System.Int16]],VB$AnonymousType_22`3[System.Byte,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_23`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,VB$AnonymousType_24`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_24`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]],VB$AnonymousType_25`4[QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_23`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,VB$AnonymousType_26`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_26`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]],VB$AnonymousType_27`4[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_27`4[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16],QueryAble`1[System.Int16]],VB$AnonymousType_28`5[QueryAble`1[System.Int16],QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
------
Select System.Func`2[System.Int32,System.Int64]
Join System.Func`3[System.Byte,System.Int64,VB$AnonymousType_29`2[System.Byte,System.Int64]]
Join System.Func`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],VB$AnonymousType_30`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_30`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]],VB$AnonymousType_25`4[QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
------
Select System.Func`2[System.Int32,System.Int64]
Join System.Func`3[System.Byte,System.Int64,VB$AnonymousType_29`2[System.Byte,System.Int64]]
Join System.Func`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],VB$AnonymousType_31`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_31`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]],VB$AnonymousType_32`4[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_32`4[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16],QueryAble`1[System.Int16]],VB$AnonymousType_28`5[QueryAble`1[System.Int16],QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
]]>)
End Sub
<Fact>
Public Sub Aggregate4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](x As Func(Of T, Integer)) As QueryAble(Of Integer)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of Integer)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object
q0 = Aggregate s1 In q Into Where(True)
q0 = Aggregate s1 In q Into Where(True), Distinct
q0 = From s0 in q Aggregate s1 In q Into Where(True)
q0 = From s0 in q Aggregate s1 In q Into Where(True), Distinct
q0 = Aggregate s1 In q Skip 10 Into Where(True)
q0 = From s0 in q Skip 10 Aggregate s1 In q Into Where(True)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Select' is not accessible in this context.
q0 = From s0 in q Aggregate s1 In q Into Where(True)
~~~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
q0 = From s0 in q Aggregate s1 In q Into Where(True)
~
BC36594: Definition of method 'Select' is not accessible in this context.
q0 = From s0 in q Aggregate s1 In q Into Where(True), Distinct
~~~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
q0 = From s0 in q Aggregate s1 In q Into Where(True), Distinct
~
BC36594: Definition of method 'Skip' is not accessible in this context.
q0 = Aggregate s1 In q Skip 10 Into Where(True)
~~~~
BC36594: Definition of method 'Skip' is not accessible in this context.
q0 = From s0 in q Skip 10 Aggregate s1 In q Into Where(True)
~~~~
</expected>)
End Sub
<Fact>
Public Sub DefaultQueryIndexer1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class DefaultQueryIndexer1
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer3
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
ReadOnly Property ElementAtOrDefault(x As String) As String
Get
Return x
End Get
End Property
End Class
Class DefaultQueryIndexer4
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Class DefaultQueryIndexer5
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Shared Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer6
Function AsEnumerable() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
End Class
Class DefaultQueryIndexer7
Function AsQueryable() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
End Class
Class DefaultQueryIndexer8
Function Cast(Of T)() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Function ElementAtOrDefault(this As DefaultQueryIndexer4, x As String) As Integer
Return x
End Function
Function TestDefaultQueryIndexer1() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
Function TestDefaultQueryIndexer5() As DefaultQueryIndexer5
Return New DefaultQueryIndexer5()
End Function
Sub Main()
Dim xx1 As New DefaultQueryIndexer1()
System.Console.WriteLine(xx1(1))
System.Console.WriteLine(TestDefaultQueryIndexer1(2))
Dim xx3 As New DefaultQueryIndexer3()
System.Console.WriteLine(xx3!aaa)
Dim xx4 As New DefaultQueryIndexer4()
System.Console.WriteLine(xx4(4))
System.Console.WriteLine((New DefaultQueryIndexer5())(6))
System.Console.WriteLine(TestDefaultQueryIndexer5(7))
System.Console.WriteLine((New DefaultQueryIndexer6())(8))
System.Console.WriteLine((New DefaultQueryIndexer7())(9))
System.Console.WriteLine((New DefaultQueryIndexer8())(10))
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
00000001-0000-0000-0000-000000000000
00000002-0000-0000-0000-000000000000
aaa
4
00000006-0000-0000-0000-000000000000
00000007-0000-0000-0000-000000000000
00000008-0000-0000-0000-000000000000
00000009-0000-0000-0000-000000000000
0000000a-0000-0000-0000-000000000000
]]>)
End Sub
<Fact>
Public Sub DefaultQueryIndexer2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class DefaultQueryIndexer1
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer2
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function ElementAtOrDefault(x As String) As Integer
Return x
End Function
End Class
Class DefaultQueryIndexer4
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Class DefaultQueryIndexer5
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Shared Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer9
Function Cast(Of T)() As DefaultQueryIndexer4
Return New DefaultQueryIndexer4()
End Function
End Class
Class DefaultQueryIndexer10
WriteOnly Property G As DefaultQueryIndexer1
Set(value As DefaultQueryIndexer1)
End Set
End Property
End Class
Class DefaultQueryIndexer11
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Public ElementAtOrDefault As Guid
End Class
Module Module1
Function TestDefaultQueryIndexer4() As DefaultQueryIndexer4
Return New DefaultQueryIndexer4()
End Function
Function TestDefaultQueryIndexer5() As DefaultQueryIndexer5
Return New DefaultQueryIndexer5()
End Function
Sub Main()
Dim xx1 As New DefaultQueryIndexer1()
System.Console.WriteLine(xx1(0, 1))
System.Console.WriteLine(xx1!aaa)
DefaultQueryIndexer1(3)
System.Console.WriteLine(DefaultQueryIndexer1(3))
Dim xx2 As New DefaultQueryIndexer2()
System.Console.WriteLine(xx2!aaa)
Dim xx4 As New DefaultQueryIndexer4()
System.Console.WriteLine(xx4(4))
System.Console.WriteLine(TestDefaultQueryIndexer4(2))
System.Console.WriteLine((New DefaultQueryIndexer5())(6))
System.Console.WriteLine(TestDefaultQueryIndexer5(7))
System.Console.WriteLine((New DefaultQueryIndexer9())(11))
System.Console.WriteLine((New DefaultQueryIndexer10()).G(11))
System.Console.WriteLine((New DefaultQueryIndexer11())(12))
System.Console.WriteLine((New DefaultQueryIndexer11())!bbb)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public Function ElementAtOrDefault(x As Integer) As Guid'.
System.Console.WriteLine(xx1(0, 1))
~
BC30367: Class 'DefaultQueryIndexer1' cannot be indexed because it has no default property.
System.Console.WriteLine(xx1!aaa)
~~~
BC30109: 'DefaultQueryIndexer1' is a class type and cannot be used as an expression.
DefaultQueryIndexer1(3)
~~~~~~~~~~~~~~~~~~~~
BC30109: 'DefaultQueryIndexer1' is a class type and cannot be used as an expression.
System.Console.WriteLine(DefaultQueryIndexer1(3))
~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer2' cannot be indexed because it has no default property.
System.Console.WriteLine(xx2!aaa)
~~~
BC30367: Class 'DefaultQueryIndexer4' cannot be indexed because it has no default property.
System.Console.WriteLine(xx4(4))
~~~
BC32016: 'Public Function TestDefaultQueryIndexer4() As DefaultQueryIndexer4' has no parameters and its return type cannot be indexed.
System.Console.WriteLine(TestDefaultQueryIndexer4(2))
~~~~~~~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
System.Console.WriteLine((New DefaultQueryIndexer5())(6))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
System.Console.WriteLine(TestDefaultQueryIndexer5(7))
~~~~~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer9' cannot be indexed because it has no default property.
System.Console.WriteLine((New DefaultQueryIndexer9())(11))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30524: Property 'G' is 'WriteOnly'.
System.Console.WriteLine((New DefaultQueryIndexer10()).G(11))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer11' cannot be indexed because it has no default property.
System.Console.WriteLine((New DefaultQueryIndexer11())(12))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer11' cannot be indexed because it has no default property.
System.Console.WriteLine((New DefaultQueryIndexer11())!bbb)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
''' <summary>
''' Breaking change: Native compiler allows ElementAtOrDefault
''' to be a field, while Roslyn requires ElementAtOrDefault
''' to be a method or property.
''' </summary>
<WorkItem(576814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576814")>
<Fact()>
Public Sub DefaultQueryIndexerField()
Dim source =
<compilation>
<file name="c.vb"><) As C
Return Nothing
End Function
Public ElementAtOrDefault As Object()
End Class
Module M
Sub M(o As C)
Dim value As Object
value = o(1)
o(2) = value
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source)
compilation.AssertTheseDiagnostics(
<expected>
BC30367: Class 'C' cannot be indexed because it has no default property.
value = o(1)
~
BC30367: Class 'C' cannot be indexed because it has no default property.
o(2) = value
~
</expected>)
End Sub
<Fact>
Public Sub QueryLambdas1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class QueryLambdas
Shared ReadOnly sharedRO As Integer
ReadOnly instanceRO As Integer
Shared fld1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim fld2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim fld3 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
Shared fld4 As Action = Sub()
PassByRef(sharedRO) '0
End Sub
Dim fld5 As Action = Sub()
PassByRef(sharedRO) '1
PassByRef(instanceRO) '2
End Sub
Shared Sub New()
Dim q As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim ggg As Action = Sub()
PassByRef(sharedRO) '3
End Sub
End Sub
Sub New()
Dim q1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim q2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
Dim ggg As Action = Sub()
PassByRef(sharedRO) '4
PassByRef(instanceRO) '5
End Sub
End Sub
Sub Test()
Dim q1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim q2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
Dim ggg As Action = Sub()
PassByRef(sharedRO) '6
PassByRef(instanceRO) '7
End Sub
End Sub
Shared Function PassByRef(ByRef x As Integer) As Integer
Return x
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Shared fld1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Dim fld3 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
~~~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(sharedRO) '0
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(instanceRO) '2
~~~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Dim q As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(sharedRO) '3
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Dim q2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
~~~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(instanceRO) '5
~~~~~~~~~~
</expected>)
End Sub
<WorkItem(528731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528731")>
<Fact>
Public Sub BC36598ERR_CannotLiftRestrictedTypeQuery()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CannotLiftRestrictedTypeQuery">
<file name="a.vb">
Imports System
Imports System.Linq
Module m1
Sub goo(y As ArgIterator)
Dim col = New Integer() {1, 2}
Dim x As New ArgIterator
Dim q1 = From i In col Where x.GetRemainingCount > 0 Select a = 1
Dim q2 = From i In col Where y.GetRemainingCount > 0 Select a = 2
End Sub
End Module
</file>
</compilation>, additionalRefs:={Net40.SystemCore})
AssertTheseEmitDiagnostics(compilation,
<expected>
BC36598: Instance of restricted type 'ArgIterator' cannot be used in a query expression.
Dim q1 = From i In col Where x.GetRemainingCount > 0 Select a = 1
~
BC36598: Instance of restricted type 'ArgIterator' cannot be used in a query expression.
Dim q2 = From i In col Where y.GetRemainingCount > 0 Select a = 2
~
</expected>)
End Sub
<WorkItem(545801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545801")>
<Fact>
Public Sub NoPropertyMethodConflictForQueryOperators()
Dim verifier = CompileAndVerify(
<compilation name="NoPropertyMethodConflictForQueryOperators">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim q As Object
Dim _i003 As I003 = New CI003()
q = Aggregate a In _i003 Into Count()
End Sub
End Module
Interface I001
ReadOnly Property Count() As Integer
End Interface
Interface I002
Function [Select](ByVal selector As Func(Of Integer, Integer)) As I002
Function Count() As Integer
End Interface
Interface I003
Inherits I001, I002
End Interface
Class CI003
Implements I003
Public ReadOnly Property Count() As Integer Implements I001.Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function Count1() As Integer Implements I002.Count
System.Console.WriteLine("CI003.Count") : Return Nothing
End Function
Public Function [Select](ByVal selector As System.Func(Of Integer, Integer)) As I002 Implements I002.Select
Return Me
End Function
End Class
</file>
</compilation>,
expectedOutput:="CI003.Count", references:={Net451.SystemCore})
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub RangeVariableNameInference1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb"><![CDATA[
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class Test
Sub Test02()
Dim x As System.Xml.Linq.XElement() = New System.Xml.Linq.XElement() { _
<Elem1>
<Elem2 Attr2="Elem2Attr2Val1" Attr-3="Elem2Attr3Val1">Elem2Val1</Elem2>
<Elem2 Attr2="Elem2Attr2Val2" Attr-3="Elem2Attr3Val2">Elem2Val2</Elem2>
<Elem2 Attr2="Elem2Attr2Val3" Attr-3="Elem2Attr3Val3">Elem2Val3</Elem2>
<Elem3>
<Elem2 Attr2="Elem2Attr2Val4" Attr-3="Elem2Attr3Val4">Elem2Val4</Elem2>
</Elem3>
<Elem-4>Elem4Val1</Elem-4>
</Elem1>}
Dim o As Object
o = From a In x Select y = 1, x.<Elem-4>
o = From a In x Select y = 1, x...<Elem-4>
o = From a In x Select y = 1, x.<Elem-4>.Value
o = From a In x Select y = 1, x...<Elem-4>.Value
o = From a In x Select y = 1, x.<Elem-4>.Value()
o = From a In x Select y = 1, x...<Elem-4>.Value()
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
o = From a In x Select y = 1, x.<Elem-4>(0)
o = From a In x Select y = 1, x...<Elem-4>(0)
o = From a In x Select y = 1, x.<Elem2>(0, 1)
o = From a In x Select y = 1, x...<Elem2>(0, 1)
o = From a In x Select y = 1, x.<Elem2>()
o = From a In x Select y = 1, x...<Elem2>()
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore,
SystemXmlRef,
SystemXmlLinqRef})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>.Value
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>.Value
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>.Value()
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>.Value()
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>
~~~~~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>(0)
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>(0)
~~~~~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x.<Elem2>(0, 1)
~~~~~~~~~~~~~~~
BC36582: Too many arguments to extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x.<Elem2>(0, 1)
~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x...<Elem2>(0, 1)
~~~~~~~~~~~~~~~~~
BC36582: Too many arguments to extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x...<Elem2>(0, 1)
~
BC36586: Argument not specified for parameter 'index' of extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x.<Elem2>()
~~~~~~~
BC36586: Argument not specified for parameter 'index' of extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x...<Elem2>()
~~~~~~~
]]></expected>)
End Sub
<Fact>
Public Sub ERR_RestrictedType1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb"><(x As d(Of T)) As Queryable2
Return Nothing
End Function
Function Where(Of T)(x As Func(Of T, Boolean)) As Queryable2
Return Nothing
End Function
Function SelectMany(Of S)(x As d(Of Queryable2), y As d2(Of S)) As Queryable2
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim xx As Object
xx = From ii In New Queryable2() Select 1
xx = From ii In New Queryable2()
xx = From ii In New Queryable2() Select ii
xx = From ii In New Queryable2() Select (ii)
xx = From ii In New Queryable2() Select jj = ii
xx = From ii In New Queryable2() Where True
xx = From ii In New Queryable2(), jj In New Queryable2()
xx = From ii In New Queryable2(), jj In New Queryable2() Select 1
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2()
~~~~~~~~~~~~~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2()
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Select ii
~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2() Select ii
~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Select (ii)
~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2() Select (ii)
~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Select jj = ii
~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2() Select jj = ii
~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Where True
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
xx = From ii In New Queryable2() Where True
~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
</expected>)
End Sub
<Fact()>
Public Sub ERR_RestrictedType1_2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">< As Queryable2
Return Nothing
End Function
Function [Select](x As d12) As Queryable2
Return Nothing
End Function
Function SelectMany(Of S)(x As d(Of Queryable2), y As d2(Of S)) As Queryable2
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim xx As Object
xx = From ii In New Queryable2() Select 1
xx = From ii In New Queryable2()
xx = From ii In New Queryable2() Select ii
xx = From ii In New Queryable2() Select (ii)
xx = From ii In New Queryable2() Select jj = ii
xx = From ii In New Queryable2(), jj In New Queryable2()
xx = From ii In New Queryable2(), jj In New Queryable2() Select 1
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
</expected>)
End Sub
<Fact()>
Public Sub ERR_RestrictedType1_3()
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Module M
Sub M()
Dim c1 As System.ArgIterator()() = Nothing
Dim c2 As System.TypedReference()() = Nothing
Dim z = From x In c1, y In c2
End Sub
End Module
</file>
</compilation>, references:={Net40.SystemCore}).AssertTheseDiagnostics(
<expected>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim c1 As System.ArgIterator()() = Nothing
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim c2 As System.TypedReference()() = Nothing
~~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
</expected>)
End Sub
<WorkItem(542724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542724")>
<Fact>
Public Sub QueryExprInAttributes()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
<![CDATA[
<MyAttr(From i In Q1 Select 2)>
Class cls1
End Class
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
<![CDATA[
BC30002: Type 'MyAttr' is not defined.
<MyAttr(From i In Q1 Select 2)>
~~~~~~
BC30059: Constant expression is required.
<MyAttr(From i In Q1 Select 2)>
~~~~~~~~~~~~~~~~~~~~~
BC30451: 'Q1' is not declared. It may be inaccessible due to its protection level.
<MyAttr(From i In Q1 Select 2)>
~~
]]>
</expected>)
End Sub
<Fact>
Public Sub Bug10127()
Dim compilationDef =
<compilation name="Bug10127">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Linq
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim q As Object
q = Aggregate x In New Integer(){1} Into s = Sum(Nothing)
System.Console.WriteLine(q)
System.Console.WriteLine(q.GetType())
System.Console.WriteLine("-------")
q = From x In New Integer() {1} Order By Nothing
System.Console.WriteLine(DirectCast(q, IEnumerable(Of Integer))(0))
End Sub
End Module
</file>
</compilation>
Dim verifier = CompileAndVerify(compilationDef, references:={Net40.SystemCore},
expectedOutput:=
<![CDATA[
0
System.Int32
-------
1
]]>)
End Sub
<WorkItem(528969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528969")>
<Fact>
Public Sub InaccessibleElementAtOrDefault()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Class Q1
Public Function [Select](selector As Func(Of Integer, Integer)) As Q1
Return Nothing
End Function
Private Function ElementAtOrDefault(x As String) As Integer
Return 4
End Function
End Class
Module Test
Sub Main()
Dim qs As New Q1()
Dim zs = From q In qs Select q
Dim element = zs(2)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30367: Class 'Q1' cannot be indexed because it has no default property.
Dim element = zs(2)
~~
</expected>)
End Sub
<WorkItem(543120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543120")>
<Fact()>
Public Sub ExplicitTypeNameInExprRangeVarDeclInLetClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Linq
Module Module1
Sub Main(args As String())
Dim q1 = From i1 In New Integer() {4, 5} Let i2 As Integer = "Hello".Length
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(543138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543138")>
<Fact()>
Public Sub FunctionLambdaInConditionOfJoinClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Sub Main(args As String())
Dim arr = New Byte() {4, 5}
Dim q2 = From num In arr Join n1 In arr On num.ToString() Equals (Function() n1).ToString()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation,
expectedOutput:=
<![CDATA[
]]>)
End Sub
<WorkItem(543171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543171")>
<Fact()>
Public Sub FunctionLambdaInOrderByClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Linq
Module Program
Sub Main()
Dim arr = New Integer() {4, 5}
Dim q2 = From i1 In arr Order By Function() 5
Dim q3 = arr.OrderBy(Function(i1) Function() 5)
Dim q4 = From i1 In arr Order By ((Function() 5))
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
compilation.AssertNoDiagnostics()
CompileAndVerify(compilation,
expectedOutput:=
<![CDATA[
]]>)
End Sub
<WorkItem(529014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529014")>
<Fact>
Public Sub MissingByInGroupByQueryOperator()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Sub Main(args As String())
Dim arr = New Integer() {4, 5}
Dim q1 = From i1 In arr, i2 In arr Group i1, i2
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36605: 'By' expected.
Dim q1 = From i1 In arr, i2 In arr Group i1, i2
~
BC36615: 'Into' expected.
Dim q1 = From i1 In arr, i2 In arr Group i1, i2
~
</expected>)
End Sub
<Fact()>
Public Sub InaccessibleQueryMethodOnCollectionType1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'QueryAble.Private Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble(Of Integer)' is not accessible in this context because it is 'Private'.
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub InaccessibleQueryMethodOnCollectionType2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, String)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'TakeWhile' is not accessible in this context.
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupBy6()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v+1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'QueryAble.Private Function GroupBy(Of K, R)(key As Func(Of Integer, K), into As Func(Of K, QueryAble(Of Integer), R)) As QueryAble(Of R)' is not accessible in this context because it is 'Private'.
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupBy7()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of Integer), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v+1)
End Function
Private Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of String), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v+1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupJoin6()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'QueryAble.Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of Integer, K), innerKey As Func(Of I, K), x As Func(Of Integer, QueryAble(Of I), R)) As QueryAble(Of R)' is not accessible in this context because it is 'Private'.
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupJoin7()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of Integer), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of String), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
~~~~~~~~~~
</expected>)
End Sub
<WorkItem(543523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543523")>
<Fact()>
Public Sub IncompleteLambdaInsideOrderByClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Linq
Module Program
Sub Main()
Dim arr = New Integer() {4, 5}
Dim q2 = From i1 In arr Order By Function()
r
End Function
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
<![CDATA[
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q2 = From i1 In arr Order By Function()
~~~~~~~~
BC36610: Name 'r' is either not declared or not in the current scope.
r
~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
]]>
</expected>)
End Sub
<Fact(), WorkItem(544312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544312")>
Public Sub WideningConversionInOverloadResolution()
Dim compilationDef =
<compilation name="WideningConversionInOverloadResolution">
<file name="a.vb"><) As scen1(Of Integer)
Order &= "Sel1"
sel(Nothing)
Return New scen1(Of Integer)
End Function
Public Function [Select](ByVal sel As Func(Of T, Long)) As scen1(Of Long)
Order &= "Sel2"
sel(Nothing)
Return New scen1(Of Long)
End Function
Public Function [Select](ByVal sel As Func(Of T, Short)) As scen1(Of Short)
Order &= "Sel3"
sel(Nothing)
Return New scen1(Of Short)
End Function
Public Function GroupJoin(Of L, K2, R)(ByVal inner As scen1(Of L), ByVal key1 As Func(Of T, K2), ByVal key2 As Func(Of L, Object), ByVal res As Func(Of T, scen1(Of L), R)) As scen1(Of R)
Order &= "Join1"
key1(Nothing)
Return New scen1(Of R)
End Function
End Class
Sub Main()
' "Need a widening conversion for result")
Order = ""
Dim c1 = New scen1(Of Integer)
Dim q1 = From i In c1 Group Join j In c1 On i Equals j Into G = Group
Console.WriteLine(order)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation,
expectedOutput:=
<![CDATA[
Join1
]]>)
End Sub
<Fact, WorkItem(530910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530910")>
Public Sub IQueryableOverStringMax()
Dim compilationDef =
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Module Regress123995
Sub Call0()
Dim ints = New System.Collections.Generic.List(Of Integer)
ints.Add(1)
Dim source As IQueryable(Of Integer)
source = ints.AsQueryable
Dim strings = New System.Collections.Generic.List(Of String)
strings.Add("1")
strings.Add("2")
'Query Use of Max
'Generically Inferred
Dim query = _
From x In source _
Select strings.Max(Function(s) s)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseDll).AssertNoDiagnostics()
End Sub
<Fact, WorkItem(1042011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042011")>
Public Sub LambdaWithClosureInQueryExpressionAndPDB()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System.Linq
Module Module1
Sub Main()
Dim x = From y In {1} Select Function() y
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, options:=TestOptions.DebugExe)
End Sub
<Fact, WorkItem(1099, "https://github.com/dotnet/roslyn/issues/1099")>
Public Sub LambdaWithErrorCrash()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System.Linq
Class C
Shared Function Id(Of T)(a As T, i As Integer) As T
Return a
End Function
Sub F2()
Dim result = From a In Id({1}, 1), b In Id({1, 2}, 2)
From c In Id({1, 2, 3}, 3)
Let d = Id(1, 4), e = Id(2, 5)
Distinct
Take Whi
Aggregate f In Id({1}, 6), g In Id({2}, 7)
From j In Id({1}, 9)
Let h = Id(1, 4), i = Id(2, 5)
Where Id(g < 2, 8)
Into Count(), Distinct()
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'Whi' is not declared. It may be inaccessible due to its protection level.
Take Whi
~~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub IOperationForQueryClause()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q'BIND:"From s In q"
Where s > 0
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... Where s > 0')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub IOperationForCollectionRangeVariable()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Where s > 0 Where 10 > s 'BIND:"From s In q Where s > 0 Where 10 > s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... here 10 > s')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where 10 > s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '10 > s')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: '10 > s')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10 > s')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10 > s')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10 > s')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: '10 > s')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub IOperationForRangeVariableReference()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Where s > 0 'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q Where s > 0')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<WorkItem(23223, "https://github.com/dotnet/roslyn/issues/23223")>
Public Sub DuplicateRangeVariableName_IOperation_01()
Dim source = <![CDATA[
Option Strict Off
Imports System
Imports System.Linq
Module Module1
Sub Main()
Dim q As Object = From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit 'BIND:"From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsInvalid) (Syntax: 'From implic ... ct implicit')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>).Select(Of System.Int32)(selector As System.Func(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, System.Int32)) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Select implicit')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>)(selector As System.Func(Of System.Int32, <anonymous type: Key implicit As System.Int32, Key $156 As System.String>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>), IsInvalid, IsImplicit) (Syntax: 'implicit = "1"')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'implicit In ... ) {1, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'New Integer() {1, 2, 3}')
Initializer:
IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3}')
Element Values(3):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"1"')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key implicit As System.Int32, Key $156 As System.String>), IsImplicit) (Syntax: '"1"')
Target:
IAnonymousFunctionOperation (Symbol: Function (implicit As System.Int32) As <anonymous type: Key implicit As System.Int32, Key $156 As System.String>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '"1"')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '"1"')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '"1"')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, IsInvalid, IsImplicit) (Syntax: 'implicit = "1"')
Initializers(2):
IParameterReferenceOperation: implicit (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'implicit')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'implicit')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, System.Int32), IsImplicit) (Syntax: 'implicit')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key implicit As System.Int32, Key $156 As System.String>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'implicit')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'implicit')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'implicit')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key implicit As System.Int32, Key $156 As System.String>.implicit As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'implicit')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, IsImplicit) (Syntax: 'implicit')
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)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30978: Range variable 'implicit' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q As Object = From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit 'BIND:"From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit"
~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<WorkItem(23223, "https://github.com/dotnet/roslyn/issues/23223")>
Public Sub DuplicateRangeVariableName_IOperation_02()
Dim source = <![CDATA[
Option Strict Off
Imports System
Imports System.Linq
Module Module1
Sub Main()
Dim a = New Integer() {1, 2, 3}
Dim q As Object = From x In a Join x In a On x Equals 1 'BIND:"From x In a Join x In a On x Equals 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From x In a ... x Equals 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
Children(5):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
Children(1):
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'x')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IAnonymousFunctionOperation (Symbol: Function ($168 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: '1')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, $168 As System.Int32) As <anonymous type: Key x As System.Int32, Key $168 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key $168 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
Initializers(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
IParameterReferenceOperation: $168 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36600: Range variable 'x' is already declared.
Dim q As Object = From x In a Join x In a On x Equals 1 'BIND:"From x In a Join x In a On x Equals 1"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class QueryExpressions
Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub ImplicitSelectClause_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q'BIND:"From s In q"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'From s In q')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'From s In q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'From s In q')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'From s In q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'From s In q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'From s In q')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Where s > 0 Where 10 > s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
-----
Where
Where
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub WhereClause_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Where s > 0 Where 10 > s'BIND:"From s In q Where s > 0 Where 10 > s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... here 10 > s')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where 10 > s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '10 > s')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: '10 > s')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10 > s')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10 > s')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10 > s')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: '10 > s')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T, U)(x As Func(Of T, U)) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.Boolean]
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Test4()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T)(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s > 0')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32050: Type parameter 'T' for 'Public Function Where(Of T)(x As Func(Of Integer, Boolean)) As QueryAble' cannot be inferred.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Test5()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T, U)(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s > 0')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32050: Type parameter 'T' for 'Public Function Where(Of T, U)(x As Func(Of Integer, Boolean)) As QueryAble' cannot be inferred.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC32050: Type parameter 'U' for 'Public Function Where(Of T, U)(x As Func(Of Integer, Boolean)) As QueryAble' cannot be inferred.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Test6()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(Of T, U)(x As Func(Of T, Action(Of U))) As QueryAble
System.Console.WriteLine("Where {0}", x.GetType())
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s > 0')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s > 0')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
BC36648: Data type(s) of the type parameter(s) in method 'Public Function Where(Of T, U)(x As Func(Of T, Action(Of U))) As QueryAble' cannot be inferred from these arguments.
Dim q1 As Object = From s In q Where s > 0'BIND:"From s In q Where s > 0"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test7()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function AsQueryable() As QueryAble1
System.Console.WriteLine("AsQueryable")
Return New QueryAble1()
End Function
Function AsEnumerable() As QueryAble1
System.Console.WriteLine("AsEnumerable")
Return New QueryAble1()
End Function
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
End Class
Class C
Function [Select](ByRef f As Func(Of String, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of String, String))")
Return Me
End Function
Function [Select](ByRef f As Func(Of Integer, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of Integer, String))")
Return Me
End Function
Function [Select](ByVal f As Func(Of Integer, Integer)) As C
System.Console.WriteLine("[Select](ByVal f As Func(Of Integer, Integer))")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
Dim y = From z In New C Select z Select z = z.ToString() Select z.ToUpper()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<)
[Select](ByRef f As Func(Of Integer, String))
[Select](ByRef f As Func(Of String, String))
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub MultipleSelectClauses_IOperation()
Dim source = <) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function AsQueryable() As QueryAble1
System.Console.WriteLine("AsQueryable")
Return New QueryAble1()
End Function
Function AsEnumerable() As QueryAble1
System.Console.WriteLine("AsEnumerable")
Return New QueryAble1()
End Function
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
End Class
Class C
Function [Select](ByRef f As Func(Of String, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of String, String))")
Return Me
End Function
Function [Select](ByRef f As Func(Of Integer, String)) As C
System.Console.WriteLine("[Select](ByRef f As Func(Of Integer, String))")
Return Me
End Function
Function [Select](ByVal f As Func(Of Integer, Integer)) As C
System.Console.WriteLine("[Select](ByVal f As Func(Of Integer, Integer))")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim y = From z In New C Select z Select z = z.ToString() Select z.ToUpper()'BIND:"From z In New C Select z Select z = z.ToString() Select z.ToUpper()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: C) (Syntax: 'From z In N ... z.ToUpper()')
Expression:
IInvocationOperation ( Function C.Select(ByRef f As System.Func(Of System.String, System.String)) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Select z.ToUpper()')
Instance Receiver:
IInvocationOperation ( Function C.Select(ByRef f As System.Func(Of System.Int32, System.String)) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Select z = z.ToString()')
Instance Receiver:
IInvocationOperation ( Function C.Select(f As System.Func(Of System.Int32, System.Int32)) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Select z')
Instance Receiver:
IObjectCreationOperation (Constructor: Sub C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C')
Arguments(0)
Initializer:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'z')
Target:
IAnonymousFunctionOperation (Symbol: Function (z As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z')
ReturnedValue:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z.ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.String), IsImplicit) (Syntax: 'z.ToString()')
Target:
IAnonymousFunctionOperation (Symbol: Function (z As System.Int32) As System.String) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z.ToString()')
ReturnedValue:
IInvocationOperation (virtual Function System.Int32.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: 'z.ToString()')
Instance Receiver:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String, System.String), IsImplicit) (Syntax: 'z.ToUpper()')
Target:
IAnonymousFunctionOperation (Symbol: Function (z As System.String) As System.String) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z.ToUpper()')
ReturnedValue:
IInvocationOperation ( Function System.String.ToUpper() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: 'z.ToUpper()')
Instance Receiver:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.String) (Syntax: 'z')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Test8()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function AsEnumerable() As QueryAble1
System.Console.WriteLine("AsEnumerable")
Return New QueryAble1()
End Function
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
AsEnumerable
]]>)
End Sub
<Fact>
Public Sub Test9()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Class QueryAble2
Function Cast(Of T)() As QueryAble2
System.Console.WriteLine("Cast")
Return Me
End Function
Public Function Where(Of T)(x As Func(Of T, Boolean)) As QueryAble2
System.Console.WriteLine("Where {0}", x.GetType())
x.Invoke(CType(CObj(1), T))
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Where s > 0
System.Console.WriteLine("-----")
Dim x as Object = new Object()
Dim q3 As Object = From s In q Where DirectCast(Function() s > 0 AndAlso x IsNot Nothing, Func(Of Boolean)).Invoke()
System.Console.WriteLine("-----")
Dim q4 As Object = From s In q Where (From s1 In q Where s > s1 ) IsNot Nothing
System.Console.WriteLine("-----")
Dim q5 As Object = From s In q Where DirectCast(Function()
System.Console.WriteLine(s)
System.Console.WriteLine(PassByRef1(s))
System.Console.WriteLine(s)
System.Console.WriteLine(PassByRef2(s))
System.Console.WriteLine(s)
return True
End Function, Func(Of Boolean)).Invoke()
End Sub
Function PassByRef1(ByRef x as Object) As Integer
x=x+1
Return x
End Function
Function PassByRef2(ByRef x as Short) As Integer
x=x+1
Return x
End Function
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Cast
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
Cast
Where System.Func`2[System.Object,System.Boolean]
-----
Cast
Where System.Func`2[System.Object,System.Boolean]
1
2
1
2
1
]]>)
End Sub
<Fact>
Public Sub Test10()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble2
End Class
Module Module1
Sub Main()
Dim q As New QueryAble2()
Dim q1 As Object = From s In q
Dim q2 As Object = From s In q Where s.Goo()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble2' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q
~
BC36593: Expression of type 'QueryAble2' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q2 As Object = From s In q Where s.Goo()
~
</expected>)
End Sub
<Fact>
Public Sub Test11()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Integer) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Integer)) As QueryAble
Return Nothing
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
]]>)
End Sub
<Fact>
Public Sub Test12()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](Of T)(x As Func(Of T, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Class Test1(Of T)
Class Test2
End Class
End Class
Class QueryAble2
Public Function [Select](Of T)(x As Func(Of Test1(Of T).Test2, Integer)) As QueryAble2
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Integer)) As QueryAble
Return Nothing
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
Dim q2 As Object = From s In New QueryAble2()
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
BC36593: Expression of type 'QueryAble2' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q2 As Object = From s In New QueryAble2()
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test13()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select]() As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Integer)) As QueryAble
Return Nothing
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Long, Integer)) As QueryAble
Return Nothing
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
</expected>)
End Sub
<Fact>
Public Sub Test14()
Dim customIL = <![CDATA[
.class public auto ansi sealed WithOpt
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname
instance void .ctor(object TargetObject,
native int TargetMethod) runtime managed
{
} // end of method WithOpt::.ctor
.method public newslot strict virtual instance class [mscorlib]System.IAsyncResult
BeginInvoke(int32 x,
class [mscorlib]System.AsyncCallback DelegateCallback,
object DelegateAsyncState) runtime managed
{
} // end of method WithOpt::BeginInvoke
.method public newslot strict virtual instance int32
EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed
{
} // end of method WithOpt::EndInvoke
.method public newslot strict virtual instance int32
Invoke([opt] int32 x) runtime managed
{
} // end of method WithOpt::Invoke
} // end of class WithOpt
.class public auto ansi sealed WithParamArray
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname
instance void .ctor(object TargetObject,
native int TargetMethod) runtime managed
{
} // end of method WithParamArray::.ctor
.method public newslot strict virtual instance class [mscorlib]System.IAsyncResult
BeginInvoke(int32 x,
class [mscorlib]System.AsyncCallback DelegateCallback,
object DelegateAsyncState) runtime managed
{
} // end of method WithParamArray::BeginInvoke
.method public newslot strict virtual instance int32
EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed
{
} // end of method WithParamArray::EndInvoke
.method public newslot strict virtual instance int32
Invoke(int32 x) runtime managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
} // end of method WithParamArray::Invoke
} // end of class WithParamArray
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Delegate Function WithByRef(ByRef x As Integer) As Integer
Class QueryAble
Public Sub [Select](x As Func(Of Integer, Integer))
System.Console.WriteLine("Select")
End Sub
Public Function [Select](x As Action(Of Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As Func(Of Integer, Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As WithByRef) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As WithOpt) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function [Select](x As WithParamArray) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
</expected>)
End Sub
<Fact>
Public Sub Test15()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test16()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q5 As Object = From s In q Where DirectCast(Function()
s = 1
return True
End Function, Func(Of Boolean)).Invoke()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
s = 1
~
</expected>)
End Sub
<Fact>
Public Sub Test17()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](Of T)(x As Func(Of Func(Of T()), Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q1 As Object = From s In q Where s > 0
~
</expected>)
End Sub
<Fact>
Public Sub Test18()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As System.Delegate) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As System.MulticastDelegate) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Object) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Action(Of Integer)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Delegate Function WithByRef(ByRef x As Integer) As Boolean
Public Function Where(x As WithByRef) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where(x As Func(Of Byte, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Where' can be called with these arguments:
'Public Function Where(x As [Delegate]) As QueryAble': Lambda expression cannot be converted to '[Delegate]' because type '[Delegate]' is declared 'MustInherit' and cannot be created.
'Public Function Where(x As MulticastDelegate) As QueryAble': Lambda expression cannot be converted to 'MulticastDelegate' because type 'MulticastDelegate' is declared 'MustInherit' and cannot be created.
'Public Function Where(x As Object) As QueryAble': Lambda expression cannot be converted to 'Object' because 'Object' is not a delegate type.
'Public Function Where(x As Action(Of Integer)) As QueryAble': Nested function does not have the same signature as delegate 'Action(Of Integer)'.
'Public Function Where(x As Func(Of Integer, Integer, Boolean)) As QueryAble': Nested function does not have the same signature as delegate 'Func(Of Integer, Integer, Boolean)'.
'Public Function Where(x As QueryAble.WithByRef) As QueryAble': Nested function does not have the same signature as delegate 'QueryAble.WithByRef'.
'Public Function Where(x As Func(Of Byte, Boolean)) As QueryAble': Nested function does not have the same signature as delegate 'Func(Of Byte, Boolean)'.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test19()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Sub Where(x As Func(Of Integer, Boolean))
End Sub
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test20()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where() As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC30057: Too many arguments to 'Public Function Where() As QueryAble'.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test21()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean), Optional y As Integer = 0) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'Where' accepts this number of arguments.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test22()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean), Optional y As Integer = 0) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function Where() As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'Where' accepts this number of arguments.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test23()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean), ParamArray y As Integer()) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'Where' accepts this number of arguments.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test24()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(ParamArray x As Func(Of Integer, Boolean)()) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
BC30589: Argument cannot match a ParamArray parameter.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test25()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public ReadOnly Property Where As QueryAble
Get
Return Nothing
End Get
End Property
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
]]>)
End Sub
<Fact>
Public Sub Test26()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Where As QueryAble
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
]]>)
End Sub
<Fact>
Public Sub Test27()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test28()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As IQueryAble1, x As Func(Of Integer, Boolean)) As IQueryAble1
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, options:=TestOptions.ReleaseExe, includeVbRuntime:=True)
CompileAndVerify(compilation, expectedOutput:="Where")
End Sub
<Fact>
Public Sub Test29()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public hidebysig newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test30()
Dim customIL = <![CDATA[
.class interface public abstract auto ansi IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Where(class [mscorlib]System.Func`2<int32,bool> x) cil managed
{
} // end of method IBase::Where1
} // end of class IBase
.class interface public abstract auto ansi IQueryAble1
implements IBase
{
.method public newslot abstract strict virtual
instance class IQueryAble1 Select(class [mscorlib]System.Func`2<int32,int32> x) cil managed
{
} // end of method IQueryAble1::Select
.method public hidebysig newslot specialname abstract strict virtual
instance int32 get_Where() cil managed
{
} // end of method IQueryAble1::get_Where
.property instance int32 Where()
{
.get instance int32 IQueryAble1::get_Where()
} // end of property IQueryAble1::Where
} // end of class IQueryAble1
]]>
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As IQueryAble1, x As Func(Of Integer, Boolean)) As IQueryAble1
System.Console.WriteLine("Where")
Return this
End Function
Sub Main()
Dim q As IQueryAble1 = Nothing
Dim q1 As Object = From s In q Where s > 0
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(compilationDef, customIL.Value, TestOptions.ReleaseExe, includeVbRuntime:=True)
CompileAndVerify(compilation, expectedOutput:="Where")
End Sub
<Fact>
Public Sub Select1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Select")
System.Console.Write(x(1))
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Where")
System.Console.Write(x(2))
Return Me
End Function
End Class
Module Module1
Function Num1() As Integer
System.Console.WriteLine("Num1")
Return -10
End Function
Function Num2() As Integer
System.Console.WriteLine("Num2")
Return -20
End Function
Class Index
Default Property Item(x As String) As Integer
Get
System.Console.WriteLine("Item {0}", x)
Return 100
End Get
Set(value As Integer)
End Set
End Property
End Class
Sub Main()
Dim q As New QueryAble()
System.Console.WriteLine("-----")
Dim q1 As Object = From s In q Select t = s * 2 Select t
System.Console.WriteLine()
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Select s * 3 Where 100 Select -1
System.Console.WriteLine()
System.Console.WriteLine("-----")
Dim ind As New Index()
Dim q3 As Object = From s In q
Select s
Where s > 0
Select Num1
Where Num1 = -10
Select Module1.Num2()
Where Num2 = -10 + Num1()
Select ind!Two
Where Two > 0
System.Console.WriteLine()
System.Console.WriteLine("-----")
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
-----
Select
2
Select
1
-----
Select
3
Where
True
Select
-1
-----
Select
1
Where
True
Select
Num1
-10
Where
False
Select
Num2
-20
Where
Num1
False
Select
Item Two
100
Where
True
-----
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Select1_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Select")
System.Console.Write(x(1))
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine()
System.Console.WriteLine("Where")
System.Console.Write(x(2))
Return Me
End Function
End Class
Module Module1
Function Num1() As Integer
System.Console.WriteLine("Num1")
Return -10
End Function
Function Num2() As Integer
System.Console.WriteLine("Num2")
Return -20
End Function
Class Index
Default Property Item(x As String) As Integer
Get
System.Console.WriteLine("Item {0}", x)
Return 100
End Get
Set(value As Integer)
End Set
End Property
End Class
Sub Main()
Dim q As New QueryAble()
Dim ind As New Index()
Dim q3 As Object = From s In q'BIND:"From s In q"
Select s
Where s > 0
Select Num1()
Where Num1 = -10
Select Module1.Num2()
Where Num2 = -10 + Num1()
Select ind!Two
Where Two > 0
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... ere Two > 0')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where Two > 0')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select ind!Two')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where Num2 ... 10 + Num1()')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select Module1.Num2()')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where Num1 = -10')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select Num1()')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Num1()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'Num1()')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Num1()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Num1()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Num1()')
ReturnedValue:
IInvocationOperation (Function Module1.Num1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Num1()')
Instance Receiver:
null
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 'Num1 = -10')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num1 As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Num1 = -10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'Num1 = -10')
Left:
IParameterReferenceOperation: Num1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Num1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -10) (Syntax: '-10')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'Module1.Num2()')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Module1.Num2()')
ReturnedValue:
IInvocationOperation (Function Module1.Num2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Module1.Num2()')
Instance Receiver:
null
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num2 As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Num2 = -10 + Num1()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'Num2 = -10 + Num1()')
Left:
IParameterReferenceOperation: Num2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Num2')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '-10 + Num1()')
Left:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -10) (Syntax: '-10')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IInvocationOperation (Function Module1.Num1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Num1()')
Instance Receiver:
null
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'ind!Two')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'ind!Two')
Target:
IAnonymousFunctionOperation (Symbol: Function (Num2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'ind!Two')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'ind!Two')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'ind!Two')
ReturnedValue:
IPropertyReferenceOperation: Property Module1.Index.Item(x As System.String) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'ind!Two')
Instance Receiver:
ILocalReferenceOperation: ind (OperationKind.LocalReference, Type: Module1.Index) (Syntax: 'ind')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Two')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Two") (Syntax: 'Two')
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)
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Two > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 'Two > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (Two As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Two > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Two > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Two > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'Two > 0')
Left:
IParameterReferenceOperation: Two (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Two')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Select2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(ParamArray x As Func(Of Integer, Boolean)()) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
End Sub
End Module
Class TestClass(Of Name1)
Sub Name5()
End Sub
Sub Test(Of Name2)(name3 As Object)
Dim q As New QueryAble()
Dim name4 As Integer = 0
name7% = 1
Dim q1 As Object = From x In q Select name1 = x
Dim q2 As Object = From x In q Select name2 = x
Dim q3 As Object = From x In q Select name3 = x
Dim q4 As Object = From x In q Select name4 = x
Dim q5 As Object = From x In q Select name5 = x
Dim q6 As Object = From x In q Select getHashcode = x
Dim q7 As Object = From x In q Select x.GetHashCode()
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
Dim q9 As Object = From x In q Select name7 = x
Dim q10 As Object = From x In q Select name8 = x + name8%
Dim q11 As Object = From x In q Select name9 = x
Dim q12 As Object = From x In q Select x1 As Integer = x
name9% = 1
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
Assert.True(compilation.Options.OptionExplicit)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'name7' is not declared. It may be inaccessible due to its protection level.
name7% = 1
~~~~~~
BC32089: 'name2' is already declared as a type parameter of this method.
Dim q2 As Object = From x In q Select name2 = x
~~~~~
BC30978: Range variable 'name3' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q3 As Object = From x In q Select name3 = x
~~~~~
BC30978: Range variable 'name4' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q4 As Object = From x In q Select name4 = x
~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q6 As Object = From x In q Select getHashcode = x
~~~~~~~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q7 As Object = From x In q Select x.GetHashCode()
~~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30978: Range variable 'name6' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~
BC36610: Name 'name8' is either not declared or not in the current scope.
Dim q10 As Object = From x In q Select name8 = x + name8%
~~~~~~
BC36610: Name 'x1' is either not declared or not in the current scope.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC30205: End of statement expected.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC30451: 'name9' is not declared. It may be inaccessible due to its protection level.
name9% = 1
~~~~~~
</expected>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionExplicit(False))
Assert.False(compilation.Options.OptionExplicit)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32089: 'name2' is already declared as a type parameter of this method.
Dim q2 As Object = From x In q Select name2 = x
~~~~~
BC36633: Range variable 'name3' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q3 As Object = From x In q Select name3 = x
~~~~~
BC36633: Range variable 'name4' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q4 As Object = From x In q Select name4 = x
~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q6 As Object = From x In q Select getHashcode = x
~~~~~~~~~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q7 As Object = From x In q Select x.GetHashCode()
~~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36633: Range variable 'name6' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q8 As Object = From name6 In q Select (From x In q Select name6 = x)
~~~~~
BC36633: Range variable 'name7' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q9 As Object = From x In q Select name7 = x
~~~~~
BC36633: Range variable 'name8' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q10 As Object = From x In q Select name8 = x + name8%
~~~~~
BC36633: Range variable 'name9' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q11 As Object = From x In q Select name9 = x
~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC36633: Range variable 'x1' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC42104: Variable 'x1' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
BC30205: End of statement expected.
Dim q12 As Object = From x In q Select x1 As Integer = x
~~
</expected>)
End Sub
<Fact>
Public Sub Select3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
End Sub
End Module
Structure TestStruct
Dim q As QueryAble
Dim y As Integer
Delegate Function DD(ByRef z As Integer) As Boolean
Sub New(ByRef x As Integer)
Dim q01 As Object = From i In q Select i + x
Dim q02 As Object = From i In q Select i + y
Dim q1 As New QueryAble()
Dim q03 As Object = From s In q
Where (DirectCast(Function(ByRef z As Integer)
System.Console.WriteLine(z)
System.Console.WriteLine(x)
System.Console.WriteLine(y)
Dim ff As Func(Of Integer) = Function()
Dim q04 As Object = From i In q1 Select i + z
Return x + y + z
End Function
Dim q05 As Object = From i In q1 Select i + z
Return True
End Function, DD).Invoke(1))
Dim gg As DD = Function(ByRef z As Integer)
System.Console.WriteLine(y)
Dim q06 As Object = From i In q1 Select i + y
System.Console.WriteLine(x)
Dim q07 As Object = From i In q1 Select i + x
Return True
End Function
For ii As Integer = 1 To 1
Dim q101 As Object = From i In q Select ii + i
Next
End Sub
End Structure
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36533: 'ByRef' parameter 'x' cannot be used in a query expression.
Dim q01 As Object = From i In q Select i + x
~
BC36535: Instance members and 'Me' cannot be used within query expressions in structures.
Dim q02 As Object = From i In q Select i + y
~
BC36533: 'ByRef' parameter 'x' cannot be used in a query expression.
System.Console.WriteLine(x)
~
BC36535: Instance members and 'Me' cannot be used within query expressions in structures.
System.Console.WriteLine(y)
~
BC36639: 'ByRef' parameter 'z' cannot be used in a lambda expression.
Dim q04 As Object = From i In q1 Select i + z
~
BC36533: 'ByRef' parameter 'x' cannot be used in a query expression.
Return x + y + z
~
BC36535: Instance members and 'Me' cannot be used within query expressions in structures.
Return x + y + z
~
BC36639: 'ByRef' parameter 'z' cannot be used in a lambda expression.
Return x + y + z
~
BC36533: 'ByRef' parameter 'z' cannot be used in a query expression.
Dim q05 As Object = From i In q1 Select i + z
~
BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures.
System.Console.WriteLine(y)
~
BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures.
Dim q06 As Object = From i In q1 Select i + y
~
BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression.
System.Console.WriteLine(x)
~
BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression.
Dim q07 As Object = From i In q1 Select i + x
~
BC42327: Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.
Dim q101 As Object = From i In q Select ii + i
~~
</expected>)
End Sub
<Fact>
<CompilerTrait(CompilerFeature.IOperation)>
Public Sub Select4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Module1
Function Goo(x As Integer) As Integer
Return x
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Select x% = s
Dim q2 As Object = From s In q Select Goo(s)
Dim q3 As Object = From s In q Select = s
Dim q4 As Object = From s In q Where Date.Now() Select s
Dim q5 As Object = From s In q Select s.Equals(0)
Dim q6 As Object = From s In q Select DoesntExist
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36601: Type characters cannot be used in range variable declarations.
Dim q1 As Object = From s In q Select x% = s
~~
BC30201: Expression expected.
Dim q3 As Object = From s In q Select = s
~
BC30311: Value of type 'Date' cannot be converted to 'Boolean'.
Dim q4 As Object = From s In q Where Date.Now() Select s
~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q5 As Object = From s In q Select s.Equals(0)
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q5 As Object = From s In q Select s.Equals(0)
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q6 As Object = From s In q Select DoesntExist
~~~~~~~~~~~
</expected>)
Dim tree = compilation.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of WhereClauseSyntax)().Single()
Assert.Equal("Date.Now()", node.Condition.ToString())
compilation.VerifyOperationTree(node.Condition, expectedOperationTree:=
<![CDATA[
IPropertyReferenceOperation: ReadOnly Property System.DateTime.Now As System.DateTime (Static) (OperationKind.PropertyReference, Type: System.DateTime, IsInvalid) (Syntax: 'Date.Now()')
Instance Receiver:
null
]]>.Value)
End Sub
<Fact>
Public Sub Select5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s > 0 Select s
Dim q2 As Object = From s In q Select
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s > 0 Select s
~~~~~
BC30201: Expression expected.
Dim q2 As Object = From s In q Select
~
</expected>)
End Sub
<Fact>
Public Sub From1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s? In q Select s
Dim q2 As Object = From s() In q Select s
Dim q3 As Object = From s? As Integer In q Select s
Dim q4 As Object = From s% In q Select s
Dim q5 As Object = From s% As Integer In q Select s
Dim q6 As Object = From s As DoesntExist In q Select s
Dim q7 As Object = From s As DoesntExist In q Where s > 0
Dim q8 As Object = From s As DoesntExist In q Select s Where s > 0
Dim q9 As Object = From s As DoesntExist In q Where s > 0 Select s
Dim q10 As Object = From s As DoesntExist In q
Dim q11 As Object = From s In Nothing
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36629: Nullable type inference is not supported in this context.
Dim q1 As Object = From s? In q Select s
~
BC36607: 'In' expected.
Dim q2 As Object = From s() In q Select s
~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q3 As Object = From s? As Integer In q Select s
~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q3 As Object = From s? As Integer In q Select s
~~~~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q3 As Object = From s? As Integer In q Select s
~
BC36601: Type characters cannot be used in range variable declarations.
Dim q4 As Object = From s% In q Select s
~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q5 As Object = From s% As Integer In q Select s
~~
BC30002: Type 'DoesntExist' is not defined.
Dim q6 As Object = From s As DoesntExist In q Select s
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q7 As Object = From s As DoesntExist In q Where s > 0
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q8 As Object = From s As DoesntExist In q Select s Where s > 0
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q9 As Object = From s As DoesntExist In q Where s > 0 Select s
~~~~~~~~~~~
BC30002: Type 'DoesntExist' is not defined.
Dim q10 As Object = From s As DoesntExist In q
~~~~~~~~~~~
BC36593: Expression of type 'Object' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q11 As Object = From s In Nothing
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub From2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As DoesntExist
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q10 As Object = From s In q
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
Public Function [Select](x As Func(Of Integer, Integer)) As DoesntExist
~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Byte In q
Dim q2 As Object = From s As Byte In q Select s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~
</expected>)
compilation = compilation.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte'.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q1 As Object = From s As Byte In q
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte'.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q2 As Object = From s As Byte In q Select s
~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q2 As Object = From s As Byte In q Select s
~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
Public Function Cast(Of T)() As DoesntExist
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q10 As Object = From s As Guid In q
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30002: Type 'DoesntExist' is not defined.
Public Function Cast(Of T)() As DoesntExist
~~~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Guid'.
Dim q10 As Object = From s As Guid In q
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q10 As Object = From s As Integer In q Select CType(s, Guid)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36593: Expression of type 'QueryAble' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Dim q10 As Object = From s As Integer In q Select CType(s, Guid)
~
BC30311: Value of type 'Integer' cannot be converted to 'Guid'.
Dim q10 As Object = From s As Integer In q Select CType(s, Guid)
~
</expected>)
End Sub
<Fact>
Public Sub ImplicitSelect4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Integer In q Where s > 1
System.Console.WriteLine("------")
Dim q2 As Object = From s As Long In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where
------
[Select]
[Where]
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Where1()
Dim source = <) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer?, Boolean?)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s'BIND:"From s In q Where s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble, IsInvalid) (Syntax: 'From s In q Where s')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: QueryAble, IsInvalid, IsImplicit) (Syntax: 'Where s')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Where s')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Nullable(Of System.Int32)) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsInvalid) (Syntax: 's')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where s'BIND:"From s In q Where s"
~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Boolean?'.
Dim q1 As Object = From s In q Where s'BIND:"From s In q Where s"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Where2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Date' cannot be converted to 'Boolean'.
Dim q1 As Object = From s In q Where s
~
</expected>)
End Sub
<Fact>
Public Sub Where3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Boolean?)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Date' cannot be converted to 'Boolean'.
Dim q1 As Object = From s In q Where s
~
</expected>)
End Sub
<Fact>
Public Sub Where4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
BC30311: Value of type 'Boolean' cannot be converted to 'Date'.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Date, Date)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Date, Object)) As QueryAble
System.Console.WriteLine("Where Object")
Return Me
End Function
Public Function Where(x As Func(Of Date, Boolean)) As QueryAble
System.Console.WriteLine("Where Boolean")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where Boolean
]]>)
End Sub
<Fact>
Public Sub Where6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("Where Byte")
Return Me
End Function
Public Function Where(x As Func(Of Integer, SByte)) As QueryAble
System.Console.WriteLine("Where SByte")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where Byte
]]>)
End Sub
<Fact>
Public Sub Where7()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("Where Long")
Return Me
End Function
Public Function Where(x As Func(Of Integer, System.DateTimeKind)) As QueryAble
System.Console.WriteLine("Where System.DateTimeKind")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
q.Where(Function(s) 0)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where Long
Where Long
]]>)
End Sub
<Fact>
Public Sub Where8()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("Where Byte")
Return Me
End Function
Public Function Where(x As Func(Of Integer, System.DateTimeKind)) As QueryAble
System.Console.WriteLine("Where System.DateTimeKind")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.DateTimeKind
]]>)
End Sub
<Fact>
Public Sub Where9()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, System.DateTimeKind)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where 0
q.Where(Function(s) 0)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30521: Overload resolution failed because no accessible 'Where' is most specific for these arguments:
'Public Function Where(x As Func(Of Integer, Byte)) As QueryAble': Not most specific.
'Public Function Where(x As Func(Of Integer, DateTimeKind)) As QueryAble': Not most specific.
q.Where(Function(s) 0)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where10()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, SByte)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30519: Overload resolution failed because no accessible 'Where' can be called without a narrowing conversion:
'Public Function Where(x As Func(Of Integer, Byte)) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'Byte'.
'Public Function Where(x As Func(Of Integer, SByte)) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'SByte'.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where10b()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Linq.Expressions
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Expression(Of Func(Of Integer, Byte))) As QueryAble
Return Me
End Function
Public Function Where(x As Expression(Of Func(Of Integer, SByte))) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Where CObj(s)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30519: Overload resolution failed because no accessible 'Where' can be called without a narrowing conversion:
'Public Function Where(x As Expression(Of Func(Of Integer, Byte))) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'Byte'.
'Public Function Where(x As Expression(Of Func(Of Integer, SByte))) As QueryAble': Return type of nested function matching parameter 'x' narrows from 'Boolean' to 'SByte'.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
Dim q1 As Object = From s In q Where CObj(s)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub Where11()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Where Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.Boolean]
]]>)
End Sub
<Fact>
Public Sub Where12()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
Public Function Where(x As Func(Of T, Object)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
Public Function Where(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Where Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.Boolean]
]]>)
End Sub
<Fact>
Public Sub Where13()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(x As Func(Of T, String)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Where Nothing
End Sub
End Module
</file>
</compilation>
Dim verifier = CompileAndVerify(compilationDef, options:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom),
expectedOutput:=
<![CDATA[
Where System.Func`2[System.Int32,System.String]
]]>)
CompilationUtils.AssertTheseDiagnostics(verifier.Compilation,
<expected>
BC42016: Implicit conversion from 'Boolean' to 'String'.
q = From s In q1 Where Nothing
~~~~~~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub While1_TakeWhile()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Take While s > 1'BIND:"From s In q Take While s > 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... While s > 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Take While s > 1')
Children(2):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 1')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'TakeWhile' is not accessible in this context.
Dim q1 As Object = From s In q Take While s > 1'BIND:"From s In q Take While s > 1"
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub While1_SkipWhile()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Skip While s > 1'BIND:"From s In q Skip While s > 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... While s > 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Skip While s > 1')
Children(2):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 1')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q2 As Object = From s In q Skip While s > 1'BIND:"From s In q Skip While s > 1"
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub While2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip While s > 0
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Take While s > 0
System.Console.WriteLine("-----")
Dim q3 As Object = From s In q Skip While s > 0 Take While 10 > s Skip While s > 0 Select s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
SkipWhile
-----
TakeWhile
-----
SkipWhile
TakeWhile
SkipWhile
Select
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub SkipWhile_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip While s > 0'BIND:"From s In q Skip While s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... While s > 0')
Expression:
IInvocationOperation ( Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip While s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub TakeWhile_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Take While s > 0'BIND:"From s In q Take While s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... While s > 0')
Expression:
IInvocationOperation ( Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Take While s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub TakeWhileAndSkipWhile_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("TakeWhile")
Return Me
End Function
Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("SkipWhile")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q3 As Object = From s In q Skip While s > 0 Take While 10 > s Skip While s > 0 Select s'BIND:"From s In q Skip While s > 0 Take While 10 > s Skip While s > 0 Select s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... 0 Select s')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip While s > 0')
Instance Receiver:
IInvocationOperation ( Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Take While 10 > s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip While s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '10 > s')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: '10 > s')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10 > s')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10 > s')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10 > s')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: '10 > s')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Distinct1()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Distinct'BIND:"From s In q Distinct"
Dim q2 As Object = From s In q Skip While s > 1 Distinct
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q Distinct')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Distinct')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Distinct' is not accessible in this context.
Dim q1 As Object = From s In q Distinct'BIND:"From s In q Distinct"
~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q2 As Object = From s In q Skip While s > 1 Distinct
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Distinct2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Distinct() As QueryAble
System.Console.WriteLine("Distinct")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Distinct
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Select s + 1 Distinct Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Distinct
-----
Select
Distinct
Distinct
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Distinct2_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Distinct() As QueryAble
System.Console.WriteLine("Distinct")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Distinct'BIND:"From s In q Distinct"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q Distinct')
Expression:
IInvocationOperation ( Function QueryAble.Distinct() As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub MultipleDistinct_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Distinct() As QueryAble
System.Console.WriteLine("Distinct")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Select s + 1 Distinct Distinct'BIND:"From s In q Select s + 1 Distinct Distinct"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... ct Distinct')
Expression:
IInvocationOperation ( Function QueryAble.Distinct() As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Distinct() As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s + 1')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's + 1')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(0)
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub SkipTake1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip 1
Dim q2 As Object = From s In q Skip While s > 1 Take 2
Dim q3 As Object = From s In q Skip While s > 1 Take DoesntExist
Dim q4 As Object = From s In q Take s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Skip' is not accessible in this context.
Dim q1 As Object = From s In q Skip 1
~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q2 As Object = From s In q Skip While s > 1 Take 2
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q3 As Object = From s In q Skip While s > 1 Take DoesntExist
~~~~~~~~~~
BC30451: 'DoesntExist' is not declared. It may be inaccessible due to its protection level.
Dim q3 As Object = From s In q Skip While s > 1 Take DoesntExist
~~~~~~~~~~~
BC30451: 's' is not declared. It may be inaccessible due to its protection level.
Dim q4 As Object = From s In q Take s
~
</expected>)
End Sub
<Fact>
Public Sub SkipTake2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Skip(count As Date) As QueryAble
System.Console.WriteLine("Skip {0}", count.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
Return Me
End Function
Public Function Take(count As Integer) As QueryAble
System.Console.WriteLine("Skip {0}", count)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip #12:00:00 AM#
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Take 1 Select s
System.Console.WriteLine("-----")
Dim q3 As Object = From s In q Select s + 1 Take 2
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Skip 1/1/0001 12:00:00 AM
-----
Skip 1
Select
-----
Select
Skip 2
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Skip_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Skip(count As Date) As QueryAble
System.Console.WriteLine("Skip {0}", count.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
Return Me
End Function
Public Function Take(count As Integer) As QueryAble
System.Console.WriteLine("Skip {0}", count)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Skip #12:00:00 AM#'BIND:"From s In q Skip #12:00:00 AM#"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... 2:00:00 AM#')
Expression:
IInvocationOperation ( Function QueryAble.Skip(count As System.DateTime) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Skip #12:00:00 AM#')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '#12:00:00 AM#')
ILiteralOperation (OperationKind.Literal, Type: System.DateTime, Constant: 01/01/0001 00:00:00) (Syntax: '#12:00:00 AM#')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Take_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Skip(count As Date) As QueryAble
System.Console.WriteLine("Skip {0}", count.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
Return Me
End Function
Public Function Take(count As Integer) As QueryAble
System.Console.WriteLine("Skip {0}", count)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Take 1 Select s'BIND:"From s In q Take 1 Select s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... 1 Select s')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Take(count As System.Int32) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Take 1')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub SkipTake3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Skip(x As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Skip Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Skip 0
]]>)
End Sub
<Fact>
Public Sub OrderBy1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Order s
Dim q2 As Object = From s In q Order By s Descending
Dim q3 As Object = From s In q Order By s Ascending
Dim q4 As Object = From s In q Skip While s > 1 Order By s
Dim q5 As Object = From s In q Skip While s > 1 Order By s Descending
Dim q6 As Object = From s In q Skip While s > 1 Order By s Ascending
Dim q7 As Object = From s In q Skip While s > 1 Order By DoesntExist
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
Dim q9 As Object = From s In q Order By s, s
Dim q10 As Object = From s In q Order By s, DoesntExist
Dim q11 As Object = From s In q Order By :
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q1 As Object = From s In q Order s
~~~~~
BC36605: 'By' expected.
Dim q1 As Object = From s In q Order s
~
BC36594: Definition of method 'OrderByDescending' is not accessible in this context.
Dim q2 As Object = From s In q Order By s Descending
~~~~~~~~
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q3 As Object = From s In q Order By s Ascending
~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q4 As Object = From s In q Skip While s > 1 Order By s
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q5 As Object = From s In q Skip While s > 1 Order By s Descending
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q6 As Object = From s In q Skip While s > 1 Order By s Ascending
~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q7 As Object = From s In q Skip While s > 1 Order By DoesntExist
~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q7 As Object = From s In q Skip While s > 1 Order By DoesntExist
~~~~~~~~~~~
BC36594: Definition of method 'SkipWhile' is not accessible in this context.
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Skip While s > 1 Order By DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q9 As Object = From s In q Order By s, s
~~~~~~~~
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q10 As Object = From s In q Order By s, DoesntExist
~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q10 As Object = From s In q Order By s, DoesntExist
~~~~~~~~~~~
BC30201: Expression expected.
Dim q11 As Object = From s In q Order By :
~
</expected>)
End Sub
<Fact>
Public Sub OrderBy2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Order By s, s
Dim q2 As Object = From s In q Order By s, s Descending
Dim q3 As Object = From s In q Order By s, s Ascending
Dim q4 As Object = From s In q Order By s, s, s
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
Dim q7 As Object = From s In q Order By s, s, DoesntExist
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q1 As Object = From s In q Order By s, s
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q2 As Object = From s In q Order By s, s Descending
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q3 As Object = From s In q Order By s, s Ascending
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q4 As Object = From s In q Order By s, s, s
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q7 As Object = From s In q Order By s, s, DoesntExist
~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q7 As Object = From s In q Order By s, s, DoesntExist
~~~~~~~~~~~
BC36594: Definition of method 'ThenBy' is not accessible in this context.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
~~~~~~~~~~~~
BC36610: Name 'DoesntExist3' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Select DoesntExist1 Order By DoesntExist2, DoesntExist3
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub OrderBy3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s In q Order By s, s
Dim q2 As Object = From s In q Order By s, s Descending
Dim q3 As Object = From s In q Order By s, s Ascending
Dim q4 As Object = From s In q Order By s, s, s
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
Dim q7 As Object = From s In q Order By s, s, DoesntExist
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
Dim q9 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2 Descending
Dim q10 As Object = From s In q Select s + 1 Order By s
Dim q11 As Object = From s In q Order By :
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q2 As Object = From s In q Order By s, s Descending
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q5 As Object = From s In q Order By s, s Ascending, s Descending
~
BC36594: Definition of method 'ThenByDescending' is not accessible in this context.
Dim q6 As Object = From s In q Order By s, s Descending, s Ascending
~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
Dim q7 As Object = From s In q Order By s, s, DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q8 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2
~~~~~~~~~~~~
BC36610: Name 'DoesntExist1' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2 Descending
~~~~~~~~~~~~
BC36610: Name 'DoesntExist2' is either not declared or not in the current scope.
Dim q9 As Object = From s In q Order By s, s, DoesntExist1, DoesntExist2 Descending
~~~~~~~~~~~~
BC36610: Name 's' is either not declared or not in the current scope.
Dim q10 As Object = From s In q Select s + 1 Order By s
~
BC30201: Expression expected.
Dim q11 As Object = From s In q Order By :
~
</expected>)
End Sub
<Fact>
Public Sub OrderBy4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q1 As Object = From s In q
Order By s, s, s Descending, s Ascending
Order By s Descending, s Descending, s
Order By s Ascending
Select s
System.Console.WriteLine("-----")
Dim q2 As Object = From s In q Select s + 1 Order By 0
System.Console.WriteLine("-----")
Dim q3 As Object = From s In q Order By s
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
OrderBy 0
ThenBy 1
ThenByDescending 2
ThenBy 3
OrderByDescending 4
ThenByDescending 5
ThenBy 6
OrderBy 7
Select 8
-----
Select 0
OrderBy 1
-----
OrderBy 0
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub OrderByAscending_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q3 As Object = From s In q Order By s'BIND:"From s In q Order By s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q Order By s')
Expression:
IInvocationOperation ( Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub OrderByDescending_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q3 As Object = From s In q Order By s Descending'BIND:"From s In q Order By s Descending"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... Descending')
Expression:
IInvocationOperation ( Function QueryAble.OrderByDescending(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub OrderByAscendingDescending_IOperation()
Dim source = <) As QueryAble
System.Console.WriteLine("Select {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenBy {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("OrderByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
System.Console.WriteLine("ThenByDescending {0}", v)
Return New QueryAble(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(0)
Dim q1 As Object = From s In q'BIND:"From s In q"
Order By s, s, s Descending, s Ascending
Order By s Descending, s Descending, s
Order By s Ascending
Select s
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... Select s')
Expression:
IInvocationOperation ( Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Select s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Ascending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenByDescending(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.OrderByDescending(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Ascending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenByDescending(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's Descending')
Instance Receiver:
IInvocationOperation ( Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Byte)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
IInvocationOperation ( Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 's')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Byte), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Byte) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's')
ReturnedValue:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub OrderBy5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function OrderBy(Of S)(x As Func(Of T, S)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Order By Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
OrderBy System.Func`2[System.Int32,System.Object]
]]>)
End Sub
<Fact>
Public Sub OrderBy6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Order By Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
OrderBy System.Func`2[System.Int32,System.Int32]
]]>)
End Sub
<Fact>
Public Sub Select6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q1 As IEnumerable = From s In New Integer() {1,-1} Select s, t=s*2 Where s > t
For Each v In q1
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q2 As IEnumerable = From s In New Integer() {1,-1} Select s, t=s*2 Select t, s
For Each v In q2
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s = 1, t = 2 }
{ s = 2, t = 3 }
------
{ s = -1, t = -2 }
------
{ t = 2, s = 1 }
{ t = -2, s = -1 }
]]>)
End Sub
<Fact>
Public Sub Select7()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim s As Integer = 0
Dim t As Integer = 0
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
Dim q1 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1, s1=s1+1
Dim q2 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1+1
Dim q3 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s2%=s1+1
Dim q4 As IEnumerable = From s1 In New Integer() {1,2} Select s1, GetHashCode=s1+1
Dim q5 As Object = From s1 In New Integer() {1,2} Select x1 = s1, x2 = x1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
~
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
~
BC30978: Range variable 't' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As IEnumerable = From s In New Integer() {1,2} Select s, t=s+1
~
BC36600: Range variable 's1' is already declared.
Dim q1 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1, s1=s1+1
~~
BC36600: Range variable 's1' is already declared.
Dim q1 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1, s1=s1+1
~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
Dim q2 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s1+1
~~~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q3 As IEnumerable = From s1 In New Integer() {1,2} Select s1, s2%=s1+1
~~~
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q4 As IEnumerable = From s1 In New Integer() {1,2} Select s1, GetHashCode=s1+1
~~~~~~~~~~~
BC36610: Name 'x1' is either not declared or not in the current scope.
Dim q5 As Object = From s1 In New Integer() {1,2} Select x1 = s1, x2 = x1
~~
</expected>)
End Sub
<Fact>
Public Sub Select8()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s In q Select x1 = s, x2 = s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q0 As Object = From s In q Select x1 = s, x2 = s
~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q0 As Object = From s In q Select x1 = s, x2 = s
~
</expected>)
End Sub
<Fact>
Public Sub Select9()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = From s In New Integer() {1, 2} Select s + 1
q0 = From s In New Integer() {1, 2} Select s + 1 Join s1 In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0 Join s1 In New Integer() {1, 2} On s Equals s1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
q0 = From s In New Integer() {1, 2} Select s + 1 Join s1 In New Integer() {1, 2} On s Equals s1
~~~~~
BC36610: Name 's' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Select s + 1 Join s1 In New Integer() {1, 2} On s Equals s1
~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0 Join s1 In New Integer() {1, 2} On s Equals s1
~~~~~
BC36610: Name 's' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Select s + 1 Where True Order By 1 Distinct Take While True Skip While False Skip 0 Take 0 Join s1 In New Integer() {1, 2} On s Equals s1
~
</expected>)
End Sub
<Fact>
Public Sub Select10()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Select Nothing
q = From s In q1 Select x=Nothing, y=Nothing
q = From s In q1 Let x = Nothing
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select System.Func`2[System.Int32,System.Object]
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Object,System.Object]]
Select System.Func`2[System.Int32,VB$AnonymousType_1`2[System.Int32,System.Object]]
]]>)
End Sub
<Fact>
Public Sub Let1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q1 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1, s3 = s2+s1
For Each v In q1
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q2 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1, s3 = s2+s1, s4 = s1+s2+s3
For Each v In q2
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q3 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1+1, s3 = s2+s1, s4 = s1+s2+s3, s5 = s1+s2+s3+s4
For Each v In q3
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q4 As IEnumerable = From s1 In New Integer() {2} Let s2 = s1+1 Let s3 = s2+s1, s4 = s1+s2+s3, s5 = s1+s2+s3+s4
For Each v In q4
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q5 As IEnumerable = From s1 In New Integer() {3} Let s2 = s1+1, s3 = s2+s1 Let s4 = s1+s2+s3, s5 = s1+s2+s3+s4
For Each v In q5
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q6 As IEnumerable = From s1 In New Integer() {4} Let s2 = s1+1, s3 = s2+s1, s4 = s1+s2+s3 Let s5 = s1+s2+s3+s4
For Each v In q6
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q7 As IEnumerable = From s1 In New Integer() {5} Select s1+1 Let s2 = 7
For Each v In q7
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
Dim q8 As IEnumerable = From s1 In New Integer() {5} Select s1+1 Let s2 = 7, s3 = 8
For Each v In q8
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, s2 = 2 }
------
{ s1 = 1, s2 = 2, s3 = 3 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 6 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 6, s5 = 12 }
------
{ s1 = 2, s2 = 3, s3 = 5, s4 = 10, s5 = 20 }
------
{ s1 = 3, s2 = 4, s3 = 7, s4 = 14, s5 = 28 }
------
{ s1 = 4, s2 = 5, s3 = 9, s4 = 18, s5 = 36 }
------
7
------
{ s2 = 7, s3 = 8 }
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Let_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1 + 1'BIND:"From s1 In New Integer() {1} Let s2 = s1 + 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (Syntax: 'From s1 In ... s2 = s1 + 1')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(selector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's2 = s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub LetMultipleVariables_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q1 As IEnumerable = From s1 In New Integer() {1} Let s2 = s1 + 1, s3 = s2 + s1'BIND:"From s1 In New Integer() {1} Let s2 = s1 + 1, s3 = s2 + s1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (Syntax: 'From s1 In ... 3 = s2 + s1')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 's3 = s2 + s1')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(selector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's2 = s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 + s1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 's2 + s1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2 + s1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2 + s1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2 + s1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 = s2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2 + s1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub LetMultipleClauses_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q5 As IEnumerable = From s1 In New Integer() {3} Let s2 = s1 + 1, s3 = s2 + s1 Let s4 = s1 + s2 + s3, s5 = s1 + s2 + s3 + s4'BIND:"From s1 In New Integer() {3} Let s2 = s1 + 1, s3 = s2 + s1 Let s4 = s1 + s2 + s3, s5 = s1 + s2 + s3 + s4"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)) (Syntax: 'From s1 In ... 2 + s3 + s4')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)(selector As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>), IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>)(selector As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>), IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>)(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>), IsImplicit) (Syntax: 's3 = s2 + s1')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(selector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's2 = s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {3}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 = s1 + 1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 + s1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>), IsImplicit) (Syntax: 's2 + s1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2 + s1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2 + s1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2 + s1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Let s2 = s1 ... 3 = s2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 = s2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2 + s1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's3 = s2 + s1')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's2 + s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's2 + s1')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>), IsImplicit) (Syntax: 's1 + s2 + s3')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>) As <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Let s4 = s1 ... 2 + s3 + s4')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Right:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + s2 + s3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's4 = s1 + s2 + s3')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2 + s3')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's3')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>), IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Initializers(5):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's4 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>.s5 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32, Key s5 As System.Int32>, IsImplicit) (Syntax: 's5 = s1 + s2 + s3 + s4')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2 + s3 + s4')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2 + s3')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + s2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.$VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's3')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.$VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's4')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, Key s3 As System.Int32>, Key s4 As System.Int32>, IsImplicit) (Syntax: 's1 + s2 + s3 + s4')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Let2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object = From s In New Integer() {1, 2} Let s.GetHashCode
Dim q1 As Object = From s In New Integer() {1, 2} Let =s.GetHashCode
Dim q2 As Object = From s In New Integer() {1, 2} Let _=s.GetHashCode
Dim q3 As Object = From s In New Integer() {1, 2} Let
Dim q4 As Object = From s In New Integer() {1, 2} Let t
Dim q5 As Object = From s In New Integer() {1, 2} Let t=
Dim q6 As Object = From s In New Integer() {1, 2} Let t1=, t2=s
Dim q7 As Object = From s In New Integer() {1, 2} Let t% = s
Dim q8 As Object = From s In New Integer() {1, 2} Let t% As Integer = s
Dim q9 As Object = From s In New Integer() {1, 2} Let t? As Integer = s
Dim q10 As Object = From s In New Integer() {1, 2} Let t? = s
Dim q11 As Object = From s In New Integer() {1, 2} Select t? As Integer = s
Dim q12 As Object = From s In New Integer() {1, 2} Select t As Integer = s
Dim q13 As Object = From s In New Integer() {1, 2} Let q0 = s + 1
Dim q14 As Object = From s In New Integer() {1, 2} Let s1 = s + 1, s1 = s + 2
Dim q15 As Object = From s In New Integer() {1, 2} Let s = s + 1
Dim q16 As Object = From s In New Integer() {1, 2} Let s1 As Date = s
Dim q17 As Object = From s In New Integer() {1, 2} Let s1? As Byte = s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q0 As Object = From s In New Integer() {1, 2} Let s.GetHashCode
~
BC32020: '=' expected.
Dim q0 As Object = From s In New Integer() {1, 2} Let s.GetHashCode
~
BC30203: Identifier expected.
Dim q1 As Object = From s In New Integer() {1, 2} Let =s.GetHashCode
~
BC30203: Identifier expected.
Dim q2 As Object = From s In New Integer() {1, 2} Let _=s.GetHashCode
~
BC30203: Identifier expected.
Dim q3 As Object = From s In New Integer() {1, 2} Let
~
BC32020: '=' expected.
Dim q3 As Object = From s In New Integer() {1, 2} Let
~
BC32020: '=' expected.
Dim q4 As Object = From s In New Integer() {1, 2} Let t
~
BC30201: Expression expected.
Dim q5 As Object = From s In New Integer() {1, 2} Let t=
~
BC30201: Expression expected.
Dim q6 As Object = From s In New Integer() {1, 2} Let t1=, t2=s
~
BC36601: Type characters cannot be used in range variable declarations.
Dim q7 As Object = From s In New Integer() {1, 2} Let t% = s
~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q8 As Object = From s In New Integer() {1, 2} Let t% As Integer = s
~~
BC36629: Nullable type inference is not supported in this context.
Dim q10 As Object = From s In New Integer() {1, 2} Let t? = s
~
BC36610: Name 't' is either not declared or not in the current scope.
Dim q11 As Object = From s In New Integer() {1, 2} Select t? As Integer = s
~
BC36637: The '?' character cannot be used here.
Dim q11 As Object = From s In New Integer() {1, 2} Select t? As Integer = s
~
BC36610: Name 't' is either not declared or not in the current scope.
Dim q12 As Object = From s In New Integer() {1, 2} Select t As Integer = s
~
BC30205: End of statement expected.
Dim q12 As Object = From s In New Integer() {1, 2} Select t As Integer = s
~~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q13 As Object = From s In New Integer() {1, 2} Let q0 = s + 1
~~
BC30978: Range variable 's1' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q14 As Object = From s In New Integer() {1, 2} Let s1 = s + 1, s1 = s + 2
~~
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q15 As Object = From s In New Integer() {1, 2} Let s = s + 1
~
BC30311: Value of type 'Integer' cannot be converted to 'Date'.
Dim q16 As Object = From s In New Integer() {1, 2} Let s1 As Date = s
~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
Dim q17 As Object = From s In New Integer() {1, 2} Let s1? As Byte = s
~
</expected>)
End Sub
<Fact>
Public Sub Let3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
'Inherits Base
'Public Shadows [Select] As Byte
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s In q Let t1 = s + 1
System.Console.WriteLine("------")
Dim q1 As Object = From s In q Let t1 = s + 1, t2 = t1
System.Console.WriteLine("------")
Dim q2 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
System.Console.WriteLine("------")
Dim q3 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2, t4 = t3
System.Console.WriteLine("------")
Dim q4 As Object = From s In q Let t1 = s + 1 Let t2 = t1, t3 = t2, t4 = t3
System.Console.WriteLine("------")
Dim q5 As Object = From s In q Let t1 = s + 1, t2 = t1 Let t3 = t2, t4 = t3
System.Console.WriteLine("------")
Dim q6 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Let t4 = t3
System.Console.WriteLine("------")
Dim q7 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Select s, t1, t2, t3, t4 = t3
System.Console.WriteLine("------")
Dim q8 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
Dim q9 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0 Select s, t1, t2, t3, t4 = t3
System.Console.WriteLine("------")
Dim q10 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0 Let t4 = 1
System.Console.WriteLine("------")
Dim q11 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2 Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0 From t4 In q
System.Console.WriteLine("------")
Dim q12 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Join t4 in q On t3 Equals t4
System.Console.WriteLine("------")
Dim q13 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group s By t3 Into Group
System.Console.WriteLine("------")
Dim q14 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group By t3 Into Group
System.Console.WriteLine("------")
Dim q15 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group Join t4 in q On t3 Equals t4 Into Group
System.Console.WriteLine("------")
Dim q16 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 in q Into Where(True)
System.Console.WriteLine("------")
Dim q17 As Object = From s In q Let t1 = s + 1, t2 = t1, t3 = t2
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 in q Into Where(True), Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_1`3[System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
Skip 0
Take 0
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32,VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32,VB$AnonymousType_5`5[System.Int32,System.Int32,System.Int32,System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,System.Int32,System.Int32],System.Boolean]
Skip 0
Take 0
GroupBy
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],QueryAble`1[System.Int32],VB$AnonymousType_7`5[System.Int32,System.Int32,System.Int32,System.Int32,QueryAble`1[System.Int32]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_8`5[System.Int32,System.Int32,System.Int32,System.Int32,QueryAble`1[System.Int32]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],VB$AnonymousType_9`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],QueryAble`1[System.Int32]]]
Select System.Func`2[VB$AnonymousType_9`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],System.Int32],System.Int32],QueryAble`1[System.Int32]],VB$AnonymousType_10`6[System.Int32,System.Int32,System.Int32,System.Int32,QueryAble`1[System.Int32],QueryAble`1[System.Int32]]]
]]>)
End Sub
<Fact>
Public Sub Let4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble1
Return nothing
End Function
End Class
Class QueryAble1
Public Function [Select](Of T, S)(x As Func(Of T, S)) As QueryAble2
Return Nothing
End Function
End Class
Class QueryAble2
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s In q Let t1 = s + 1
Dim q1 As Object = From s In q Where s>0 Let t1 = s + 1, t2 = t1
Dim q2 As Object = From s In q Select s1 Let t1 = s1 + 1
Dim q3 As Object = From s In q Where s>0 Let s1 + 1, t2 = t12
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q0 As Object = From s In q Let t1 = s + 1
~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
Dim q0 As Object = From s In q Let t1 = s + 1
~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
Dim q1 As Object = From s In q Where s>0 Let t1 = s + 1, t2 = t1
~
BC36610: Name 's1' is either not declared or not in the current scope.
Dim q2 As Object = From s In q Select s1 Let t1 = s1 + 1
~~
BC32020: '=' expected.
Dim q3 As Object = From s In q Where s>0 Let s1 + 1, t2 = t12
~
BC36610: Name 't12' is either not declared or not in the current scope.
Dim q3 As Object = From s In q Where s>0 Let s1 + 1, t2 = t12
~~~
</expected>)
End Sub
<Fact>
Public Sub From3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3}, s3 In New Integer() {4, 5}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} From s2 In New Integer() {2, 3}, s3 In New Integer() {6, 7}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} From s3 In New Integer() {8, 9}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, -1} Select s1 + 1 From s2 In New Integer() {2, 3}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, -1} Select s1 + 1 From s2 In New Integer() {2, 3}, s3 In New Integer() {4, 5}
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} Select s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} Let s3 = s1 + s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}, s2 In New Integer() {2, 3} Let s3 = s1 + s2, s4 = s3 + 1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 2} Select s1 + 1 From s2 In New Integer() {2, 3} Select s3 = 4, s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 2} Select s1 + 1 From s2 In New Integer() {2, 3} Let s3 = 5
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer()() {New Integer() {1, 2}, New Integer() {2, 3}}, s2 In s1 Select s3 = s1(0), s2
For Each v In q0
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, s2 = 2 }
{ s1 = 1, s2 = 3 }
------
{ s1 = 1, s2 = 2, s3 = 4 }
{ s1 = 1, s2 = 2, s3 = 5 }
{ s1 = 1, s2 = 3, s3 = 4 }
{ s1 = 1, s2 = 3, s3 = 5 }
------
{ s1 = 1, s2 = 2, s3 = 6 }
{ s1 = 1, s2 = 2, s3 = 7 }
{ s1 = 1, s2 = 3, s3 = 6 }
{ s1 = 1, s2 = 3, s3 = 7 }
------
{ s1 = 1, s2 = 2, s3 = 8 }
{ s1 = 1, s2 = 2, s3 = 9 }
{ s1 = 1, s2 = 3, s3 = 8 }
{ s1 = 1, s2 = 3, s3 = 9 }
------
2
3
2
3
------
{ s2 = 2, s3 = 4 }
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 4 }
{ s2 = 3, s3 = 5 }
{ s2 = 2, s3 = 4 }
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 4 }
{ s2 = 3, s3 = 5 }
------
{ s2 = 2, s1 = 1 }
{ s2 = 3, s1 = 1 }
------
{ s1 = 1, s2 = 2, s3 = 3 }
{ s1 = 1, s2 = 3, s3 = 4 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4 }
{ s1 = 1, s2 = 3, s3 = 4, s4 = 5 }
------
{ s3 = 4, s2 = 2 }
{ s3 = 4, s2 = 3 }
{ s3 = 4, s2 = 2 }
{ s3 = 4, s2 = 3 }
------
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 5 }
{ s2 = 2, s3 = 5 }
{ s2 = 3, s3 = 5 }
------
{ s3 = 1, s2 = 1 }
{ s3 = 1, s2 = 2 }
{ s3 = 2, s2 = 2 }
{ s3 = 2, s2 = 3 }
]]>)
End Sub
<Fact>
Public Sub From4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object = From s In New Integer() {1, 2} From GetHashCode
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
Dim q2 As Object = From s In New Integer() {1, 2} From _ In New Integer() {1, 2}
Dim q3 As Object = From s In New Integer() {1, 2} From
Dim q4 As Object = From s In New Integer() {1, 2} From t
Dim q5 As Object = From s In New Integer() {1, 2} From t In
Dim q6 As Object = From s In New Integer() {1, 2} From t1 In , t2 In New Integer() {1, 2}
Dim q7 As Object = From s In New Integer() {1, 2} From t% In New Integer() {1, 2}
Dim q8 As Object = From s In New Integer() {1, 2} From t% As Integer In New Integer() {1, 2}
Dim q9 As Object = From s In New Integer() {1, 2} From t? As Integer In New Integer() {1, 2}
Dim q10 As Object = From s In New Integer() {1, 2} From t? In New Integer() {1, 2}
Dim q11 As Object = From s In New Integer() {1, 2} From t In New Integer() {1, 2},
Dim q12 As Object = From s In New Integer() {1, 2} From t1 In New Integer() {1, 2}, t2 In
Dim q13 As Object = From s In New Integer() {1, 2} From q0 In New Integer() {1, 2}
Dim q14 As Object = From s In New Integer() {1, 2} From s1 In New Integer() {1, 2}, s1 In New Integer() {1, 2}
Dim q15 As Object = From s In New Integer() {1, 2} From s In New Integer() {1, 2}
Dim q16 As Object = From s In New Integer() {1, 2} From s1 As Date In New Integer() {1, 2}
Dim q17 As Object = From s In New Integer() {1, 2} From s1? As Byte In New Integer() {1, 2}
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
Dim q0 As Object = From s In New Integer() {1, 2} From GetHashCode
~~~~~~~~~~~
BC36607: 'In' expected.
Dim q0 As Object = From s In New Integer() {1, 2} From GetHashCode
~
BC30183: Keyword is not valid as an identifier.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~~
BC36607: 'In' expected.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~
BC36607: 'In' expected.
Dim q1 As Object = From s In New Integer() {1, 2} From In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q2 As Object = From s In New Integer() {1, 2} From _ In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q3 As Object = From s In New Integer() {1, 2} From
~
BC36607: 'In' expected.
Dim q3 As Object = From s In New Integer() {1, 2} From
~
BC36607: 'In' expected.
Dim q4 As Object = From s In New Integer() {1, 2} From t
~
BC30201: Expression expected.
Dim q5 As Object = From s In New Integer() {1, 2} From t In
~
BC30201: Expression expected.
Dim q6 As Object = From s In New Integer() {1, 2} From t1 In , t2 In New Integer() {1, 2}
~
BC36601: Type characters cannot be used in range variable declarations.
Dim q7 As Object = From s In New Integer() {1, 2} From t% In New Integer() {1, 2}
~~
BC36601: Type characters cannot be used in range variable declarations.
Dim q8 As Object = From s In New Integer() {1, 2} From t% As Integer In New Integer() {1, 2}
~~
BC36629: Nullable type inference is not supported in this context.
Dim q10 As Object = From s In New Integer() {1, 2} From t? In New Integer() {1, 2}
~
BC30203: Identifier expected.
Dim q11 As Object = From s In New Integer() {1, 2} From t In New Integer() {1, 2},
~
BC36607: 'In' expected.
Dim q11 As Object = From s In New Integer() {1, 2} From t In New Integer() {1, 2},
~
BC30201: Expression expected.
Dim q12 As Object = From s In New Integer() {1, 2} From t1 In New Integer() {1, 2}, t2 In
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q13 As Object = From s In New Integer() {1, 2} From q0 In New Integer() {1, 2}
~~
BC30978: Range variable 's1' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q14 As Object = From s In New Integer() {1, 2} From s1 In New Integer() {1, 2}, s1 In New Integer() {1, 2}
~~
BC30978: Range variable 's' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q15 As Object = From s In New Integer() {1, 2} From s In New Integer() {1, 2}
~
BC30311: Value of type 'Integer' cannot be converted to 'Date'.
Dim q16 As Object = From s In New Integer() {1, 2} From s1 As Date In New Integer() {1, 2}
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
Dim q17 As Object = From s In New Integer() {1, 2} From s1? As Byte In New Integer() {1, 2}
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub From5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q0 As Object
q0 = From s1 In qi From s2 In qb
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu, s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb From s3 In qs, s4 In qu, s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs From s4 In qu, s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu From s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0 From s5 In ql
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0 Let s5 = 1L
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0 Select s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Select s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Select s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Let s3 = 1L
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Let s5 = 1L
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Let s3 = 1S, s4 = 1UI
System.Console.WriteLine("------")
q0 = From s1 In qi, s2 In qb Let s3 = 1S Let s4 = 1UI
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Let s5 = 1L Select s5, s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi Select s1 + 1 From s2 In qb
System.Console.WriteLine("------")
q0 = From s1 In qi Select s1 + 1 From s2 In qb Select s2, s3 = 1S
System.Console.WriteLine("------")
q0 = From s1 In qi Select s1 + 1 From s2 In qb Let s3 = 1S
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Join s5 In ql On s1 Equals s5
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group s1 By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group Join s5 In ql On s1 Equals s5 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s5 In ql Into Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi From s2 In qb, s3 In qs, s4 In qu Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s5 In ql Into Where(True), Distinct
System.Console.WriteLine("------")
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
Skip 0
Take 0
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_6`4[System.UInt32,System.Int16,System.Byte,System.Int32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_7`2[System.Byte,System.Int32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_6`4[System.UInt32,System.Int16,System.Byte,System.Int32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16]]
Select System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16],VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16]]
Select System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Byte,System.Int16],VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_8`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,System.Int64]]
Select System.Func`2[VB$AnonymousType_8`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,System.Int64],VB$AnonymousType_9`5[System.Int64,System.UInt32,System.Int16,System.Byte,System.Int32]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,System.Byte]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_10`2[System.Byte,System.Int16]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_10`2[System.Byte,System.Int16]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int64,VB$AnonymousType_5`5[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Byte,System.Int16,System.UInt32],System.Boolean]
Skip 0
Take 0
GroupBy
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],QueryAble`1[System.Int64],VB$AnonymousType_12`5[System.Int32,System.Byte,System.Int16,System.UInt32,QueryAble`1[System.Int64]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_13`5[System.Int32,System.Byte,System.Int16,System.UInt32,QueryAble`1[System.Int64]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
SelectMany System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32,VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],VB$AnonymousType_14`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],QueryAble`1[System.Int64]]]
Select System.Func`2[VB$AnonymousType_14`2[VB$AnonymousType_4`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],System.UInt32],QueryAble`1[System.Int64]],VB$AnonymousType_15`6[System.Int32,System.Byte,System.Int16,System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Int64]]]
------
]]>)
End Sub
<Fact>
Public Sub From6()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble1
Return nothing
End Function
End Class
Class QueryAble1
Public Function SelectMany(Of S)(x As Func(Of Integer, QueryAble), y As Func(Of Integer, Integer, S)) As QueryAble2
Return Nothing
End Function
End Class
Class QueryAble2
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s In q From t1 In q
Dim q1 As Object = From s In q Where s>0 From t1 In q, t2 In q
Dim q2 As Object = From s In q Select s1 From t1 In q
Dim q3 As Object = From s In q Where s>0 From _ In q, t2 In q
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'SelectMany' is not accessible in this context.
Dim q0 As Object = From s In q From t1 In q
~~~~
BC36594: Definition of method 'SelectMany' is not accessible in this context.
Dim q1 As Object = From s In q Where s>0 From t1 In q, t2 In q
~
BC36610: Name 's1' is either not declared or not in the current scope.
Dim q2 As Object = From s In q Select s1 From t1 In q
~~
BC30203: Identifier expected.
Dim q3 As Object = From s In q Where s>0 From _ In q, t2 In q
~
BC36594: Definition of method 'SelectMany' is not accessible in this context.
Dim q3 As Object = From s In q Where s>0 From _ In q, t2 In q
~
</expected>)
End Sub
<Fact>
Public Sub Join1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
q0 = From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s1 Equals s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s2 + 1 Equals s1 + 2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 On s1 + 1 Equals s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Select s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 Select s3, s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 On s1 + 1 Equals s2 Select s3, s2, s1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Let s3 = s1 + s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 Let s4 = s1 + s2 + s3
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 On s1 + 1 Equals s2 Let s4 = s1 + s2 + s3
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Let s3 = s1 + s2, s4 = s3 + 1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s3 + 1 Equals s4
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s3 + 1 Equals s4
Select s1 + s2 + s3 + s4 + s5 + s6
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s3 + 1 Equals s4
Let s7 = s1 + s2 + s3 + s4 + s5 + s6
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New IComparable() {New Guid("F31A2538-E129-437E-AD69-B484F979246E")}
Join s2 In New Guid() {New Guid("F31A2538-E129-437E-AD69-B484F979246E")} On s1 Equals s2
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New String() {"1", "2"}
Join s2 In New Integer() {2, 3} On s1 Equals s2 - 1
For Each v In q0
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
q0 = From s1 In New Integer() {1, 2, 3, 4, 5}
Join s2 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 * 2 Equals s2
Join s3 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 + 1 Equals s3 And s2 - 1 Equals s3 + 1
For Each v In q0
System.Console.WriteLine(v)
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 3, s2 = 3 }
------
{ s1 = 1, s2 = 2 }
------
{ s1 = 1, s2 = 2, s3 = 4 }
------
{ s1 = 1, s2 = 2, s3 = 4 }
------
{ s2 = 2, s1 = 1 }
------
{ s3 = 4, s2 = 2, s1 = 1 }
------
{ s3 = 4, s2 = 2, s1 = 1 }
------
{ s1 = 1, s2 = 2, s3 = 3 }
------
{ s1 = 1, s2 = 2, s3 = 4, s4 = 7 }
------
{ s1 = 1, s2 = 2, s3 = 4, s4 = 7 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4 }
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4, s5 = 5, s6 = 6 }
------
21
------
{ s1 = 1, s2 = 2, s3 = 3, s4 = 4, s5 = 5, s6 = 6, s7 = 21 }
------
{ s1 = f31a2538-e129-437e-ad69-b484f979246e, s2 = f31a2538-e129-437e-ad69-b484f979246e }
------
{ s1 = 1, s2 = 2 }
{ s1 = 2, s2 = 3 }
------
{ s1 = 3, s2 = 6, s3 = 4 }
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub Join_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable = From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s1 Equals s2'BIND:"From s1 In New Integer() {1, 3} Join s2 In New Integer() {2, 3} On s1 Equals s2"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (Syntax: 'From s1 In ... 1 Equals s2')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, s2 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub JoinMultiple_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
q0 = From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2'BIND:"From s1 In New Integer() {1} Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (Syntax: 'From s1 In ... uals s2 * 2')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>).Join(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, s2 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s2 In ... 1 Equals s2')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {4, 5}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {4, 5}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{4, 5}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32), IsImplicit) (Syntax: 's3')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's3')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's2 * 2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 's3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 * 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2 * 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s3 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2 * 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2 * 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2 * 2')
ReturnedValue:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's3')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, s3 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join s3 In ... uals s2 * 2')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Join2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = From s In New Integer() {1, 2} Join GetHashCode
q0 = From s In New Integer() {1, 2} Join s1 In
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s Equals
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join _ In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join
q0 = From s In New Integer() {1, 2} Join t
q0 = From s In New Integer() {1, 2} Join t1 In Join t2 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join t% In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t% As Integer In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t? As Integer In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t? In New Integer() {1, 2} On s Equals t
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
q0 = From s In New Integer() {1, 2} Join q0 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1 As Date In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1? As Byte In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1 In New String() {"1"} On s Equals s1
q0 = From s In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 Join s1 In New Integer() {1, 2} On s Equals s1
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 Equals s2 + s1
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s2
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s1
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 Equals 0 + 1 + 2
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 Equals 0
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 Equals 0
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s1 + s4 + s6 Equals s2 + s5 + s3
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2
Join s3 In New Integer() {3, 4}
On s2 + 1 Equals s3
Join s4 In New Integer() {4, 5}
Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5
Join s6 In New Integer() {6, 7}
On s5 + 1 Equals s6
On s1 + s4 + s3 Equals s2 + s5 + s6
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals 0 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 + DoesntExist Equals 0 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals 0 + 1 + 2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals 0 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s2 + DoesntExist
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + s2 + DoesntExist
q0 = From s1 In New Date() {} Join s2 In New Guid() {} On s1 Equals s2
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
q0 = From s1 In New Integer() {1, 2, 3, 4, 5}
Join s2 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 * 2 Equals s2
Join s3 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 + 1 Equals s3 And s2 - 1 Equals s3 + s1
q0 = From s1 In New Integer() {1}
Join s1 In New Integer() {10} On s1 * 2 Equals 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
q0 = From s In New Integer() {1, 2} Join GetHashCode
~~~~~~~~~~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join GetHashCode
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join GetHashCode
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On s Equals
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} On _ Equals _
~
BC30183: Keyword is not valid as an identifier.
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join _ In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join _ In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join t
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t
~
BC30451: 'Join' is not declared. It may be inaccessible due to its protection level.
q0 = From s In New Integer() {1, 2} Join t1 In Join t2 In New Integer() {1, 2}
~~~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t1 In Join t2 In New Integer() {1, 2}
~
BC36601: Type characters cannot be used in range variable declarations.
q0 = From s In New Integer() {1, 2} Join t% In New Integer() {1, 2} On s Equals t
~~
BC36601: Type characters cannot be used in range variable declarations.
q0 = From s In New Integer() {1, 2} Join t% As Integer In New Integer() {1, 2} On s Equals t
~~
BC36629: Nullable type inference is not supported in this context.
q0 = From s In New Integer() {1, 2} Join t? In New Integer() {1, 2} On s Equals t
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t In New Integer() {1, 2} Join
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join t1 In New Integer() {1, 2} Join t2 In
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = From s In New Integer() {1, 2} Join q0 In New Integer() {1, 2}
~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join q0 In New Integer() {1, 2}
~
BC36600: Range variable 's1' is already declared.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s1 In New Integer() {1, 2}
~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 On s Equals s1
~
BC36610: Name 's' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 On s Equals s1
~
BC30311: Value of type 'Integer' cannot be converted to 'Date'.
q0 = From s In New Integer() {1, 2} Join s1 As Date In New Integer() {1, 2} On s Equals s1
~~~~~~~
BC36621: 'Equals' cannot compare a value of type 'Integer' with a value of type 'Date'.
q0 = From s In New Integer() {1, 2} Join s1 As Date In New Integer() {1, 2} On s Equals s1
~~~~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'.
q0 = From s In New Integer() {1, 2} Join s1? As Byte In New Integer() {1, 2} On s Equals s1
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'String' to 'Double'.
q0 = From s In New Integer() {1, 2} Join s1 In New String() {"1"} On s Equals s1
~~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 Join s1 In New Integer() {1, 2} On s Equals s1
~
BC36610: Name 's1' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Join s In New Integer() {1, 2} On s Equals s1 Join s1 In New Integer() {1, 2} On s Equals s1
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 Equals s2 + s1
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 Equals s2 + s1
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s2
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 Equals s1
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 Equals 0 + 1 + 2
~~~~~~~~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 Equals 0
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 Equals 0
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1' must appear on one side of the 'Equals' operator, and range variable(s) 's2' must appear on the other.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 Equals 0
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s6 Equals s2 + s5 + s3
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s3 Equals s2 + s5 + s6
~~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2', 's3' must appear on one side of the 'Equals' operator, and range variable(s) 's4', 's5', 's6' must appear on the other.
On s1 + s4 + s3 Equals s2 + s5 + s6
~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 1 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On 0 + DoesntExist Equals s2 + s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals 0 + 1 + 2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals 0 + 1 + 2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s1 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals 0 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = From s1 In New Integer() {1, 2} Join s2 In New Integer() {1, 2} On s2 + DoesntExist Equals s1 + s2 + DoesntExist
~~~~~~~~~~~
BC36621: 'Equals' cannot compare a value of type 'Date' with a value of type 'Guid'.
q0 = From s1 In New Date() {} Join s2 In New Guid() {} On s1 Equals s2
~~~~~~~~~~~~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
~
BC36622: You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) 's1', 's2' must appear on one side of the 'Equals' operator, and range variable(s) 's3' must appear on the other.
Join s3 In New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} On s1 + 1 Equals s3 And s2 - 1 Equals s3 + s1
~~
BC36600: Range variable 's1' is already declared.
Join s1 In New Integer() {10} On s1 * 2 Equals 0
~~
</expected>)
End Sub
<Fact>
Public Sub Join3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim qd As New QueryAble(Of Double)(0)
Dim q0 As Object
q0 = From s1 In qi Join s2 In qb On s1 Equals s2
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Select s6, s5, s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Let s7 = s6 + s5 + s4 + s3 + s2 + s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Select s6, s5, s4, s3, s2, s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Let s7 = s6 + s5 + s4 + s3 + s2 + s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Join s7 In qd On s1 Equals s7
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
From s7 In qd
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group s1 By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group By s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group Join s7 In qd On s1 Equals s7 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Join s2 In qb
On s1 + 1 Equals s2
Join s3 In qs
On s2 + 1 Equals s3
Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s5 + 1 Equals s6
On s1 + s2 + s3 Equals s4 + s5 + s6
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True), Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_5`6[System.Double,System.Int64,System.UInt32,System.Int16,System.Byte,System.Int32]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double]]
Where System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
Skip 0
Take 0
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_5`6[System.Double,System.Int64,System.UInt32,System.Int16,System.Byte,System.Int32]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Double,VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Double,VB$AnonymousType_6`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,System.Double]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double]]
Where System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_2`6[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double],System.Boolean]
Skip 0
Take 0
GroupBy
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],QueryAble`1[System.Double],VB$AnonymousType_9`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,QueryAble`1[System.Double]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_10`7[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,QueryAble`1[System.Double]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_0`2[System.Int32,System.Byte]]
Join System.Func`3[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16,VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16]]
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_3`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double],VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]]]
Where System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],VB$AnonymousType_11`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],QueryAble`1[System.Double]]]
Select System.Func`2[VB$AnonymousType_11`2[VB$AnonymousType_7`2[VB$AnonymousType_1`2[VB$AnonymousType_0`2[System.Int32,System.Byte],System.Int16],VB$AnonymousType_4`2[VB$AnonymousType_3`2[System.UInt32,System.Int64],System.Double]],QueryAble`1[System.Double]],VB$AnonymousType_12`8[System.Int32,System.Byte,System.Int16,System.UInt32,System.Int64,System.Double,QueryAble`1[System.Double],QueryAble`1[System.Double]]]
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Join4()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s1 In q Join t1 In q On s1 Equals t1'BIND:"From s1 In q Join t1 In q On s1 Equals t1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s1 In ... 1 Equals t1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Children(5):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
IAnonymousFunctionOperation (Symbol: Function (t1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 't1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 't1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 't1')
ReturnedValue:
IParameterReferenceOperation: t1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 't1')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, t1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In q')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 't1 In q')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>.t1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 't1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key t1 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join t1 In ... 1 Equals t1')
Right:
IParameterReferenceOperation: t1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 't1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'Join' is not accessible in this context.
Dim q0 As Object = From s1 In q Join t1 In q On s1 Equals t1'BIND:"From s1 In q Join t1 In q On s1 Equals t1"
~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupBy1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As IEnumerable
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1, s1str = CStr(s1) By s1 = s1 Mod 2, s2 = s1 Mod 3 Into gr = Group, c = Count(), Max(s1)
System.Console.WriteLine(v)
For Each gv In v.gr
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group Join s1 In New Integer() {1, 2} On key Equals s1
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Count(s1 - 2)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, Group = System.Int32[] }
1
{ s1 = 2, Group = System.Int32[] }
2
2
{ s1 = 3, Group = System.Int32[] }
3
3
{ s1 = 4, Group = System.Int32[] }
4
------
{ s1 = 1, Count = 1 }
{ s1 = 2, Count = 2 }
{ s1 = 3, Count = 2 }
{ s1 = 4, Count = 1 }
------
{ s1 = 1, Group = System.Int32[] }
1
{ s1 = 2, Group = System.Int32[] }
2
2
{ s1 = 3, Group = System.Int32[] }
3
3
{ s1 = 4, Group = System.Int32[] }
4
------
{ s1 = 1, Count = 1 }
{ s1 = 2, Count = 2 }
{ s1 = 3, Count = 2 }
{ s1 = 4, Count = 1 }
------
{ s1 = 1, s2 = 1, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 1, Max = 1 }
{ s1 = 1, s1str = 1 }
{ s1 = 0, s2 = 2, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 2, Max = 2 }
{ s1 = 2, s1str = 2 }
{ s1 = 2, s1str = 2 }
{ s1 = 1, s2 = 0, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 2, Max = 3 }
{ s1 = 3, s1str = 3 }
{ s1 = 3, s1str = 3 }
{ s1 = 0, s2 = 1, gr = VB$AnonymousType_2`2[System.Int32,System.String][], c = 1, Max = 4 }
{ s1 = 4, s1str = 4 }
------
{ key = 1, Group = System.Int32[] }
2
3
------
{ key = 1, Group = System.Int32[], s1 = 1 }
2
3
------
{ s1 = 1, Count = 1 }
{ s1 = 2, Count = 0 }
{ s1 = 3, Count = 2 }
{ s1 = 4, Count = 1 }
------
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_GroupAggregation_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Group'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Group"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(keySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By s1 Into Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By s1 Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By s1 Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By s1 Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By s1 Into Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_FunctionAggregation_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Count()'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group By s1 Into Count()"
System.Console.WriteLine(v)
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)) (Syntax: 'From s1 In ... nto Count()')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)(keySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>), IsImplicit) (Syntax: 'Group By s1 Into Count()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>), IsImplicit) (Syntax: 'Group By s1 Into Count()')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group By s1 Into Count()')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>, IsImplicit) (Syntax: 'Group By s1 Into Count()')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>, IsImplicit) (Syntax: 'Group By s1 Into Count()')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Count As System.Int32>, IsImplicit) (Syntax: 'Group By s1 Into Count()')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By s1 Into Count()')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_WithOptionalGroupClause_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Group'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1 By s1 Into Group"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(keySelector As System.Func(Of System.Int32, System.Int32), elementSelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: elementSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group s1 By ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group s1 By ... Into Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_MultipleAggregations_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1, s1str = CStr(s1) By s1 = s1 Mod 2, s2 = s1 Mod 3 Into gr = Group, c = Count(), Max(s1)'BIND:"From s1 In New Integer() {1, 2, 3, 4, 2, 3} Group s1, s1str = CStr(s1) By s1 = s1 Mod 2, s2 = s1 Mod 3 Into gr = Group, c = Count(), Max(s1)"
System.Console.WriteLine(v)
For Each gv In v.gr
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)) (Syntax: 'From s1 In ... (), Max(s1)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)(keySelector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), elementSelector As System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), resultSelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... 3, 4, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6, IsImplicit) (Syntax: 'New Integer ... 3, 4, 2, 3}')
Initializer:
IArrayInitializerOperation (6 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4, 2, 3}')
Element Values(6):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>), IsImplicit) (Syntax: 's1 Mod 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 Mod 2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 = s1 Mod 2')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 Mod 2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 Mod 2')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 = s1 Mod 3')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1 Mod 3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 Mod 3')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: elementSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As <anonymous type: Key s1 As System.Int32, Key s1str As System.String>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s1str As System.String>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 's1str = CStr(s1)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s1str As System.String>.s1str As System.String (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'CStr(s1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String) (Syntax: 'CStr(s1)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>)) As <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Initializers(5):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'From s1 In ... (), Max(s1)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = Count()')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.c As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Max(s1)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>.Max As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Max(s1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s2 As System.Int32, Key gr As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), Key c As System.Int32, Key Max As System.Int32>, IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>).Max(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, System.Int32)) As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Max(s1)')
Instance Receiver:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>), IsImplicit) (Syntax: 'Group s1, s ... (), Max(s1)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key s1str As System.String>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s1str As System.String>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s1str As System.String>, IsImplicit) (Syntax: 's1')
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)
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy_WithJoin_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group Join s1 In New Integer() {1, 2} On key Equals s1'BIND:"From s1 In New Integer() {1, 2} Select s1 + 1 Group By key = 1 Into Group Join s1 In New Integer() {1, 2} On key Equals s1"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)) (Syntax: 'From s1 In ... y Equals s1')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>).Join(Of System.Int32, System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>), IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(keySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By ke ... Into Group')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of System.Int32)(selector As System.Func(Of System.Int32, System.Int32)) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Select s1 + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 2}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: '1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$ItAnonymous As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group By ke ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (key As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group By ke ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By ke ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'key =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By ke ... Into Group')
Right:
IParameterReferenceOperation: key (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... y Equals s1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By ke ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group By ke ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group By ke ... Into Group')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 2}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'key')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), IsImplicit) (Syntax: 'key')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'key')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'key')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'key')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'key')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'key')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32, <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>), IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, s1 As System.Int32) As <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'key =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.key As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'key')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New I ... er() {1, 2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key key As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32), Key s1 As System.Int32>, IsImplicit) (Syntax: 'Join s1 In ... y Equals s1')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupBy2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
1: q0 = From s1 In New Integer() {1} Group By Into Group
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
3: q0 = From s1 In New Integer() {1} Group s1 By s2 As Integer =s1 Into Group
4: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 As Integer =Group
5: q0 = From s1 In New Integer() {1} Group By s1 Into
6: q0 = From s1 In New Integer() {1} Group q0 = s1 By s1 Into Group
7: q0 = From s1 In New Integer() {1} Group s1 By q0 = s1 Into Group
8: q0 = From s1 In New Integer() {1} Group s1 By s1 Into q0 = Group
9: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s1 = Group
10: Dim count As Integer = 0
11: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count()
12: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count
If count > 0 Then
Dim group As String = ""
13: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Group
End If
14: q0 = From s1 In New Integer() {1} Group
15: q0 = From s1 In New Integer() {1} Group By
16: q0 = From s1 In New Integer() {1} Group s1 By s1 Into
17: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 =
18: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into Max(s1 + s2)
19: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s3 = Max(), s3 = Min()
20: q0 = From s1 In New Integer() {1} Group s2 = s1, s2 = s1 By s1, s1 Into s3 = Max()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36610: Name 'Into' is either not declared or not in the current scope.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~~~~
BC36615: 'Into' expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC30201: Expression expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC36605: 'By' expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC36615: 'Into' expected.
1: q0 = From s1 In New Integer() {1} Group By Into Group
~
BC36610: Name 's2' is either not declared or not in the current scope.
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
~~
BC36605: 'By' expected.
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
~
BC36615: 'Into' expected.
2: q0 = From s1 In New Integer() {1} Group s2 As Integer = s1 By s1 Into Group
~
BC36610: Name 's2' is either not declared or not in the current scope.
3: q0 = From s1 In New Integer() {1} Group s1 By s2 As Integer =s1 Into Group
~~
BC36615: 'Into' expected.
3: q0 = From s1 In New Integer() {1} Group s1 By s2 As Integer =s1 Into Group
~
BC36594: Definition of method 's2' is not accessible in this context.
4: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 As Integer =Group
~~
BC30205: End of statement expected.
4: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 As Integer =Group
~~
BC36707: 'Group' or an identifier expected.
5: q0 = From s1 In New Integer() {1} Group By s1 Into
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
6: q0 = From s1 In New Integer() {1} Group q0 = s1 By s1 Into Group
~~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
7: q0 = From s1 In New Integer() {1} Group s1 By q0 = s1 Into Group
~~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
8: q0 = From s1 In New Integer() {1} Group s1 By s1 Into q0 = Group
~~
BC36600: Range variable 's1' is already declared.
9: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s1 = Group
~~
BC30978: Range variable 'Count' hides a variable in an enclosing block or a range variable previously defined in the query expression.
11: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count()
~~~~~
BC30978: Range variable 'Count' hides a variable in an enclosing block or a range variable previously defined in the query expression.
12: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Count
~~~~~
BC30978: Range variable 'Group' hides a variable in an enclosing block or a range variable previously defined in the query expression.
13: q0 = From s1 In New Integer() {1} Group s1 By s1 Into Group
~~~~~
BC30201: Expression expected.
14: q0 = From s1 In New Integer() {1} Group
~
BC36605: 'By' expected.
14: q0 = From s1 In New Integer() {1} Group
~
BC36615: 'Into' expected.
14: q0 = From s1 In New Integer() {1} Group
~
BC30201: Expression expected.
15: q0 = From s1 In New Integer() {1} Group By
~
BC36615: 'Into' expected.
15: q0 = From s1 In New Integer() {1} Group By
~
BC36707: 'Group' or an identifier expected.
16: q0 = From s1 In New Integer() {1} Group s1 By s1 Into
~
BC36707: 'Group' or an identifier expected.
17: q0 = From s1 In New Integer() {1} Group s1 By s1 Into s2 =
~
BC36610: Name 's1' is either not declared or not in the current scope.
18: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into Max(s1 + s2)
~~
BC36600: Range variable 's3' is already declared.
19: q0 = From s1 In New Integer() {1} Group s2 = s1 By s1 Into s3 = Max(), s3 = Min()
~~
BC36600: Range variable 's2' is already declared.
20: q0 = From s1 In New Integer() {1} Group s2 = s1, s2 = s1 By s1, s1 Into s3 = Max()
~~
BC36600: Range variable 's1' is already declared.
20: q0 = From s1 In New Integer() {1} Group s2 = s1, s2 = s1 By s1, s1 Into s3 = Max()
~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupBy3()
Dim source = <) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s1 In q Group By s1 Into Group'BIND:"From s1 In q Group By s1 Into Group"
Dim q1 As Object = From s1 In q Group s2 = s1 By s1 Into Group
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Children(3):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As ?) As <anonymous type: Key s1 As System.Int32, Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group By s1 Into Group')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q0 As Object = From s1 In q Group By s1 Into Group'BIND:"From s1 In q Group By s1 Into Group"
~~~~~~~~
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q1 As Object = From s1 In q Group s2 = s1 By s1 Into Group
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupBy4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Action(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Func(Of Byte, Integer, Integer)) As QueryAble
Return Me
End Function
Public Function GroupBy(key As Func(Of Integer, Integer), into As Func(Of Integer, Integer, Integer)) As QueryAble
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q0 As Object = From s1 In q Group By s1 Into Group
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q0 As Object = From s1 In q Group By s1 Into Group
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub GroupBy5()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
System.Console.WriteLine(" {0}", key)
System.Console.WriteLine(" {0}", into)
Return New QueryAble(Of R)()
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)()
Dim q As Object
q = From s In q1 Group Nothing By key = Nothing Into Group
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
GroupBy System.Func`2[System.Int32,System.Object]
System.Func`2[System.Int32,System.Object]
System.Func`3[System.Object,QueryAble`1[System.Object],VB$AnonymousType_0`2[System.Object,QueryAble`1[System.Object]]]
]]>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)>
Public Sub GroupJoin1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s1 Equals s2 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s2 + 1 Equals s1 + 2 Into Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Into gr1 = Group Group Join s3 In New Integer() {4, 5} On s3 Equals (s1 + 1) * 2 Into gr2 = Group
System.Console.WriteLine(v)
For Each gv In v.gr1
System.Console.WriteLine(" {0}", gv)
Next
For Each gv In v.gr2
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} Group Join s3 In New Integer() {4, 5} On s3 Equals s2 * 2 Into gr1 = Group On s1 + 1 Equals s2 Into gr2 = Group
System.Console.WriteLine(v)
For Each gr2 In v.gr2
System.Console.WriteLine(" {0}", gr2)
For Each gr1 In gr2.gr1
System.Console.WriteLine(" {0}", gr1)
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In New Integer() {1}
Group Join s2 In New Integer() {2, 3}
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In New Integer() {3, 4}
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In New Integer() {4, 5}
Group Join s5 In New Integer() {5, 6}
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In New Integer() {6, 7}
On s4 + 2 Equals s6 Into g4 = Group
On s1 + 3 Equals s4 Into g5 = Group
System.Console.WriteLine(v)
For Each gr1 In v.g1
System.Console.WriteLine(" {0}", gr1)
Next
For Each gr2 In v.g2
System.Console.WriteLine(" {0}", gr2)
Next
For Each gr5 In v.g5
System.Console.WriteLine(" {0}", gr5)
For Each gr3 In gr5.g3
System.Console.WriteLine(" {0}", gr3)
Next
For Each gr4 In gr5.g4
System.Console.WriteLine(" {0}", gr4)
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From s1 In From s1 In New Integer() {1}
Group Join
s2 In New Integer() {1}
Join
s3 In New Integer() {1}
On s2 Equals s3
Join
s4 In New Integer() {1}
On s2 Equals s4
On s1 Equals s2 Into s3 = Group
System.Console.WriteLine(v)
For Each gv In v.s3
System.Console.WriteLine(" {0}", gv)
Next
Next
System.Console.WriteLine("------")
For Each v In From s In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
System.Console.WriteLine(v)
For Each g1 In v.Group
System.Console.WriteLine(" {0}", g1)
For Each g2 In g1.Group
System.Console.WriteLine(" {0}", g2)
For Each g3 In g2.Group
System.Console.WriteLine(" {0}", g3)
For Each g4 In g3.Group
System.Console.WriteLine(" {0}", g4)
Next
Next
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From s In New Integer() {1, 2}
Join
s1 In New Integer() {1, 2}
Join
s2 In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s2 Equals s1 Into Group
On s2 Equals s1
On s Equals s1
System.Console.WriteLine(v)
For Each g1 In v.Group
System.Console.WriteLine(" {0}", g1)
For Each g2 In g1.Group
System.Console.WriteLine(" {0}", g2)
Next
Next
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {1, 2} Group Join y In New Integer() {0, 3, 4} On x + 1 Equals y Into Count(y + x), Group
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
{ s1 = 1, Group = System.Int32[] }
{ s1 = 3, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
3
------
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
{ s1 = 3, Group = System.Int32[] }
------
{ s1 = 1, gr1 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], gr2 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
4
------
{ s1 = 1, gr2 = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_4`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s2 = 2, gr1 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
4
------
{ s1 = 1, g1 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], g2 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], g5 = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_9`3[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32],System.Collections.Generic.IEnumerable`1[System.Int32]]] }
2
3
{ s4 = 4, g3 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32], g4 = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
5
6
------
{ s1 = 1, s3 = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_12`3[System.Int32,System.Int32,System.Int32]] }
{ s2 = 1, s3 = 1, s4 = 1 }
------
{ s = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]]]] }
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]] }
{ s = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
1
{ s = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]]]] }
{ s1 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_13`2[System.Int32,System.Collections.Generic.IEnumerable`1[VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]]]] }
{ s = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
------
{ s = 1, s1 = 1, s2 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
1
{ s = 2, s1 = 2, s2 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Collections.Generic.IEnumerable`1[System.Int32]]] }
{ s1 = 2, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
2
------
{ x = 1, Count = 0, Group = System.Int32[] }
{ x = 2, Count = 1, Group = System.Linq.Lookup`2+Grouping[System.Int32,System.Int32] }
3
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s1 Equals s2 Into Group'BIND:"From s1 In New Integer() {1, 3} Group Join s2 In New Integer() {2, 3} On s1 Equals s2 Into Group"
System.Console.WriteLine(v)
For Each gv In v.Group
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupJoin(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... Into Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New I ... er() {1, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>.Group As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... Into Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin_Nested_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Into gr1 = Group Group Join s3 In New Integer() {4, 5} On s3 Equals (s1 + 1) * 2 Into gr2 = Group'BIND:"From s1 In New Integer() {1} Group Join s2 In New Integer() {2, 3} On s1 + 1 Equals s2 Into gr1 = Group Group Join s3 In New Integer() {4, 5} On s3 Equals (s1 + 1) * 2 Into gr2 = Group"
System.Console.WriteLine(v)
For Each gv In v.gr1
System.Console.WriteLine(" {0}", gv)
Next
For Each gv In v.gr2
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (Syntax: 'From s1 In ... gr2 = Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>).GroupJoin(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupJoin(Of System.Int32, System.Int32, <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New I ... er() {2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {2, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1 + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1 + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1 + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1 + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1 + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... gr2 = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr1 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr1 = Group')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's3 In New I ... er() {4, 5}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {4, 5}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {4, 5}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{4, 5}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Int32), IsImplicit) (Syntax: 's3')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's3')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '(s1 + 1) * 2')
Left:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Int32) (Syntax: '(s1 + 1)')
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 's1 + 1')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 's3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: '(s1 + 1) * 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s3 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '(s1 + 1) * 2')
ReturnedValue:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's3')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, System.Collections.Generic.IEnumerable(Of System.Int32), <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of System.Int32)) As <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'gr1 =')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr1 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'gr1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr1 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'gr1')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'From s1 In ... gr2 = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>.gr2 As System.Collections.Generic.IEnumerable(Of System.Int32) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key gr1 As System.Collections.Generic.IEnumerable(Of System.Int32), Key gr2 As System.Collections.Generic.IEnumerable(Of System.Int32)>, IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Group Join ... gr2 = Group')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin_NestedJoin_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From s1 In From s1 In New Integer() {1}'BIND:"From s1 In From s1 In New Integer() {1}"
Group Join
s2 In New Integer() {1}
Join
s3 In New Integer() {1}
On s2 Equals s3
Join
s4 In New Integer() {1}
On s2 Equals s4
On s1 Equals s2 Into s3 = Group
System.Console.WriteLine(v)
For Each gv In v.s3
System.Console.WriteLine(" {0}", gv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (Syntax: 'From s1 In ... s3 = Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>).Select(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)(selector As System.Func(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
Instance Receiver:
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (Syntax: 'From s1 In ... s3 = Group')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).GroupJoin(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, System.Int32, <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)(inner As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, System.Int32), resultSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's1 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>).Join(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>)(inner As System.Collections.Generic.IEnumerable(Of System.Int32), outerKeySelector As System.Func(Of System.Int32, System.Int32), innerKeySelector As System.Func(Of System.Int32, System.Int32), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's2 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3 In New Integer() {1}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's3 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's2')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's3')
Target:
IAnonymousFunctionOperation (Symbol: Function (s3 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's3')
ReturnedValue:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's3')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Target:
IAnonymousFunctionOperation (Symbol: Function (s2 As System.Int32, s3 As System.Int32) As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s3')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
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)
Arguments(4):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's4 In New Integer() {1}')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 's4 In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 's2')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's4')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's4')
Target:
IAnonymousFunctionOperation (Symbol: Function (s4 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's4')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's4')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's4')
ReturnedValue:
IParameterReferenceOperation: s4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's4')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, System.Int32, <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, s4 As System.Int32) As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's2 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's3 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>.s3 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's3')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's4 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s4 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 'Join ... 2 Equals s4')
Right:
IParameterReferenceOperation: s4 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's4')
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)
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: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's1')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
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: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, System.Int32), IsImplicit) (Syntax: 's2')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's2')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>.s2 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's2')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>, IsImplicit) (Syntax: 's2')
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: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)) As <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>.s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 'Group Join ... s3 = Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>), IsImplicit) (Syntax: 'Group Join ... s3 = Group')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>), IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
Target:
IAnonymousFunctionOperation (Symbol: Function (s1 As <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>) As <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'From s1 In ... s3 = Group')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: <anonymous type: Key s1 As System.Int32, Key s3 As System.Collections.Generic.IEnumerable(Of <anonymous type: Key s2 As System.Int32, Key s3 As System.Int32, Key s4 As System.Int32>)>, IsImplicit) (Syntax: 's1')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub GroupJoin2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join
q0 = From s In New Integer() {1, 2} Group Join t
q0 = From s In New Integer() {1, 2} Group Join s1 In
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into Group,
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
q0 = From s In New Integer() {1, 2} Group Join s In New Integer() {1, 2} On s Equals s1 Into Group
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into s = Group
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
q0 = From s1 In New Integer() {1}
Group Join
s2 In New Integer() {1}
On s1 Equals s2 Into s1 = Group
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {1}
Group Join
s1 In New Integer() {1}
On s1 Equals s2 Into s1 = Group
On s1 Equals s2
q0 = From s1 In New Integer() {1}
Join s2 In New Integer() {1}
Group Join
s1 In New Integer() {1}
On s1 Equals s2 Into s2 = Group
On s1 Equals s2
q0 = From s In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s2 In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
q0 = From s In New Integer() {1, 2}
Join
s1 In New Integer() {1, 2}
Group Join
s2 In New Integer() {1, 2}
Group Join
s1 In New Integer() {1, 2}
Group Join
s In New Integer() {1, 2}
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1 Into Group
On s Equals s1
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Group s2 In New Integer() {1, 2} On s1 Equals s2 Into group On s Equals s1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36606: Range variable name cannot match the name of a member of the 'Object' class.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~~~~~~~~~~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join GetHashCode
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On _ Equals _ :
~
BC30183: Keyword is not valid as an identifier.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join _ In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join t
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s
~
BC36619: 'Equals' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1
~
BC36707: 'Group' or an identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into
~
BC36707: 'Group' or an identifier expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into Group,
~
BC30451: 'Group' is not declared. It may be inaccessible due to its protection level.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~~~~~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In Group Join t2 In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36607: 'In' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t In New Integer() {1, 2} Group Join
~
BC30201: Expression expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join t1 In New Integer() {1, 2} Group Join t2 In
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
~~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join q0 In New Integer() {1, 2}
~
BC36600: Range variable 's1' is already declared.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}
~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Group Join s In New Integer() {1, 2} On s Equals s1 Into Group
~
BC36610: Name 's1' is either not declared or not in the current scope.
q0 = From s In New Integer() {1, 2} Group Join s In New Integer() {1, 2} On s Equals s1 Into Group
~~
BC36600: Range variable 's' is already declared.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2} On s Equals s1 Into s = Group
~
BC36615: 'Into' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
~
BC36618: 'On' expected.
q0 = From s In New Integer() {1, 2} Group Join s1 In New Integer() {1, 2}, s2 In New Integer() {1, 2}
~
BC36600: Range variable 's1' is already declared.
On s1 Equals s2 Into s1 = Group
~~
BC36600: Range variable 's1' is already declared.
On s1 Equals s2 Into s1 = Group
~~
BC36600: Range variable 's2' is already declared.
On s1 Equals s2 Into s2 = Group
~~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36610: Name 's' is either not declared or not in the current scope.
On s Equals s1 Into Group
~
BC36631: 'Join' expected.
q0 = From s In New Integer() {1, 2} Join s1 In New Integer() {1, 2} Group s2 In New Integer() {1, 2} On s1 Equals s2 Into group On s Equals s1
~
</expected>)
End Sub
<Fact>
Public Sub GroupJoin3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim qd As New QueryAble(Of Double)(0)
Dim q0 As Object
q0 = From s1 In qi Group Join s2 In qb On s1 Equals s2 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Select g1, g2, g5, s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Let s7 = s1
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Join s7 In qd On s1 Equals s7
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
From s7 In qd
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group s1 By s2 = s1 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group By s2 = s1 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Group Join s7 In qd On s1 Equals s7 Into Group
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
Group Join s3 In qd
On s4 Equals s3 Into g2 = Group
On s1 Equals s4 Into g5 = Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s4 In qu
Join s5 In ql
On s4 + 1 Equals s5
Join s6 In qd
On s4 + 2 Equals s6
Join s3 In qd
On s4 Equals s3
On s1 Equals s4 Into g5 = Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True)
System.Console.WriteLine("------")
q0 = From s1 In qi
Group Join s2 In qb
On s1 + 1 Equals s2 Into g1 = Group
Group Join s3 In qs
On s1 + 2 Equals s3 Into g2 = Group
Group Join s4 In qu
Group Join s5 In ql
On s4 + 1 Equals s5 Into g3 = Group
Group Join s6 In qd
On s4 + 2 Equals s6 Into g4 = Group
On s1 Equals s4 Into g5 = Group
Where True Order By s1 Distinct Take While True Skip While False Skip 0 Take 0
Aggregate s7 In qd Into Where(True), Distinct
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_0`2[System.Int32,QueryAble`1[System.Byte]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_7`4[QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Int32]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_8`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Int32]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Double,VB$AnonymousType_8`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Double]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Double,VB$AnonymousType_8`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],System.Double]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
GroupBy
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],QueryAble`1[System.Double],VB$AnonymousType_10`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],QueryAble`1[System.Double]]]
------
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_12`2[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_12`2[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double]],QueryAble`1[System.Double],VB$AnonymousType_13`4[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[System.Int32,QueryAble`1[VB$AnonymousType_13`4[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double],QueryAble`1[System.Double]]],VB$AnonymousType_11`2[System.Int32,QueryAble`1[VB$AnonymousType_13`4[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double],QueryAble`1[System.Double]]]]]
------
Join System.Func`3[System.UInt32,System.Int64,VB$AnonymousType_14`2[System.UInt32,System.Int64]]
Join System.Func`3[VB$AnonymousType_14`2[System.UInt32,System.Int64],System.Double,VB$AnonymousType_15`2[VB$AnonymousType_14`2[System.UInt32,System.Int64],System.Double]]
Join System.Func`3[VB$AnonymousType_15`2[VB$AnonymousType_14`2[System.UInt32,System.Int64],System.Double],System.Double,VB$AnonymousType_16`4[System.UInt32,System.Int64,System.Double,System.Double]]
GroupJoin System.Func`3[System.Int32,QueryAble`1[VB$AnonymousType_16`4[System.UInt32,System.Int64,System.Double,System.Double]],VB$AnonymousType_11`2[System.Int32,QueryAble`1[VB$AnonymousType_16`4[System.UInt32,System.Int64,System.Double,System.Double]]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_17`5[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],QueryAble`1[System.Double]]]
------
GroupJoin System.Func`3[System.Int32,QueryAble`1[System.Byte],VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]]]
GroupJoin System.Func`3[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
GroupJoin System.Func`3[System.UInt32,QueryAble`1[System.Int64],VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]]]
GroupJoin System.Func`3[VB$AnonymousType_4`2[System.UInt32,QueryAble`1[System.Int64]],QueryAble`1[System.Double],VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]
GroupJoin System.Func`3[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]]]
Where System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],VB$AnonymousType_18`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],QueryAble`1[System.Double]]]
Select System.Func`2[VB$AnonymousType_18`2[VB$AnonymousType_6`2[VB$AnonymousType_2`2[VB$AnonymousType_1`2[System.Int32,QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]]],QueryAble`1[System.Double]],VB$AnonymousType_19`6[System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[VB$AnonymousType_5`3[System.UInt32,QueryAble`1[System.Int64],QueryAble`1[System.Double]]],QueryAble`1[System.Double],QueryAble`1[System.Double]]]
]]>)
End Sub
<Fact>
Public Sub GroupJoin4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group
Dim q1 As Object = From s1 In q Join t1 In q Group Join t2 In q On t1 Equals t2 Into Group On s1 Equals t1
Dim q2 As Object = From s1 In q Join t1 In q Group t2 In q On t1 Equals t2 Into Group On s1 Equals t1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group
~~~~~~~~~~
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q1 As Object = From s1 In q Join t1 In q Group Join t2 In q On t1 Equals t2 Into Group On s1 Equals t1
~~~~~~~~~~
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q2 As Object = From s1 In q Join t1 In q Group t2 In q On t1 Equals t2 Into Group On s1 Equals t1
~~~~~
BC36631: 'Join' expected.
Dim q2 As Object = From s1 In q Join t1 In q Group t2 In q On t1 Equals t2 Into Group On s1 Equals t1
~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GroupJoin5()
Dim source = <(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of I, R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group'BIND:"From s1 In q Group Join t1 In q On s1 Equals t1 Into Group"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s1 In ... Into Group')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(5):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Children(1):
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'q')
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'q')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's1')
ReturnedValue:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's1')
IAnonymousFunctionOperation (Symbol: Function (t1 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 't1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 't1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 't1')
ReturnedValue:
IParameterReferenceOperation: t1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 't1')
IAnonymousFunctionOperation (Symbol: Function (s1 As System.Int32, $VB$ItAnonymous As ?) As <anonymous type: Key s1 As System.Int32, Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's1 In q')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.s1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s1 In ... Into Group')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s1 As System.Int32, Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s1 As System.Int32, Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
Right:
IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q0 As Object = From s1 In q Group Join t1 In q On s1 Equals t1 Into Group'BIND:"From s1 In q Group Join t1 In q On s1 Equals t1 Into Group"
~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Aggregate1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count())
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2))
System.Console.WriteLine(Aggregate x In New Integer() {3, 4}, y In New Integer() {1, 3} Where x > y Into Sum(x + y))
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1 Aggregate y In New Integer() {3, 4} Into Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1 Aggregate y In New Integer() {3, 4} Into Count(), Sum()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} Aggregate y In x Into Sum()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} Aggregate y In x Into Sum(), Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} From z In x Aggregate y In x Into Sum(z + y)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer()() {New Integer() {3, 4}} From z In x Aggregate y In x Into Sum(z + y), Count()
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1 Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)
For Each vv In v
System.Console.WriteLine(vv)
Next
Next
System.Console.WriteLine("------")
For Each v In Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3}
Where True Order By x Distinct Take While True Skip While False Skip 0 Take 100
Select x, y, z Let w = x + y + z
Into Where(True)
System.Console.WriteLine(v)
Next
System.Console.WriteLine("------")
For Each v In From x In New Integer() {3, 4} Select x + 1
Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3}
Where True Order By x Distinct Take While True Skip While False Skip 0 Take 100
Select x, y, z Let w = x + y + z
Into Where(True)
For Each vv In v
System.Console.WriteLine(vv)
Next
Next
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, references:={LinqAssemblyRef},
expectedOutput:=
<![CDATA[
2
{ Count = 2, Sum = 3 }
16
------
2
2
------
{ Count = 2, Sum = 7 }
{ Count = 2, Sum = 7 }
------
{ x = System.Int32[], Sum = 7 }
------
{ x = System.Int32[], Sum = 7, Count = 2 }
------
{ x = System.Int32[], z = 3, Sum = 13 }
{ x = System.Int32[], z = 4, Sum = 15 }
------
{ x = System.Int32[], z = 3, Sum = 13, Count = 2 }
{ x = System.Int32[], z = 4, Sum = 15, Count = 2 }
------
{ x = 1, y = 2, z = 3 }
------
{ x = 1, y = 2, z = 3 }
{ x = 1, y = 2, z = 3 }
------
{ x = 1, y = 2, z = 3, w = 6 }
------
{ x = 1, y = 2, z = 3, w = 6 }
{ x = 1, y = 2, z = 3, w = 6 }
]]>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count())'BIND:"Aggregate y In New Integer() {3, 4} Into Count()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Int32) (Syntax: 'Aggregate y ... nto Count()')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New In ... er() {3, 4}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_MultipleAggregations_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2)) 'BIND:"Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2)"'BIND:"Aggregate y In New Integer() {3, 4} Into Count(), Sum(y \ 2)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Expression:
IAggregateQueryOperation (OperationKind.None, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Group:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Aggregation:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>, IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>, IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Count() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Count()')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPlaceholderOperation (OperationKind.None, Type: System.Int32(), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Sum(y \ 2)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>.Sum As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Sum(y \ 2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key Count As System.Int32, Key Sum As System.Int32>, IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Right:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Sum(selector As System.Func(Of System.Int32, System.Int32)) As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Sum(y \ 2)')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPlaceholderOperation (OperationKind.None, Type: System.Int32(), IsImplicit) (Syntax: 'Aggregate y ... Sum(y \ 2)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y \ 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'y \ 2')
Target:
IAnonymousFunctionOperation (Symbol: Function (y As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y \ 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y \ 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y \ 2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.IntegerDivide, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y \ 2')
Left:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_WithWhereFilter_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
System.Console.WriteLine(Aggregate x In New Integer() {3, 4}, y In New Integer() {1, 3} Where x > y Into Sum(x + y))'BIND:"Aggregate x In New Integer() {3, 4}, y In New Integer() {1, 3} Where x > y Into Sum(x + y)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Int32) (Syntax: 'Aggregate x ... Sum(x + y)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).Sum(selector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32)) As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'Sum(x + y)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Where x > y')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)(collectionSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New In ... er() {3, 4}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {1, 3}')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {1, 3}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {1, 3}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 3}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, y As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Sum(x + y)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New In ... er() {3, 4}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New In ... er() {1, 3}')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x > y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'x > y')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x > y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x > y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x > y')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x > y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x > y')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x > y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32), IsImplicit) (Syntax: 'x + y')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x + y')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x + y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_MultipleRangeVariableDeclarations_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)'BIND:"Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3} Into Where(True)"
System.Console.WriteLine(v)
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (Syntax: 'Aggregate x ... Where(True)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'Where(True)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)(collectionSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'z In New Integer() {3}')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)(collectionSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'y In New Integer() {2}')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {2}')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New Integer() {2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {2}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, y As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New Integer() {2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {3}')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'z In New Integer() {3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {3}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, z As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New Integer() {2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub AggregateClause_WithDifferentClauses_IOperation()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
For Each v In From x In New Integer() {3, 4} Select x + 1'BIND:"From x In New Integer() {3, 4} Select x + 1"
Aggregate x In New Integer() {1}, y In New Integer() {2}, z In New Integer() {3}
Where True Order By x Distinct Take While True Skip While False Skip 0 Take 100
Select x, y, z Let w = x + y + z
Into Where(True)
For Each vv In v
System.Console.WriteLine(vv)
Next
Next
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))) (Syntax: 'From x In N ... Where(True)')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))(selector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))) As System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>))) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of System.Int32)(selector As System.Func(Of System.Int32, System.Int32)) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Select x + 1')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New In ... er() {3, 4}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3, 4}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'New Integer() {3, 4}')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3, 4}')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 'x + 1')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)), IsImplicit) (Syntax: 'New Integer() {1}')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$ItAnonymous As System.Int32) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {1}')
ReturnedValue:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>), IsImplicit) (Syntax: 'Where(True)')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>).Select(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)(selector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>), IsImplicit) (Syntax: 'w = x + y + z')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Select(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)(selector As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'Select x, y, z')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Take(count As System.Int32) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Take 100')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Skip(count As System.Int32) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Skip 0')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).SkipWhile(predicate As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Skip While False')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).TakeWhile(predicate As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Take While True')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Distinct() As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Distinct')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Order By x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).OrderBy(Of System.Int32)(keySelector As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Int32)) As System.Linq.IOrderedEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'x')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>).Where(predicate As System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Where True')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>).SelectMany(Of System.Int32, <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)(collectionSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'z In New Integer() {3}')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).SelectMany(Of System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)(collectionSelector As System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), resultSelector As System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'y In New Integer() {2}')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'x In New Integer() {1}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {1}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {2}')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {2}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'y In New Integer() {2}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {2}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {2}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{2}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32, <anonymous type: Key x As System.Int32, Key y As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, y As System.Int32) As <anonymous type: Key x As System.Int32, Key y As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x In New Integer() {1}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y In New Integer() {2}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'y In New Integer() {2}')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Collections.Generic.IEnumerable(Of System.Int32)), IsImplicit) (Syntax: 'New Integer() {3}')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32>) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'New Integer() {3}')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'z In New Integer() {3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'New Integer() {3}')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{3}')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32>, System.Int32, <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>), IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, z As System.Int32) As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'Aggregate x ... Where(True)')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IParameterReferenceOperation: $VB$It1 (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z In New Integer() {3}')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'z In New Integer() {3}')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Int32), IsImplicit) (Syntax: 'x')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(0)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'False')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'False')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'False')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'False')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'False')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'False')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '100')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
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)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>), IsImplicit) (Syntax: 'x')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>) As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.$VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32> (OperationKind.PropertyReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'Select x, y, z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It1 As <anonymous type: Key x As System.Int32, Key y As System.Int32>, Key z As System.Int32>, IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>), IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>) As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Initializers(4):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'z')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'w = x + y + z')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>.w As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, IsImplicit) (Syntax: 'w = x + y + z')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.x As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.y As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
Right:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>.z As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32>, IsImplicit) (Syntax: 'x + y + z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'True')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>, System.Boolean), IsImplicit) (Syntax: 'True')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key x As System.Int32, Key y As System.Int32, Key z As System.Int32, Key w As System.Int32>) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'True')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'True')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Aggregate2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Module Module1
Sub Main()
Dim q0 As Object
q0 = Aggregate
q0 = Aggregate s
q0 = Aggregate s In
q0 = Aggregate s In New Integer() {1, 2}
q0 = Aggregate s In New Integer() {1, 2} Into
q0 = Aggregate s In New Integer() {1, 2} Into Group
q0 = Aggregate s In New Integer() {1, 2} Into [Group]
q0 = Aggregate s In New Integer() {1, 2} Into s
q0 = Aggregate s In New Integer() {1, 2} Into n=
q0 = Aggregate s In New Integer() {1, 2} Into n= ,
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2=
q0 = Aggregate s In New Integer() {1, 2} Into q0 = Count()
q0 = Aggregate s In New Integer() {1, 2} Into s = Count()
q0 = Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
q0 = From x In New Integer() {3, 4} Aggregate
q0 = From x In New Integer() {3, 4} Aggregate s
q0 = From x In New Integer() {3, 4} Aggregate s In
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2}
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into [Group]
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n=
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n= ,
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2=
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into q0 = Count()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s = Count()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x = Count()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
q0 = Aggregate s In New Integer() {1, 2} Into Count() Where True
q0 = Aggregate s In New Integer() {1, 2} Into Where(DoesntExist)
q0 = From x In New Integer() {3, 4} Select x + 1 Aggregate s In New Integer() {1, 2}
q0 = Aggregate s In New Integer() {1, 2} Into Group()
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group()
q0 = Aggregate x In "" Into c = Count%
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'Aggregate' is not declared. It may be inaccessible due to its protection level.
q0 = Aggregate
~~~~~~~~~
BC36607: 'In' expected.
q0 = Aggregate s
~
BC36615: 'Into' expected.
q0 = Aggregate s
~
BC30201: Expression expected.
q0 = Aggregate s In
~
BC36615: 'Into' expected.
q0 = Aggregate s In
~
BC36615: 'Into' expected.
q0 = Aggregate s In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into
~
BC36708: 'Group' not allowed in this context; identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into Group
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into [Group]
~~~~~~~
BC36594: Definition of method 's' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into s
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n=
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2
~
BC36594: Definition of method 'n2' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2
~~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30203: Identifier expected.
q0 = Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = Aggregate s In New Integer() {1, 2} Into q0 = Count()
~~
BC36600: Range variable 's' is already declared.
q0 = Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate
~
BC36607: 'In' expected.
q0 = From x In New Integer() {3, 4} Aggregate
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate
~
BC36607: 'In' expected.
q0 = From x In New Integer() {3, 4} Aggregate s
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate s
~
BC30201: Expression expected.
q0 = From x In New Integer() {3, 4} Aggregate s In
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate s In
~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2}
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into
~
BC36708: 'Group' not allowed in this context; identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into [Group]
~~~~~~~
BC36594: Definition of method 's' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s
~
BC36594: Definition of method 'x' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x
~
BC36600: Range variable 'x' is already declared.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n=
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n= ,
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2
~
BC36594: Definition of method 'n2' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2
~~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30203: Identifier expected.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into n1= , n2=
~
BC30978: Range variable 'q0' hides a variable in an enclosing block or a range variable previously defined in the query expression.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into q0 = Count()
~~
BC36600: Range variable 'x' is already declared.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into x = Count()
~
BC36600: Range variable 's' is already declared.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into s = Count(), s = Max()
~
BC30205: End of statement expected.
q0 = Aggregate s In New Integer() {1, 2} Into Count() Where True
~~~~~
BC36610: Name 'DoesntExist' is either not declared or not in the current scope.
q0 = Aggregate s In New Integer() {1, 2} Into Where(DoesntExist)
~~~~~~~~~~~
BC36615: 'Into' expected.
q0 = From x In New Integer() {3, 4} Select x + 1 Aggregate s In New Integer() {1, 2}
~
BC30183: Keyword is not valid as an identifier.
q0 = Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC30183: Keyword is not valid as an identifier.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC36594: Definition of method 'Group' is not accessible in this context.
q0 = From x In New Integer() {3, 4} Aggregate s In New Integer() {1, 2} Into Group()
~~~~~
BC36617: Aggregate function name cannot be used with a type character.
q0 = Aggregate x In "" Into c = Count%
~~~~~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Aggregate2b()
Dim source = <(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'Aggregate i ... aggr10(10)')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'aggr10(10)')
Children(2):
ILocalReferenceOperation: colm (OperationKind.LocalReference, Type: cls1) (Syntax: 'colm')
IAnonymousFunctionOperation (Symbol: Function (i As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'aggr10' is not accessible in this context.
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub Aggregate2c()
Dim source = <(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Double)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'Aggregate i ... aggr10(10)')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'aggr10(10)')
Children(2):
ILocalReferenceOperation: colm (OperationKind.LocalReference, Type: cls1) (Syntax: 'colm')
IAnonymousFunctionOperation (Symbol: Function (i As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36594: Definition of method 'aggr10' is not accessible in this context.
Dim q10m = Aggregate i In colm Into aggr10(10)'BIND:"Aggregate i In colm Into aggr10(10)"
~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub Aggregate2d()
Dim compilationDef =
<compilation name="Aggregate2d">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class cls1
Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function aggr10(ByVal sel As Func(Of Integer, Double)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub Aggregate2e()
Dim compilationDef =
<compilation name="Aggregate2e">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Public Module UserDefinedAggregates
<System.Runtime.CompilerServices.Extension()>
Public Function Aggr10(ByVal values As cls1, ByVal selector As Func(Of Integer, Integer)) As Double
Return 1
End Function
End Module
Public Class cls1
Public Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Public Shared Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub Aggregate2f()
Dim compilationDef =
<compilation name="Aggregate2f">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Public Module UserDefinedAggregates
<System.Runtime.CompilerServices.Extension()>
Public Function Aggr10(ByVal values As cls1, ByVal selector As Func(Of Integer, Integer)) As Double
Return 1
End Function
End Module
Public Class cls1
Public Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Private Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact>
Public Sub Aggregate2g()
Dim compilationDef =
<compilation name="Aggregate2g">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class cls1
Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1
Return Nothing
End Function
Private Function aggr10(ByVal sel As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim colm As New cls1
Dim q10m = Aggregate i In colm Into aggr10(10)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'cls1.Private Function aggr10(sel As Func(Of Integer, Integer)) As Object' is not accessible in this context because it is 'Private'.
Dim q10m = Aggregate i In colm Into aggr10(10)
~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Aggregate3()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
'Inherits Base
'Public Shadows [Select] As Byte
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("SkipWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("OrderBy {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Skip(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Skip {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Take(count As Integer) As QueryAble(Of T)
System.Console.WriteLine("Take {0}", count)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim q0 As Object
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Select Where, t, s
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Select Distinct, Where, t, s
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Let t4 = 1
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Let t4 = 1
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
From t4 In qs
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
From t4 In qs
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Join t4 In qs On s Equals t4
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Join t4 In qs On s Equals t4
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group s By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group s By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group By t Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group Join t4 In qs On t Equals t4 Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Group Join t4 In qs On t Equals t4 Into Group
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True)
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True)
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True)
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True), d = Distinct()
System.Console.WriteLine("------")
q0 = From s In qi Let t = s + 1
Aggregate x In qb Into Where(True), Distinct()
Where True Order By s Distinct Take While True Skip While False Skip 0 Take 0
Aggregate t4 In qs Into w = Where(True), d = Distinct()
System.Console.WriteLine("------")
q0 = From i In qi, b In qb
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b)
System.Console.WriteLine("------")
q0 = From i In qi, b In qb
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b), Distinct()
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b)
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i
Aggregate s In qs Where s > i AndAlso s < b Into Where(s > i AndAlso s < b), Distinct()
System.Console.WriteLine("------")
q0 = From i In qi Select i + 1 From b In qb
Aggregate s In qs Where s < b Into Where(s < b)
System.Console.WriteLine("------")
q0 = From i In qi Select i + 1 From b In qb
Aggregate s In qs Where s < b Into Where(s < b), Distinct()
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i From ii As Long In qi
Aggregate s In qs Where s < b Into Where(s < b)
Select Where, ii, b, i
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb On b Equals i From ii As Long In qi
Aggregate s In qs Where s < b Into Where(s < b), Distinct()
Select Distinct, Where, ii, b, i
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb Join ii As Long In qi On b Equals ii On b Equals i
Aggregate s In qs Where s < b Into Where(s < b)
Select Where, ii, b, i
System.Console.WriteLine("------")
q0 = From i In qi Join b In qb Join ii As Long In qi On b Equals ii On b Equals i
Aggregate s In qs Where s < b Into Where(s < b), Distinct()
Select Distinct, Where, ii, b, i
End Sub
End Module
]]></file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_5`3[QueryAble`1[System.Byte],System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_7`4[QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int32,System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_8`4[System.Int32,System.Int32,QueryAble`1[System.Byte],System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_9`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int32]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_8`4[System.Int32,System.Int32,QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
SelectMany System.Func`3[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_9`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_8`4[System.Int32,System.Int32,QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Join System.Func`3[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int16,VB$AnonymousType_9`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],System.Int16]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_1`3[System.Int32,System.Int32,QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_3`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupBy
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_11`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
GroupJoin System.Func`3[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],QueryAble`1[System.Int16],VB$AnonymousType_12`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_13`4[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_14`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_2`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_4`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],VB$AnonymousType_15`5[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,VB$AnonymousType_0`2[System.Int32,System.Int32]]
Select System.Func`2[VB$AnonymousType_0`2[System.Int32,System.Int32],VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte]],VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]]]
Where System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
OrderBy System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Int32]
Distinct
TakeWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
SkipWhile System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],System.Boolean]
Skip 0
Take 0
Select System.Func`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],VB$AnonymousType_2`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_2`2[VB$AnonymousType_6`3[VB$AnonymousType_0`2[System.Int32,System.Int32],QueryAble`1[System.Byte],QueryAble`1[System.Byte]],QueryAble`1[System.Int16]],VB$AnonymousType_16`6[System.Int32,System.Int32,QueryAble`1[System.Byte],QueryAble`1[System.Byte],QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_17`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
------
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]],VB$AnonymousType_19`4[System.Int32,System.Byte,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_17`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_18`3[System.Int32,System.Byte,QueryAble`1[System.Int16]],VB$AnonymousType_19`4[System.Int32,System.Byte,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_20`2[System.Byte,QueryAble`1[System.Int16]]]
------
Select System.Func`2[System.Int32,System.Int32]
SelectMany System.Func`3[System.Int32,System.Byte,VB$AnonymousType_21`2[System.Byte,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_21`2[System.Byte,QueryAble`1[System.Int16]],VB$AnonymousType_22`3[System.Byte,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_23`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,VB$AnonymousType_24`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_24`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]],VB$AnonymousType_25`4[QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
------
Join System.Func`3[System.Int32,System.Byte,VB$AnonymousType_23`2[System.Int32,System.Byte]]
SelectMany System.Func`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,VB$AnonymousType_26`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_26`3[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16]],VB$AnonymousType_27`4[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_27`4[VB$AnonymousType_23`2[System.Int32,System.Byte],System.Int64,QueryAble`1[System.Int16],QueryAble`1[System.Int16]],VB$AnonymousType_28`5[QueryAble`1[System.Int16],QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
------
Select System.Func`2[System.Int32,System.Int64]
Join System.Func`3[System.Byte,System.Int64,VB$AnonymousType_29`2[System.Byte,System.Int64]]
Join System.Func`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],VB$AnonymousType_30`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_30`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]],VB$AnonymousType_25`4[QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
------
Select System.Func`2[System.Int32,System.Int64]
Join System.Func`3[System.Byte,System.Int64,VB$AnonymousType_29`2[System.Byte,System.Int64]]
Join System.Func`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],VB$AnonymousType_31`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_31`3[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16]],VB$AnonymousType_32`4[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16],QueryAble`1[System.Int16]]]
Select System.Func`2[VB$AnonymousType_32`4[System.Int32,VB$AnonymousType_29`2[System.Byte,System.Int64],QueryAble`1[System.Int16],QueryAble`1[System.Int16]],VB$AnonymousType_28`5[QueryAble`1[System.Int16],QueryAble`1[System.Int16],System.Int64,System.Byte,System.Int32]]
]]>)
End Sub
<Fact>
Public Sub Aggregate4()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](x As Func(Of T, Integer)) As QueryAble(Of Integer)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of Integer)(v + 1)
End Function
Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Public Function Distinct() As QueryAble(Of T)
System.Console.WriteLine("Distinct")
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q0 As Object
q0 = Aggregate s1 In q Into Where(True)
q0 = Aggregate s1 In q Into Where(True), Distinct
q0 = From s0 in q Aggregate s1 In q Into Where(True)
q0 = From s0 in q Aggregate s1 In q Into Where(True), Distinct
q0 = Aggregate s1 In q Skip 10 Into Where(True)
q0 = From s0 in q Skip 10 Aggregate s1 In q Into Where(True)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Select' is not accessible in this context.
q0 = From s0 in q Aggregate s1 In q Into Where(True)
~~~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
q0 = From s0 in q Aggregate s1 In q Into Where(True)
~
BC36594: Definition of method 'Select' is not accessible in this context.
q0 = From s0 in q Aggregate s1 In q Into Where(True), Distinct
~~~~~~~~~
BC36532: Nested function does not have the same signature as delegate 'Func(Of Integer, Integer)'.
q0 = From s0 in q Aggregate s1 In q Into Where(True), Distinct
~
BC36594: Definition of method 'Skip' is not accessible in this context.
q0 = Aggregate s1 In q Skip 10 Into Where(True)
~~~~
BC36594: Definition of method 'Skip' is not accessible in this context.
q0 = From s0 in q Skip 10 Aggregate s1 In q Into Where(True)
~~~~
</expected>)
End Sub
<Fact>
Public Sub DefaultQueryIndexer1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class DefaultQueryIndexer1
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer3
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
ReadOnly Property ElementAtOrDefault(x As String) As String
Get
Return x
End Get
End Property
End Class
Class DefaultQueryIndexer4
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Class DefaultQueryIndexer5
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Shared Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer6
Function AsEnumerable() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
End Class
Class DefaultQueryIndexer7
Function AsQueryable() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
End Class
Class DefaultQueryIndexer8
Function Cast(Of T)() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Function ElementAtOrDefault(this As DefaultQueryIndexer4, x As String) As Integer
Return x
End Function
Function TestDefaultQueryIndexer1() As DefaultQueryIndexer1
Return New DefaultQueryIndexer1()
End Function
Function TestDefaultQueryIndexer5() As DefaultQueryIndexer5
Return New DefaultQueryIndexer5()
End Function
Sub Main()
Dim xx1 As New DefaultQueryIndexer1()
System.Console.WriteLine(xx1(1))
System.Console.WriteLine(TestDefaultQueryIndexer1(2))
Dim xx3 As New DefaultQueryIndexer3()
System.Console.WriteLine(xx3!aaa)
Dim xx4 As New DefaultQueryIndexer4()
System.Console.WriteLine(xx4(4))
System.Console.WriteLine((New DefaultQueryIndexer5())(6))
System.Console.WriteLine(TestDefaultQueryIndexer5(7))
System.Console.WriteLine((New DefaultQueryIndexer6())(8))
System.Console.WriteLine((New DefaultQueryIndexer7())(9))
System.Console.WriteLine((New DefaultQueryIndexer8())(10))
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
00000001-0000-0000-0000-000000000000
00000002-0000-0000-0000-000000000000
aaa
4
00000006-0000-0000-0000-000000000000
00000007-0000-0000-0000-000000000000
00000008-0000-0000-0000-000000000000
00000009-0000-0000-0000-000000000000
0000000a-0000-0000-0000-000000000000
]]>)
End Sub
<Fact>
Public Sub DefaultQueryIndexer2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class DefaultQueryIndexer1
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer2
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Function ElementAtOrDefault(x As String) As Integer
Return x
End Function
End Class
Class DefaultQueryIndexer4
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
End Class
Class DefaultQueryIndexer5
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Shared Function ElementAtOrDefault(x As Integer) As Guid
Return New Guid(x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
End Function
End Class
Class DefaultQueryIndexer9
Function Cast(Of T)() As DefaultQueryIndexer4
Return New DefaultQueryIndexer4()
End Function
End Class
Class DefaultQueryIndexer10
WriteOnly Property G As DefaultQueryIndexer1
Set(value As DefaultQueryIndexer1)
End Set
End Property
End Class
Class DefaultQueryIndexer11
Function [Select](x As Func(Of Integer, Integer)) As Object
Return Nothing
End Function
Public ElementAtOrDefault As Guid
End Class
Module Module1
Function TestDefaultQueryIndexer4() As DefaultQueryIndexer4
Return New DefaultQueryIndexer4()
End Function
Function TestDefaultQueryIndexer5() As DefaultQueryIndexer5
Return New DefaultQueryIndexer5()
End Function
Sub Main()
Dim xx1 As New DefaultQueryIndexer1()
System.Console.WriteLine(xx1(0, 1))
System.Console.WriteLine(xx1!aaa)
DefaultQueryIndexer1(3)
System.Console.WriteLine(DefaultQueryIndexer1(3))
Dim xx2 As New DefaultQueryIndexer2()
System.Console.WriteLine(xx2!aaa)
Dim xx4 As New DefaultQueryIndexer4()
System.Console.WriteLine(xx4(4))
System.Console.WriteLine(TestDefaultQueryIndexer4(2))
System.Console.WriteLine((New DefaultQueryIndexer5())(6))
System.Console.WriteLine(TestDefaultQueryIndexer5(7))
System.Console.WriteLine((New DefaultQueryIndexer9())(11))
System.Console.WriteLine((New DefaultQueryIndexer10()).G(11))
System.Console.WriteLine((New DefaultQueryIndexer11())(12))
System.Console.WriteLine((New DefaultQueryIndexer11())!bbb)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public Function ElementAtOrDefault(x As Integer) As Guid'.
System.Console.WriteLine(xx1(0, 1))
~
BC30367: Class 'DefaultQueryIndexer1' cannot be indexed because it has no default property.
System.Console.WriteLine(xx1!aaa)
~~~
BC30109: 'DefaultQueryIndexer1' is a class type and cannot be used as an expression.
DefaultQueryIndexer1(3)
~~~~~~~~~~~~~~~~~~~~
BC30109: 'DefaultQueryIndexer1' is a class type and cannot be used as an expression.
System.Console.WriteLine(DefaultQueryIndexer1(3))
~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer2' cannot be indexed because it has no default property.
System.Console.WriteLine(xx2!aaa)
~~~
BC30367: Class 'DefaultQueryIndexer4' cannot be indexed because it has no default property.
System.Console.WriteLine(xx4(4))
~~~
BC32016: 'Public Function TestDefaultQueryIndexer4() As DefaultQueryIndexer4' has no parameters and its return type cannot be indexed.
System.Console.WriteLine(TestDefaultQueryIndexer4(2))
~~~~~~~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
System.Console.WriteLine((New DefaultQueryIndexer5())(6))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
System.Console.WriteLine(TestDefaultQueryIndexer5(7))
~~~~~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer9' cannot be indexed because it has no default property.
System.Console.WriteLine((New DefaultQueryIndexer9())(11))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30524: Property 'G' is 'WriteOnly'.
System.Console.WriteLine((New DefaultQueryIndexer10()).G(11))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer11' cannot be indexed because it has no default property.
System.Console.WriteLine((New DefaultQueryIndexer11())(12))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'DefaultQueryIndexer11' cannot be indexed because it has no default property.
System.Console.WriteLine((New DefaultQueryIndexer11())!bbb)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
''' <summary>
''' Breaking change: Native compiler allows ElementAtOrDefault
''' to be a field, while Roslyn requires ElementAtOrDefault
''' to be a method or property.
''' </summary>
<WorkItem(576814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576814")>
<Fact()>
Public Sub DefaultQueryIndexerField()
Dim source =
<compilation>
<file name="c.vb"><) As C
Return Nothing
End Function
Public ElementAtOrDefault As Object()
End Class
Module M
Sub M(o As C)
Dim value As Object
value = o(1)
o(2) = value
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source)
compilation.AssertTheseDiagnostics(
<expected>
BC30367: Class 'C' cannot be indexed because it has no default property.
value = o(1)
~
BC30367: Class 'C' cannot be indexed because it has no default property.
o(2) = value
~
</expected>)
End Sub
<Fact>
Public Sub QueryLambdas1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class QueryLambdas
Shared ReadOnly sharedRO As Integer
ReadOnly instanceRO As Integer
Shared fld1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim fld2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim fld3 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
Shared fld4 As Action = Sub()
PassByRef(sharedRO) '0
End Sub
Dim fld5 As Action = Sub()
PassByRef(sharedRO) '1
PassByRef(instanceRO) '2
End Sub
Shared Sub New()
Dim q As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim ggg As Action = Sub()
PassByRef(sharedRO) '3
End Sub
End Sub
Sub New()
Dim q1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim q2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
Dim ggg As Action = Sub()
PassByRef(sharedRO) '4
PassByRef(instanceRO) '5
End Sub
End Sub
Sub Test()
Dim q1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
Dim q2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
Dim ggg As Action = Sub()
PassByRef(sharedRO) '6
PassByRef(instanceRO) '7
End Sub
End Sub
Shared Function PassByRef(ByRef x As Integer) As Integer
Return x
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Shared fld1 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Dim fld3 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
~~~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(sharedRO) '0
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(instanceRO) '2
~~~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Dim q As Object = From x In New Integer() {1, 2, 3} Select PassByRef(sharedRO)
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(sharedRO) '3
~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
Dim q2 As Object = From x In New Integer() {1, 2, 3} Select PassByRef(instanceRO)
~~~~~~~~~~
BC36602: 'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.
PassByRef(instanceRO) '5
~~~~~~~~~~
</expected>)
End Sub
<WorkItem(528731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528731")>
<Fact>
Public Sub BC36598ERR_CannotLiftRestrictedTypeQuery()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CannotLiftRestrictedTypeQuery">
<file name="a.vb">
Imports System
Imports System.Linq
Module m1
Sub goo(y As ArgIterator)
Dim col = New Integer() {1, 2}
Dim x As New ArgIterator
Dim q1 = From i In col Where x.GetRemainingCount > 0 Select a = 1
Dim q2 = From i In col Where y.GetRemainingCount > 0 Select a = 2
End Sub
End Module
</file>
</compilation>, additionalRefs:={Net40.SystemCore})
AssertTheseEmitDiagnostics(compilation,
<expected>
BC36598: Instance of restricted type 'ArgIterator' cannot be used in a query expression.
Dim q1 = From i In col Where x.GetRemainingCount > 0 Select a = 1
~
BC36598: Instance of restricted type 'ArgIterator' cannot be used in a query expression.
Dim q2 = From i In col Where y.GetRemainingCount > 0 Select a = 2
~
</expected>)
End Sub
<WorkItem(545801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545801")>
<Fact>
Public Sub NoPropertyMethodConflictForQueryOperators()
Dim verifier = CompileAndVerify(
<compilation name="NoPropertyMethodConflictForQueryOperators">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim q As Object
Dim _i003 As I003 = New CI003()
q = Aggregate a In _i003 Into Count()
End Sub
End Module
Interface I001
ReadOnly Property Count() As Integer
End Interface
Interface I002
Function [Select](ByVal selector As Func(Of Integer, Integer)) As I002
Function Count() As Integer
End Interface
Interface I003
Inherits I001, I002
End Interface
Class CI003
Implements I003
Public ReadOnly Property Count() As Integer Implements I001.Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function Count1() As Integer Implements I002.Count
System.Console.WriteLine("CI003.Count") : Return Nothing
End Function
Public Function [Select](ByVal selector As System.Func(Of Integer, Integer)) As I002 Implements I002.Select
Return Me
End Function
End Class
</file>
</compilation>,
expectedOutput:="CI003.Count", references:={Net451.SystemCore})
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub RangeVariableNameInference1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb"><![CDATA[
Option Strict On
Option Infer On
Imports System
Imports System.Collections
Imports System.Linq
Class Test
Sub Test02()
Dim x As System.Xml.Linq.XElement() = New System.Xml.Linq.XElement() { _
<Elem1>
<Elem2 Attr2="Elem2Attr2Val1" Attr-3="Elem2Attr3Val1">Elem2Val1</Elem2>
<Elem2 Attr2="Elem2Attr2Val2" Attr-3="Elem2Attr3Val2">Elem2Val2</Elem2>
<Elem2 Attr2="Elem2Attr2Val3" Attr-3="Elem2Attr3Val3">Elem2Val3</Elem2>
<Elem3>
<Elem2 Attr2="Elem2Attr2Val4" Attr-3="Elem2Attr3Val4">Elem2Val4</Elem2>
</Elem3>
<Elem-4>Elem4Val1</Elem-4>
</Elem1>}
Dim o As Object
o = From a In x Select y = 1, x.<Elem-4>
o = From a In x Select y = 1, x...<Elem-4>
o = From a In x Select y = 1, x.<Elem-4>.Value
o = From a In x Select y = 1, x...<Elem-4>.Value
o = From a In x Select y = 1, x.<Elem-4>.Value()
o = From a In x Select y = 1, x...<Elem-4>.Value()
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
o = From a In x Select y = 1, x.<Elem-4>(0)
o = From a In x Select y = 1, x...<Elem-4>(0)
o = From a In x Select y = 1, x.<Elem2>(0, 1)
o = From a In x Select y = 1, x...<Elem2>(0, 1)
o = From a In x Select y = 1, x.<Elem2>()
o = From a In x Select y = 1, x...<Elem2>()
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore,
SystemXmlRef,
SystemXmlLinqRef})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>.Value
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>.Value
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>.Value()
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>.Value()
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>
~~~~~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x.<Elem2>.@<Attr-3>.Normalize(0)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x.<Elem-4>(0)
~~~~~~
BC36614: Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.
o = From a In x Select y = 1, x...<Elem-4>(0)
~~~~~~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x.<Elem2>(0, 1)
~~~~~~~~~~~~~~~
BC36582: Too many arguments to extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x.<Elem2>(0, 1)
~
BC36599: Range variable name can be inferred only from a simple or qualified name with no arguments.
o = From a In x Select y = 1, x...<Elem2>(0, 1)
~~~~~~~~~~~~~~~~~
BC36582: Too many arguments to extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x...<Elem2>(0, 1)
~
BC36586: Argument not specified for parameter 'index' of extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x.<Elem2>()
~~~~~~~
BC36586: Argument not specified for parameter 'index' of extension method 'Public Function ElementAtOrDefault(index As Integer) As XElement' defined in 'Enumerable'.
o = From a In x Select y = 1, x...<Elem2>()
~~~~~~~
]]></expected>)
End Sub
<Fact>
Public Sub ERR_RestrictedType1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb"><(x As d(Of T)) As Queryable2
Return Nothing
End Function
Function Where(Of T)(x As Func(Of T, Boolean)) As Queryable2
Return Nothing
End Function
Function SelectMany(Of S)(x As d(Of Queryable2), y As d2(Of S)) As Queryable2
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim xx As Object
xx = From ii In New Queryable2() Select 1
xx = From ii In New Queryable2()
xx = From ii In New Queryable2() Select ii
xx = From ii In New Queryable2() Select (ii)
xx = From ii In New Queryable2() Select jj = ii
xx = From ii In New Queryable2() Where True
xx = From ii In New Queryable2(), jj In New Queryable2()
xx = From ii In New Queryable2(), jj In New Queryable2() Select 1
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2()
~~~~~~~~~~~~~~~~~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2()
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Select ii
~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2() Select ii
~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Select (ii)
~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2() Select (ii)
~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Select jj = ii
~~~~~~
BC36594: Definition of method 'Select' is not accessible in this context.
xx = From ii In New Queryable2() Select jj = ii
~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2() Where True
~~~~~
BC36594: Definition of method 'Where' is not accessible in this context.
xx = From ii In New Queryable2() Where True
~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
</expected>)
End Sub
<Fact()>
Public Sub ERR_RestrictedType1_2()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">< As Queryable2
Return Nothing
End Function
Function [Select](x As d12) As Queryable2
Return Nothing
End Function
Function SelectMany(Of S)(x As d(Of Queryable2), y As d2(Of S)) As Queryable2
Return Nothing
End Function
End Class
Module Module1
Sub Main()
Dim xx As Object
xx = From ii In New Queryable2() Select 1
xx = From ii In New Queryable2()
xx = From ii In New Queryable2() Select ii
xx = From ii In New Queryable2() Select (ii)
xx = From ii In New Queryable2() Select jj = ii
xx = From ii In New Queryable2(), jj In New Queryable2()
xx = From ii In New Queryable2(), jj In New Queryable2() Select 1
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef,
additionalRefs:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
xx = From ii In New Queryable2(), jj In New Queryable2()
~~
</expected>)
End Sub
<Fact()>
Public Sub ERR_RestrictedType1_3()
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Module M
Sub M()
Dim c1 As System.ArgIterator()() = Nothing
Dim c2 As System.TypedReference()() = Nothing
Dim z = From x In c1, y In c2
End Sub
End Module
</file>
</compilation>, references:={Net40.SystemCore}).AssertTheseDiagnostics(
<expected>
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim c1 As System.ArgIterator()() = Nothing
~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim c2 As System.TypedReference()() = Nothing
~~~~~~~~~~~~~~~~~~~~~~~~~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
BC31396: 'TypedReference' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.
Dim z = From x In c1, y In c2
~
</expected>)
End Sub
<WorkItem(542724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542724")>
<Fact>
Public Sub QueryExprInAttributes()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
<![CDATA[
<MyAttr(From i In Q1 Select 2)>
Class cls1
End Class
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
<![CDATA[
BC30002: Type 'MyAttr' is not defined.
<MyAttr(From i In Q1 Select 2)>
~~~~~~
BC30059: Constant expression is required.
<MyAttr(From i In Q1 Select 2)>
~~~~~~~~~~~~~~~~~~~~~
BC30451: 'Q1' is not declared. It may be inaccessible due to its protection level.
<MyAttr(From i In Q1 Select 2)>
~~
]]>
</expected>)
End Sub
<Fact>
Public Sub Bug10127()
Dim compilationDef =
<compilation name="Bug10127">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Linq
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim q As Object
q = Aggregate x In New Integer(){1} Into s = Sum(Nothing)
System.Console.WriteLine(q)
System.Console.WriteLine(q.GetType())
System.Console.WriteLine("-------")
q = From x In New Integer() {1} Order By Nothing
System.Console.WriteLine(DirectCast(q, IEnumerable(Of Integer))(0))
End Sub
End Module
</file>
</compilation>
Dim verifier = CompileAndVerify(compilationDef, references:={Net40.SystemCore},
expectedOutput:=
<![CDATA[
0
System.Int32
-------
1
]]>)
End Sub
<WorkItem(528969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528969")>
<Fact>
Public Sub InaccessibleElementAtOrDefault()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Class Q1
Public Function [Select](selector As Func(Of Integer, Integer)) As Q1
Return Nothing
End Function
Private Function ElementAtOrDefault(x As String) As Integer
Return 4
End Function
End Class
Module Test
Sub Main()
Dim qs As New Q1()
Dim zs = From q In qs Select q
Dim element = zs(2)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30367: Class 'Q1' cannot be indexed because it has no default property.
Dim element = zs(2)
~~
</expected>)
End Sub
<WorkItem(543120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543120")>
<Fact()>
Public Sub ExplicitTypeNameInExprRangeVarDeclInLetClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Linq
Module Module1
Sub Main(args As String())
Dim q1 = From i1 In New Integer() {4, 5} Let i2 As Integer = "Hello".Length
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(543138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543138")>
<Fact()>
Public Sub FunctionLambdaInConditionOfJoinClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Sub Main(args As String())
Dim arr = New Byte() {4, 5}
Dim q2 = From num In arr Join n1 In arr On num.ToString() Equals (Function() n1).ToString()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation,
expectedOutput:=
<![CDATA[
]]>)
End Sub
<WorkItem(543171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543171")>
<Fact()>
Public Sub FunctionLambdaInOrderByClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Linq
Module Program
Sub Main()
Dim arr = New Integer() {4, 5}
Dim q2 = From i1 In arr Order By Function() 5
Dim q3 = arr.OrderBy(Function(i1) Function() 5)
Dim q4 = From i1 In arr Order By ((Function() 5))
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
compilation.AssertNoDiagnostics()
CompileAndVerify(compilation,
expectedOutput:=
<![CDATA[
]]>)
End Sub
<WorkItem(529014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529014")>
<Fact>
Public Sub MissingByInGroupByQueryOperator()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Sub Main(args As String())
Dim arr = New Integer() {4, 5}
Dim q1 = From i1 In arr, i2 In arr Group i1, i2
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36605: 'By' expected.
Dim q1 = From i1 In arr, i2 In arr Group i1, i2
~
BC36615: 'Into' expected.
Dim q1 = From i1 In arr, i2 In arr Group i1, i2
~
</expected>)
End Sub
<Fact()>
Public Sub InaccessibleQueryMethodOnCollectionType1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'QueryAble.Private Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble(Of Integer)' is not accessible in this context because it is 'Private'.
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub InaccessibleQueryMethodOnCollectionType2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, String)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T)
System.Console.WriteLine("TakeWhile {0}", x)
Return New QueryAble(Of T)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'TakeWhile' is not accessible in this context.
Dim q0 = From s1 In qi Take While False'BIND:"Take While False"
~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupBy6()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v+1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'QueryAble.Private Function GroupBy(Of K, R)(key As Func(Of Integer, K), into As Func(Of K, QueryAble(Of Integer), R)) As QueryAble(Of R)' is not accessible in this context because it is 'Private'.
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupBy7()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of Integer), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v+1)
End Function
Private Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of String), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v+1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupBy' is not accessible in this context.
Dim q As Object = From s In qi Group By key = Nothing Into [Select](s)
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupJoin6()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'QueryAble.Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of Integer, K), innerKey As Func(Of I, K), x As Func(Of Integer, QueryAble(Of I), R)) As QueryAble(Of R)' is not accessible in this context because it is 'Private'.
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GroupJoin7()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of Integer), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
Private Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of String), R)) As QueryAble(Of R)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'GroupJoin' is not accessible in this context.
Dim q0 As Object = From s1 In qi Group Join t1 In qi On s1 Equals t1 Into [Select](t1)
~~~~~~~~~~
</expected>)
End Sub
<WorkItem(543523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543523")>
<Fact()>
Public Sub IncompleteLambdaInsideOrderByClause()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System
Imports System.Linq
Module Program
Sub Main()
Dim arr = New Integer() {4, 5}
Dim q2 = From i1 In arr Order By Function()
r
End Function
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
<![CDATA[
BC36594: Definition of method 'OrderBy' is not accessible in this context.
Dim q2 = From i1 In arr Order By Function()
~~~~~~~~
BC36610: Name 'r' is either not declared or not in the current scope.
r
~
BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
]]>
</expected>)
End Sub
<Fact(), WorkItem(544312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544312")>
Public Sub WideningConversionInOverloadResolution()
Dim compilationDef =
<compilation name="WideningConversionInOverloadResolution">
<file name="a.vb"><) As scen1(Of Integer)
Order &= "Sel1"
sel(Nothing)
Return New scen1(Of Integer)
End Function
Public Function [Select](ByVal sel As Func(Of T, Long)) As scen1(Of Long)
Order &= "Sel2"
sel(Nothing)
Return New scen1(Of Long)
End Function
Public Function [Select](ByVal sel As Func(Of T, Short)) As scen1(Of Short)
Order &= "Sel3"
sel(Nothing)
Return New scen1(Of Short)
End Function
Public Function GroupJoin(Of L, K2, R)(ByVal inner As scen1(Of L), ByVal key1 As Func(Of T, K2), ByVal key2 As Func(Of L, Object), ByVal res As Func(Of T, scen1(Of L), R)) As scen1(Of R)
Order &= "Join1"
key1(Nothing)
Return New scen1(Of R)
End Function
End Class
Sub Main()
' "Need a widening conversion for result")
Order = ""
Dim c1 = New scen1(Of Integer)
Dim q1 = From i In c1 Group Join j In c1 On i Equals j Into G = Group
Console.WriteLine(order)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation,
expectedOutput:=
<![CDATA[
Join1
]]>)
End Sub
<Fact, WorkItem(530910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530910")>
Public Sub IQueryableOverStringMax()
Dim compilationDef =
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Module Regress123995
Sub Call0()
Dim ints = New System.Collections.Generic.List(Of Integer)
ints.Add(1)
Dim source As IQueryable(Of Integer)
source = ints.AsQueryable
Dim strings = New System.Collections.Generic.List(Of String)
strings.Add("1")
strings.Add("2")
'Query Use of Max
'Generically Inferred
Dim query = _
From x In source _
Select strings.Max(Function(s) s)
End Sub
End Module
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseDll).AssertNoDiagnostics()
End Sub
<Fact, WorkItem(1042011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042011")>
Public Sub LambdaWithClosureInQueryExpressionAndPDB()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System.Linq
Module Module1
Sub Main()
Dim x = From y In {1} Select Function() y
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef, options:=TestOptions.DebugExe)
End Sub
<Fact, WorkItem(1099, "https://github.com/dotnet/roslyn/issues/1099")>
Public Sub LambdaWithErrorCrash()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Imports System.Linq
Class C
Shared Function Id(Of T)(a As T, i As Integer) As T
Return a
End Function
Sub F2()
Dim result = From a In Id({1}, 1), b In Id({1, 2}, 2)
From c In Id({1, 2, 3}, 3)
Let d = Id(1, 4), e = Id(2, 5)
Distinct
Take Whi
Aggregate f In Id({1}, 6), g In Id({2}, 7)
From j In Id({1}, 9)
Let h = Id(1, 4), i = Id(2, 5)
Where Id(g < 2, 8)
Into Count(), Distinct()
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, references:={Net40.SystemCore}, options:=TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'Whi' is not declared. It may be inaccessible due to its protection level.
Take Whi
~~~
</expected>)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub IOperationForQueryClause()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q'BIND:"From s In q"
Where s > 0
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... Where s > 0')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub IOperationForCollectionRangeVariable()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Where s > 0 Where 10 > s 'BIND:"From s In q Where s > 0 Where 10 > s"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q ... here 10 > s')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where 10 > s')
Instance Receiver:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '10 > s')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: '10 > s')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '10 > s')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '10 > s')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '10 > s')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: '10 > s')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
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)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")>
Public Sub IOperationForRangeVariableReference()
Dim source = <) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble()
Dim q2 As Object = From s In q Where s > 0 'BIND:"From s In q Where s > 0"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: QueryAble) (Syntax: 'From s In q Where s > 0')
Expression:
IInvocationOperation ( Function QueryAble.Where(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble) (OperationKind.Invocation, Type: QueryAble, IsImplicit) (Syntax: 'Where s > 0')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: QueryAble) (Syntax: 'q')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's > 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Boolean), IsImplicit) (Syntax: 's > 0')
Target:
IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Boolean) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's > 0')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's > 0')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's > 0')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's > 0')
Left:
IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<WorkItem(23223, "https://github.com/dotnet/roslyn/issues/23223")>
Public Sub DuplicateRangeVariableName_IOperation_01()
Dim source = <![CDATA[
Option Strict Off
Imports System
Imports System.Linq
Module Module1
Sub Main()
Dim q As Object = From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit 'BIND:"From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsInvalid) (Syntax: 'From implic ... ct implicit')
Expression:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>).Select(Of System.Int32)(selector As System.Func(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, System.Int32)) As System.Collections.Generic.IEnumerable(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'Select implicit')
Instance Receiver:
IInvocationOperation ( Function System.Collections.Generic.IEnumerable(Of System.Int32).Select(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>)(selector As System.Func(Of System.Int32, <anonymous type: Key implicit As System.Int32, Key $156 As System.String>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>), IsInvalid, IsImplicit) (Syntax: 'implicit = "1"')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.Int32), IsImplicit) (Syntax: 'implicit In ... ) {1, 2, 3}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer() {1, 2, 3}')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'New Integer() {1, 2, 3}')
Initializer:
IArrayInitializerOperation (3 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3}')
Element Values(3):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"1"')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, <anonymous type: Key implicit As System.Int32, Key $156 As System.String>), IsImplicit) (Syntax: '"1"')
Target:
IAnonymousFunctionOperation (Symbol: Function (implicit As System.Int32) As <anonymous type: Key implicit As System.Int32, Key $156 As System.String>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '"1"')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '"1"')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '"1"')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, IsInvalid, IsImplicit) (Syntax: 'implicit = "1"')
Initializers(2):
IParameterReferenceOperation: implicit (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'implicit')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'implicit')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, System.Int32), IsImplicit) (Syntax: 'implicit')
Target:
IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key implicit As System.Int32, Key $156 As System.String>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'implicit')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'implicit')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'implicit')
ReturnedValue:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key implicit As System.Int32, Key $156 As System.String>.implicit As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'implicit')
Instance Receiver:
IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key implicit As System.Int32, Key $156 As System.String>, IsImplicit) (Syntax: 'implicit')
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)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30978: Range variable 'implicit' hides a variable in an enclosing block or a range variable previously defined in the query expression.
Dim q As Object = From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit 'BIND:"From implicit In New Integer() {1, 2, 3} Let implicit = "1" Select implicit"
~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<WorkItem(23223, "https://github.com/dotnet/roslyn/issues/23223")>
Public Sub DuplicateRangeVariableName_IOperation_02()
Dim source = <![CDATA[
Option Strict Off
Imports System
Imports System.Linq
Module Module1
Sub Main()
Dim a = New Integer() {1, 2, 3}
Dim q As Object = From x In a Join x In a On x Equals 1 'BIND:"From x In a Join x In a On x Equals 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From x In a ... x Equals 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
Children(5):
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
Children(1):
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'x')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
IAnonymousFunctionOperation (Symbol: Function ($168 As System.Int32) As ?) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: '1')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IAnonymousFunctionOperation (Symbol: Function (x As System.Int32, $168 As System.Int32) As <anonymous type: Key x As System.Int32, Key $168 As System.Int32>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key x As System.Int32, Key $168 As System.Int32>, IsInvalid, IsImplicit) (Syntax: 'Join x In a ... x Equals 1')
Initializers(2):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
IParameterReferenceOperation: $168 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36600: Range variable 'x' is already declared.
Dim q As Object = From x In a Join x In a On x Equals 1 'BIND:"From x In a Join x In a On x Equals 1"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationErrors.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnClassName_ShouldFail()
{
var markup = @"
using System;
class MyClass$$
{
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnField_ShouldFail()
{
var markup = @"
using System;
class MyClass
{
int t$$ = 2;
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters()
{
var markup = @"class C { void $$M() { } }";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail()
{
var markup = @"
class C
{
public static C $$operator +(C a, C b)
{
return null;
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnClassName_ShouldFail()
{
var markup = @"
using System;
class MyClass$$
{
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnField_ShouldFail()
{
var markup = @"
using System;
class MyClass
{
int t$$ = 2;
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters()
{
var markup = @"class C { void $$M() { } }";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail()
{
var markup = @"
class C
{
public static C $$operator +(C a, C b)
{
return null;
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ReadOnlyRegionsChangedEventSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class ReadOnlyRegionsChangedEventSource : AbstractTaggerEventSource
{
private readonly ITextBuffer _subjectBuffer;
public ReadOnlyRegionsChangedEventSource(ITextBuffer subjectBuffer)
{
Contract.ThrowIfNull(subjectBuffer);
_subjectBuffer = subjectBuffer;
}
public override void Connect()
=> _subjectBuffer.ReadOnlyRegionsChanged += OnReadOnlyRegionsChanged;
public override void Disconnect()
=> _subjectBuffer.ReadOnlyRegionsChanged -= OnReadOnlyRegionsChanged;
private void OnReadOnlyRegionsChanged(object? sender, SnapshotSpanEventArgs e)
=> this.RaiseChanged();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class ReadOnlyRegionsChangedEventSource : AbstractTaggerEventSource
{
private readonly ITextBuffer _subjectBuffer;
public ReadOnlyRegionsChangedEventSource(ITextBuffer subjectBuffer)
{
Contract.ThrowIfNull(subjectBuffer);
_subjectBuffer = subjectBuffer;
}
public override void Connect()
=> _subjectBuffer.ReadOnlyRegionsChanged += OnReadOnlyRegionsChanged;
public override void Disconnect()
=> _subjectBuffer.ReadOnlyRegionsChanged -= OnReadOnlyRegionsChanged;
private void OnReadOnlyRegionsChanged(object? sender, SnapshotSpanEventArgs e)
=> this.RaiseChanged();
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Commands/CreateEventCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Commands;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Commands;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Commands
{
/// <summary>
/// Handle the command that adds an event handler method in code
/// </summary>
internal class CreateEventCommandHandler : AbstractExecuteWorkspaceCommandHandler
{
public override string Command => StringConstants.CreateEventHandlerCommand;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
public override TextDocumentIdentifier? GetTextDocumentIdentifier(ExecuteCommandParams request)
=> ((JToken)request.Arguments.First()).ToObject<TextDocumentIdentifier>();
public override async Task<object> HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.Arguments);
var document = context.Document;
if (document == null)
{
return false;
}
var commandService = document.Project.LanguageServices.GetService<IXamlCommandService>();
if (commandService == null)
{
return false;
}
// request.Arguments has two argument for CreateEventHandlerCommand
// Arguments[0]: TextDocumentIdentifier
// Arguments[1]: XamlEventDescription
var arguments = new object[] { ((JToken)request.Arguments[1]).ToObject<XamlEventDescription>() };
return await commandService.ExecuteCommandAsync(document, request.Command, arguments, cancellationToken).ConfigureAwait(false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Commands;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Commands;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Commands
{
/// <summary>
/// Handle the command that adds an event handler method in code
/// </summary>
internal class CreateEventCommandHandler : AbstractExecuteWorkspaceCommandHandler
{
public override string Command => StringConstants.CreateEventHandlerCommand;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
public override TextDocumentIdentifier? GetTextDocumentIdentifier(ExecuteCommandParams request)
=> ((JToken)request.Arguments.First()).ToObject<TextDocumentIdentifier>();
public override async Task<object> HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(request.Arguments);
var document = context.Document;
if (document == null)
{
return false;
}
var commandService = document.Project.LanguageServices.GetService<IXamlCommandService>();
if (commandService == null)
{
return false;
}
// request.Arguments has two argument for CreateEventHandlerCommand
// Arguments[0]: TextDocumentIdentifier
// Arguments[1]: XamlEventDescription
var arguments = new object[] { ((JToken)request.Arguments[1]).ToObject<XamlEventDescription>() };
return await commandService.ExecuteCommandAsync(document, request.Command, arguments, cancellationToken).ConfigureAwait(false);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/VisualBasic/Portable/Symbols/Wrapped/WrappedEventSymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Globalization
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents an event that is based on another event.
''' When inheriting from this class, one shouldn't assume that
''' the default behavior it has is appropriate for every case.
''' That behavior should be carefully reviewed and derived type
''' should override behavior as appropriate.
''' </summary>
Friend MustInherit Class WrappedEventSymbol
Inherits EventSymbol
Protected ReadOnly _underlyingEvent As EventSymbol
Public ReadOnly Property UnderlyingEvent As EventSymbol
Get
Return Me._underlyingEvent
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return Me._underlyingEvent.IsImplicitlyDeclared
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return Me._underlyingEvent.HasSpecialName
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Me._underlyingEvent.Name
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return Me._underlyingEvent.Locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return Me._underlyingEvent.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Me._underlyingEvent.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return Me._underlyingEvent.IsShared
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return Me._underlyingEvent.IsOverridable
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return Me._underlyingEvent.IsOverrides
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return Me._underlyingEvent.IsMustOverride
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return Me._underlyingEvent.IsNotOverridable
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Me._underlyingEvent.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property IsWindowsRuntimeEvent As Boolean
Get
Return Me._underlyingEvent.IsWindowsRuntimeEvent
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return Me._underlyingEvent.HasRuntimeSpecialName
End Get
End Property
Public Sub New(underlyingEvent As EventSymbol)
Debug.Assert(underlyingEvent IsNot Nothing)
Me._underlyingEvent = underlyingEvent
End Sub
Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
Return Me._underlyingEvent.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Globalization
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents an event that is based on another event.
''' When inheriting from this class, one shouldn't assume that
''' the default behavior it has is appropriate for every case.
''' That behavior should be carefully reviewed and derived type
''' should override behavior as appropriate.
''' </summary>
Friend MustInherit Class WrappedEventSymbol
Inherits EventSymbol
Protected ReadOnly _underlyingEvent As EventSymbol
Public ReadOnly Property UnderlyingEvent As EventSymbol
Get
Return Me._underlyingEvent
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return Me._underlyingEvent.IsImplicitlyDeclared
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return Me._underlyingEvent.HasSpecialName
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Me._underlyingEvent.Name
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return Me._underlyingEvent.Locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return Me._underlyingEvent.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Me._underlyingEvent.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return Me._underlyingEvent.IsShared
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return Me._underlyingEvent.IsOverridable
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return Me._underlyingEvent.IsOverrides
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return Me._underlyingEvent.IsMustOverride
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return Me._underlyingEvent.IsNotOverridable
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Me._underlyingEvent.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property IsWindowsRuntimeEvent As Boolean
Get
Return Me._underlyingEvent.IsWindowsRuntimeEvent
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return Me._underlyingEvent.HasRuntimeSpecialName
End Get
End Property
Public Sub New(underlyingEvent As EventSymbol)
Debug.Assert(underlyingEvent IsNot Nothing)
Me._underlyingEvent = underlyingEvent
End Sub
Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
Return Me._underlyingEvent.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/Core/Portable/Storage/SQLite/Interop/SafeSqliteBlobHandle.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.Shared.Extensions;
using SQLitePCL;
namespace Microsoft.CodeAnalysis.SQLite.Interop
{
internal sealed class SafeSqliteBlobHandle : SafeHandle
{
private readonly sqlite3_blob? _wrapper;
private readonly SafeHandleLease _lease;
private readonly SafeHandleLease _sqliteLease;
public SafeSqliteBlobHandle(SafeSqliteHandle sqliteHandle, sqlite3_blob? wrapper)
: base(invalidHandleValue: IntPtr.Zero, ownsHandle: true)
{
_wrapper = wrapper;
if (wrapper is not null)
{
_lease = wrapper.Lease();
SetHandle(wrapper.DangerousGetHandle());
}
else
{
_lease = default;
SetHandle(IntPtr.Zero);
}
_sqliteLease = sqliteHandle.Lease();
}
public override bool IsInvalid => handle == IntPtr.Zero;
public sqlite3_blob DangerousGetWrapper()
=> _wrapper!;
protected override bool ReleaseHandle()
{
try
{
using var _ = _wrapper;
_lease.Dispose();
SetHandle(IntPtr.Zero);
return true;
}
finally
{
_sqliteLease.Dispose();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using SQLitePCL;
namespace Microsoft.CodeAnalysis.SQLite.Interop
{
internal sealed class SafeSqliteBlobHandle : SafeHandle
{
private readonly sqlite3_blob? _wrapper;
private readonly SafeHandleLease _lease;
private readonly SafeHandleLease _sqliteLease;
public SafeSqliteBlobHandle(SafeSqliteHandle sqliteHandle, sqlite3_blob? wrapper)
: base(invalidHandleValue: IntPtr.Zero, ownsHandle: true)
{
_wrapper = wrapper;
if (wrapper is not null)
{
_lease = wrapper.Lease();
SetHandle(wrapper.DangerousGetHandle());
}
else
{
_lease = default;
SetHandle(IntPtr.Zero);
}
_sqliteLease = sqliteHandle.Lease();
}
public override bool IsInvalid => handle == IntPtr.Zero;
public sqlite3_blob DangerousGetWrapper()
=> _wrapper!;
protected override bool ReleaseHandle()
{
try
{
using var _ = _wrapper;
_lease.Dispose();
SetHandle(IntPtr.Zero);
return true;
}
finally
{
_sqliteLease.Dispose();
}
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncIteratorInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Additional information for rewriting an async-iterator.
/// </summary>
internal sealed class AsyncIteratorInfo
{
// This `ManualResetValueTaskSourceCore<bool>` struct implements the `IValueTaskSource` logic
internal FieldSymbol PromiseOfValueOrEndField { get; }
// This `CancellationTokenSource` field helps combine two cancellation tokens
internal FieldSymbol CombinedTokensField { get; }
// Stores the current/yielded value
internal FieldSymbol CurrentField { get; }
// Whether the state machine is in dispose mode
internal FieldSymbol DisposeModeField { get; }
// Method to fulfill the promise with a result: `void ManualResetValueTaskSourceCore<T>.SetResult(T result)`
internal MethodSymbol SetResultMethod { get; }
// Method to fulfill the promise with an exception: `void ManualResetValueTaskSourceCore<T>.SetException(Exception error)`
internal MethodSymbol SetExceptionMethod { get; }
public AsyncIteratorInfo(FieldSymbol promiseOfValueOrEndField, FieldSymbol combinedTokensField, FieldSymbol currentField, FieldSymbol disposeModeField,
MethodSymbol setResultMethod, MethodSymbol setExceptionMethod)
{
PromiseOfValueOrEndField = promiseOfValueOrEndField;
CombinedTokensField = combinedTokensField;
CurrentField = currentField;
DisposeModeField = disposeModeField;
SetResultMethod = setResultMethod;
SetExceptionMethod = setExceptionMethod;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Additional information for rewriting an async-iterator.
/// </summary>
internal sealed class AsyncIteratorInfo
{
// This `ManualResetValueTaskSourceCore<bool>` struct implements the `IValueTaskSource` logic
internal FieldSymbol PromiseOfValueOrEndField { get; }
// This `CancellationTokenSource` field helps combine two cancellation tokens
internal FieldSymbol CombinedTokensField { get; }
// Stores the current/yielded value
internal FieldSymbol CurrentField { get; }
// Whether the state machine is in dispose mode
internal FieldSymbol DisposeModeField { get; }
// Method to fulfill the promise with a result: `void ManualResetValueTaskSourceCore<T>.SetResult(T result)`
internal MethodSymbol SetResultMethod { get; }
// Method to fulfill the promise with an exception: `void ManualResetValueTaskSourceCore<T>.SetException(Exception error)`
internal MethodSymbol SetExceptionMethod { get; }
public AsyncIteratorInfo(FieldSymbol promiseOfValueOrEndField, FieldSymbol combinedTokensField, FieldSymbol currentField, FieldSymbol disposeModeField,
MethodSymbol setResultMethod, MethodSymbol setExceptionMethod)
{
PromiseOfValueOrEndField = promiseOfValueOrEndField;
CombinedTokensField = combinedTokensField;
CurrentField = currentField;
DisposeModeField = disposeModeField;
SetResultMethod = setResultMethod;
SetExceptionMethod = setExceptionMethod;
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/VisualBasic/Portable/Scanner/TokenFactories.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'-----------------------------------------------------------------------------
' Contains the definition of the Scanner, which produces tokens from text
'-----------------------------------------------------------------------------
Option Compare Binary
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Scanner
#Region "Caches"
#Region "Trivia"
Private Structure TriviaKey
Public ReadOnly spelling As String
Public ReadOnly kind As SyntaxKind
Public Sub New(spelling As String, kind As SyntaxKind)
Me.spelling = spelling
Me.kind = kind
End Sub
End Structure
Private Shared ReadOnly s_triviaKeyHasher As Func(Of TriviaKey, Integer) =
Function(key) RuntimeHelpers.GetHashCode(key.spelling) Xor key.kind
Private Shared ReadOnly s_triviaKeyEquality As Func(Of TriviaKey, SyntaxTrivia, Boolean) =
Function(key, value) (key.spelling Is value.Text) AndAlso (key.kind = value.Kind)
Private Shared ReadOnly s_singleSpaceWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_fourSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_eightSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_twelveSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_sixteenSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared Function CreateWsTable() As CachingFactory(Of TriviaKey, SyntaxTrivia)
Dim table = New CachingFactory(Of TriviaKey, SyntaxTrivia)(TABLE_LIMIT, Nothing, s_triviaKeyHasher, s_triviaKeyEquality)
' Prepopulate the table with some common values
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_singleSpaceWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_fourSpacesWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_eightSpacesWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_twelveSpacesWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_sixteenSpacesWhitespaceTrivia)
Return table
End Function
#End Region
#Region "WhiteSpaceList"
Private Shared ReadOnly s_wsListKeyHasher As Func(Of SyntaxListBuilder, Integer) =
Function(builder)
Dim code = 0
For i = 0 To builder.Count - 1
Dim value = builder(i)
' shift because there could be the same trivia nodes in the list
code = (code << 1) Xor RuntimeHelpers.GetHashCode(value)
Next
Return code
End Function
Private Shared ReadOnly s_wsListKeyEquality As Func(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), Boolean) =
Function(builder, list)
If builder.Count <> list.Count Then
Return False
End If
For i = 0 To builder.Count - 1
If builder(i) IsNot list.ItemUntyped(i) Then
Return False
End If
Next
Return True
End Function
Private Shared ReadOnly s_wsListFactory As Func(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) =
Function(builder)
Return builder.ToList(Of VisualBasicSyntaxNode)()
End Function
#End Region
#Region "Tokens"
Private Structure TokenParts
Friend ReadOnly spelling As String
Friend ReadOnly pTrivia As GreenNode
Friend ReadOnly fTrivia As GreenNode
Friend Sub New(pTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), fTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), spelling As String)
Me.spelling = spelling
Me.pTrivia = pTrivia.Node
Me.fTrivia = fTrivia.Node
End Sub
End Structure
Private Shared ReadOnly s_tokenKeyHasher As Func(Of TokenParts, Integer) =
Function(key)
Dim code = RuntimeHelpers.GetHashCode(key.spelling)
Dim trivia = key.pTrivia
If trivia IsNot Nothing Then
code = code Xor (RuntimeHelpers.GetHashCode(trivia) << 1)
End If
trivia = key.fTrivia
If trivia IsNot Nothing Then
code = code Xor RuntimeHelpers.GetHashCode(trivia)
End If
Return code
End Function
Private Shared ReadOnly s_tokenKeyEquality As Func(Of TokenParts, SyntaxToken, Boolean) =
Function(x, y)
If y Is Nothing OrElse
x.spelling IsNot y.Text OrElse
x.fTrivia IsNot y.GetTrailingTrivia OrElse
x.pTrivia IsNot y.GetLeadingTrivia Then
Return False
End If
Return True
End Function
#End Region
Private Shared Function CanCache(trivia As SyntaxListBuilder) As Boolean
For i = 0 To trivia.Count - 1
Dim t = trivia(i)
Select Case t.RawKind
Case SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.DocumentationCommentExteriorTrivia
'do nothing
Case Else
Return False
End Select
Next
Return True
End Function
#End Region
#Region "Trivia"
Friend Function MakeWhiteSpaceTrivia(text As String) As SyntaxTrivia
Debug.Assert(text.Length > 0)
Debug.Assert(text.All(AddressOf IsWhitespace))
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.WhitespaceTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.WhitespaceTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Function MakeEndOfLineTrivia(text As String) As SyntaxTrivia
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.EndOfLineTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.EndOfLineTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Function MakeColonTrivia(text As String) As SyntaxTrivia
Debug.Assert(text.Length = 1)
Debug.Assert(IsColon(text(0)))
Dim ct As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.ColonTrivia)
If Not _wsTable.TryGetValue(key, ct) Then
ct = SyntaxFactory.ColonTrivia(text)
_wsTable.Add(key, ct)
End If
Return ct
End Function
Private Shared ReadOnly s_crLfTrivia As SyntaxTrivia = SyntaxFactory.EndOfLineTrivia(vbCrLf)
Friend Function MakeEndOfLineTriviaCRLF() As SyntaxTrivia
AdvanceChar(2)
Return s_crLfTrivia
End Function
Friend Function MakeLineContinuationTrivia(text As String) As SyntaxTrivia
Debug.Assert(text.Length = 1)
Debug.Assert(IsUnderscore(text(0)))
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.LineContinuationTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.LineContinuationTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Function MakeDocumentationCommentExteriorTrivia(text As String) As SyntaxTrivia
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.DocumentationCommentExteriorTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.DocumentationCommentExteriorTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Shared Function MakeCommentTrivia(text As String) As SyntaxTrivia
Return SyntaxFactory.SyntaxTrivia(SyntaxKind.CommentTrivia, text)
End Function
Friend Function MakeTriviaArray(builder As SyntaxListBuilder) As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)
If builder.Count = 0 Then
Return Nothing
End If
Dim foundTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing
Dim useCache = CanCache(builder)
If useCache Then
Return _wslTable.GetOrMakeValue(builder)
Else
Return builder.ToList
End If
End Function
#End Region
#Region "Identifiers"
Private Function MakeIdentifier(spelling As String,
contextualKind As SyntaxKind,
isBracketed As Boolean,
BaseSpelling As String,
TypeCharacter As TypeCharacter,
leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As IdentifierTokenSyntax
Dim followingTrivia = ScanSingleLineTrivia()
Return MakeIdentifier(spelling,
contextualKind,
isBracketed,
BaseSpelling,
TypeCharacter,
leadingTrivia,
followingTrivia)
End Function
Friend Function MakeIdentifier(keyword As KeywordSyntax) As IdentifierTokenSyntax
Return MakeIdentifier(keyword.Text,
keyword.Kind,
False,
keyword.Text,
TypeCharacter.None,
keyword.GetLeadingTrivia,
keyword.GetTrailingTrivia)
End Function
Private Function MakeIdentifier(spelling As String,
contextualKind As SyntaxKind,
isBracketed As Boolean,
BaseSpelling As String,
TypeCharacter As TypeCharacter,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode),
followingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode)) As IdentifierTokenSyntax
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim id As IdentifierTokenSyntax = Nothing
If _idTable.TryGetValue(tp, id) Then
Return id
End If
If contextualKind <> SyntaxKind.IdentifierToken OrElse
isBracketed = True OrElse
TypeCharacter <> TypeCharacter.None Then
id = SyntaxFactory.Identifier(spelling, contextualKind, isBracketed, BaseSpelling, TypeCharacter, precedingTrivia.Node, followingTrivia.Node)
Else
id = SyntaxFactory.Identifier(spelling, precedingTrivia.Node, followingTrivia.Node)
End If
_idTable.Add(tp, id)
Return id
End Function
#End Region
#Region "Keywords"
Private Function MakeKeyword(tokenType As SyntaxKind,
spelling As String,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As KeywordSyntax
Dim followingTrivia = ScanSingleLineTrivia()
Return MakeKeyword(tokenType,
spelling,
precedingTrivia,
followingTrivia)
End Function
Friend Function MakeKeyword(identifier As IdentifierTokenSyntax) As KeywordSyntax
Debug.Assert(identifier.PossibleKeywordKind <> SyntaxKind.IdentifierToken AndAlso
Not identifier.IsBracketed AndAlso
(identifier.TypeCharacter = TypeCharacter.None OrElse identifier.PossibleKeywordKind = SyntaxKind.MidKeyword))
Return MakeKeyword(identifier.PossibleKeywordKind,
identifier.Text,
identifier.GetLeadingTrivia,
identifier.GetTrailingTrivia)
End Function
Friend Function MakeKeyword(xmlName As XmlNameTokenSyntax) As KeywordSyntax
Debug.Assert(xmlName.PossibleKeywordKind <> SyntaxKind.XmlNameToken)
Return MakeKeyword(xmlName.PossibleKeywordKind,
xmlName.Text,
xmlName.GetLeadingTrivia,
xmlName.GetTrailingTrivia)
End Function
Private Function MakeKeyword(tokenType As SyntaxKind,
spelling As String,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode),
followingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode)) As KeywordSyntax
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim kw As KeywordSyntax = Nothing
If _kwTable.TryGetValue(tp, kw) Then
Return kw
End If
kw = New KeywordSyntax(tokenType, spelling, precedingTrivia.Node, followingTrivia.Node)
_kwTable.Add(tp, kw)
Return kw
End Function
#End Region
#Region "Punctuation"
Friend Function MakePunctuationToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
spelling As String,
kind As SyntaxKind) As PunctuationSyntax
Dim followingTrivia = ScanSingleLineTrivia()
Return MakePunctuationToken(kind, spelling, precedingTrivia, followingTrivia)
End Function
Private Function MakePunctuationToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
length As Integer,
kind As SyntaxKind) As PunctuationSyntax
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Return MakePunctuationToken(kind, spelling, precedingTrivia, followingTrivia)
End Function
Friend Function MakePunctuationToken(kind As SyntaxKind,
spelling As String,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode),
followingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode)
) As PunctuationSyntax
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As PunctuationSyntax = Nothing
If _punctTable.TryGetValue(tp, p) Then
Return p
End If
p = New PunctuationSyntax(kind, spelling, precedingTrivia.Node, followingTrivia.Node)
_punctTable.Add(tp, p)
Return p
End Function
Private Function MakeOpenParenToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_LEFT_PARENTHESIS_STRING, "(")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.OpenParenToken)
End Function
Private Function MakeCloseParenToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_RIGHT_PARENTHESIS_STRING, ")")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CloseParenToken)
End Function
Private Function MakeDotToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_FULL_STOP_STRING, ".")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.DotToken)
End Function
Private Function MakeCommaToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_COMMA_STRING, ",")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CommaToken)
End Function
Private Function MakeEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_EQUALS_SIGN_STRING, "=")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.EqualsToken)
End Function
Private Function MakeHashToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_NUMBER_SIGN_STRING, "#")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.HashToken)
End Function
Private Function MakeAmpersandToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_AMPERSAND_STRING, "&")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.AmpersandToken)
End Function
Private Function MakeOpenBraceToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_LEFT_CURLY_BRACKET_STRING, "{")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.OpenBraceToken)
End Function
Private Function MakeCloseBraceToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_RIGHT_CURLY_BRACKET_STRING, "}")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CloseBraceToken)
End Function
Private Function MakeColonToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Debug.Assert(Peek() = If(charIsFullWidth, FULLWIDTH_COLON, ":"c))
Debug.Assert(Not precedingTrivia.Any())
Dim width = _endOfTerminatorTrivia - _lineBufferOffset
Debug.Assert(width = 1)
AdvanceChar(width)
' Colon does not consume trailing trivia
Return SyntaxFactory.ColonToken
End Function
Private Function MakeEmptyToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, "", SyntaxKind.EmptyToken)
End Function
Private Function MakePlusToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_PLUS_SIGN_STRING, "+")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.PlusToken)
End Function
Private Function MakeMinusToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_HYPHEN_MINUS_STRING, "-")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.MinusToken)
End Function
Private Function MakeAsteriskToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_ASTERISK_STRING, "*")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.AsteriskToken)
End Function
Private Function MakeSlashToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_SOLIDUS_STRING, "/")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.SlashToken)
End Function
Private Function MakeBackslashToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_REVERSE_SOLIDUS_STRING, "\")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.BackslashToken)
End Function
Private Function MakeCaretToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_CIRCUMFLEX_ACCENT_STRING, "^")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CaretToken)
End Function
Private Function MakeExclamationToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_EXCLAMATION_MARK_STRING, "!")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.ExclamationToken)
End Function
Private Function MakeQuestionToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_QUESTION_MARK_STRING, "?")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.QuestionToken)
End Function
Private Function MakeGreaterThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_GREATER_THAN_SIGN_STRING, ">")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.GreaterThanToken)
End Function
Private Function MakeLessThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_LESS_THAN_SIGN_STRING, "<")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.LessThanToken)
End Function
' ==== TOKENS WITH NOT FIXED SPELLING
Private Function MakeStatementTerminatorToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), width As Integer) As PunctuationSyntax
Debug.Assert(_endOfTerminatorTrivia = _lineBufferOffset + width)
Debug.Assert(width = 1 OrElse width = 2)
Debug.Assert(Not precedingTrivia.Any())
AdvanceChar(width)
' Statement terminator does not consume trailing trivia
Return SyntaxFactory.StatementTerminatorToken
End Function
Private Function MakeAmpersandEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.AmpersandEqualsToken)
End Function
Private Function MakeColonEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.ColonEqualsToken)
End Function
Private Function MakePlusEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.PlusEqualsToken)
End Function
Private Function MakeMinusEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.MinusEqualsToken)
End Function
Private Function MakeAsteriskEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.AsteriskEqualsToken)
End Function
Private Function MakeSlashEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.SlashEqualsToken)
End Function
Private Function MakeBackSlashEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.BackslashEqualsToken)
End Function
Private Function MakeCaretEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.CaretEqualsToken)
End Function
Private Function MakeGreaterThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.GreaterThanEqualsToken)
End Function
Private Function MakeLessThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanEqualsToken)
End Function
Private Function MakeLessThanGreaterThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanGreaterThanToken)
End Function
Private Function MakeLessThanLessThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanLessThanToken)
End Function
Private Function MakeGreaterThanGreaterThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.GreaterThanGreaterThanToken)
End Function
Private Function MakeLessThanLessThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanLessThanEqualsToken)
End Function
Private Function MakeGreaterThanGreaterThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.GreaterThanGreaterThanEqualsToken)
End Function
Private Function MakeAtToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_COMMERCIAL_AT_STRING, "@")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.AtToken)
End Function
#End Region
#Region "Literals"
Private Function MakeIntegerLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
base As LiteralBase,
typeCharacter As TypeCharacter,
integralValue As ULong,
length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.IntegerLiteralToken(
spelling,
base,
typeCharacter,
integralValue,
precedingTrivia.Node,
followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeCharacterLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), value As Char, length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.CharacterLiteralToken(spelling, value, precedingTrivia.Node, followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeDateLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), value As DateTime, length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.DateLiteralToken(spelling, value, precedingTrivia.Node, followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeFloatingLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
typeCharacter As TypeCharacter,
floatingValue As Double,
length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.FloatingLiteralToken(
spelling,
typeCharacter,
floatingValue,
precedingTrivia.Node,
followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeDecimalLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
typeCharacter As TypeCharacter,
decimalValue As Decimal,
length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.DecimalLiteralToken(
spelling,
typeCharacter,
decimalValue,
precedingTrivia.Node,
followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
#End Region
' BAD TOKEN
Private Function MakeBadToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer, errId As ERRID) As SyntaxToken
Dim spelling = GetTextNotInterned(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim result1 = SyntaxFactory.BadToken(SyntaxSubKind.None, spelling, precedingTrivia.Node, followingTrivia.Node)
Dim errResult1 = result1.AddError(ErrorFactory.ErrorInfo(errId))
Return DirectCast(errResult1, SyntaxToken)
End Function
Private Shared Function MakeEofToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken
Return SyntaxFactory.Token(precedingTrivia.Node, SyntaxKind.EndOfFileToken, Nothing, String.Empty)
End Function
Private ReadOnly _simpleEof As SyntaxToken = SyntaxFactory.Token(Nothing, SyntaxKind.EndOfFileToken, Nothing, String.Empty)
Private Function MakeEofToken() As SyntaxToken
Return _simpleEof
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'-----------------------------------------------------------------------------
' Contains the definition of the Scanner, which produces tokens from text
'-----------------------------------------------------------------------------
Option Compare Binary
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Scanner
#Region "Caches"
#Region "Trivia"
Private Structure TriviaKey
Public ReadOnly spelling As String
Public ReadOnly kind As SyntaxKind
Public Sub New(spelling As String, kind As SyntaxKind)
Me.spelling = spelling
Me.kind = kind
End Sub
End Structure
Private Shared ReadOnly s_triviaKeyHasher As Func(Of TriviaKey, Integer) =
Function(key) RuntimeHelpers.GetHashCode(key.spelling) Xor key.kind
Private Shared ReadOnly s_triviaKeyEquality As Func(Of TriviaKey, SyntaxTrivia, Boolean) =
Function(key, value) (key.spelling Is value.Text) AndAlso (key.kind = value.Kind)
Private Shared ReadOnly s_singleSpaceWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_fourSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_eightSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_twelveSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared ReadOnly s_sixteenSpacesWhitespaceTrivia As SyntaxTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Private Shared Function CreateWsTable() As CachingFactory(Of TriviaKey, SyntaxTrivia)
Dim table = New CachingFactory(Of TriviaKey, SyntaxTrivia)(TABLE_LIMIT, Nothing, s_triviaKeyHasher, s_triviaKeyEquality)
' Prepopulate the table with some common values
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_singleSpaceWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_fourSpacesWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_eightSpacesWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_twelveSpacesWhitespaceTrivia)
table.Add(New TriviaKey(" ", SyntaxKind.WhitespaceTrivia), s_sixteenSpacesWhitespaceTrivia)
Return table
End Function
#End Region
#Region "WhiteSpaceList"
Private Shared ReadOnly s_wsListKeyHasher As Func(Of SyntaxListBuilder, Integer) =
Function(builder)
Dim code = 0
For i = 0 To builder.Count - 1
Dim value = builder(i)
' shift because there could be the same trivia nodes in the list
code = (code << 1) Xor RuntimeHelpers.GetHashCode(value)
Next
Return code
End Function
Private Shared ReadOnly s_wsListKeyEquality As Func(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), Boolean) =
Function(builder, list)
If builder.Count <> list.Count Then
Return False
End If
For i = 0 To builder.Count - 1
If builder(i) IsNot list.ItemUntyped(i) Then
Return False
End If
Next
Return True
End Function
Private Shared ReadOnly s_wsListFactory As Func(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) =
Function(builder)
Return builder.ToList(Of VisualBasicSyntaxNode)()
End Function
#End Region
#Region "Tokens"
Private Structure TokenParts
Friend ReadOnly spelling As String
Friend ReadOnly pTrivia As GreenNode
Friend ReadOnly fTrivia As GreenNode
Friend Sub New(pTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), fTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), spelling As String)
Me.spelling = spelling
Me.pTrivia = pTrivia.Node
Me.fTrivia = fTrivia.Node
End Sub
End Structure
Private Shared ReadOnly s_tokenKeyHasher As Func(Of TokenParts, Integer) =
Function(key)
Dim code = RuntimeHelpers.GetHashCode(key.spelling)
Dim trivia = key.pTrivia
If trivia IsNot Nothing Then
code = code Xor (RuntimeHelpers.GetHashCode(trivia) << 1)
End If
trivia = key.fTrivia
If trivia IsNot Nothing Then
code = code Xor RuntimeHelpers.GetHashCode(trivia)
End If
Return code
End Function
Private Shared ReadOnly s_tokenKeyEquality As Func(Of TokenParts, SyntaxToken, Boolean) =
Function(x, y)
If y Is Nothing OrElse
x.spelling IsNot y.Text OrElse
x.fTrivia IsNot y.GetTrailingTrivia OrElse
x.pTrivia IsNot y.GetLeadingTrivia Then
Return False
End If
Return True
End Function
#End Region
Private Shared Function CanCache(trivia As SyntaxListBuilder) As Boolean
For i = 0 To trivia.Count - 1
Dim t = trivia(i)
Select Case t.RawKind
Case SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.DocumentationCommentExteriorTrivia
'do nothing
Case Else
Return False
End Select
Next
Return True
End Function
#End Region
#Region "Trivia"
Friend Function MakeWhiteSpaceTrivia(text As String) As SyntaxTrivia
Debug.Assert(text.Length > 0)
Debug.Assert(text.All(AddressOf IsWhitespace))
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.WhitespaceTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.WhitespaceTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Function MakeEndOfLineTrivia(text As String) As SyntaxTrivia
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.EndOfLineTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.EndOfLineTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Function MakeColonTrivia(text As String) As SyntaxTrivia
Debug.Assert(text.Length = 1)
Debug.Assert(IsColon(text(0)))
Dim ct As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.ColonTrivia)
If Not _wsTable.TryGetValue(key, ct) Then
ct = SyntaxFactory.ColonTrivia(text)
_wsTable.Add(key, ct)
End If
Return ct
End Function
Private Shared ReadOnly s_crLfTrivia As SyntaxTrivia = SyntaxFactory.EndOfLineTrivia(vbCrLf)
Friend Function MakeEndOfLineTriviaCRLF() As SyntaxTrivia
AdvanceChar(2)
Return s_crLfTrivia
End Function
Friend Function MakeLineContinuationTrivia(text As String) As SyntaxTrivia
Debug.Assert(text.Length = 1)
Debug.Assert(IsUnderscore(text(0)))
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.LineContinuationTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.LineContinuationTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Function MakeDocumentationCommentExteriorTrivia(text As String) As SyntaxTrivia
Dim ws As SyntaxTrivia = Nothing
Dim key = New TriviaKey(text, SyntaxKind.DocumentationCommentExteriorTrivia)
If Not _wsTable.TryGetValue(key, ws) Then
ws = SyntaxFactory.DocumentationCommentExteriorTrivia(text)
_wsTable.Add(key, ws)
End If
Return ws
End Function
Friend Shared Function MakeCommentTrivia(text As String) As SyntaxTrivia
Return SyntaxFactory.SyntaxTrivia(SyntaxKind.CommentTrivia, text)
End Function
Friend Function MakeTriviaArray(builder As SyntaxListBuilder) As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)
If builder.Count = 0 Then
Return Nothing
End If
Dim foundTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing
Dim useCache = CanCache(builder)
If useCache Then
Return _wslTable.GetOrMakeValue(builder)
Else
Return builder.ToList
End If
End Function
#End Region
#Region "Identifiers"
Private Function MakeIdentifier(spelling As String,
contextualKind As SyntaxKind,
isBracketed As Boolean,
BaseSpelling As String,
TypeCharacter As TypeCharacter,
leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As IdentifierTokenSyntax
Dim followingTrivia = ScanSingleLineTrivia()
Return MakeIdentifier(spelling,
contextualKind,
isBracketed,
BaseSpelling,
TypeCharacter,
leadingTrivia,
followingTrivia)
End Function
Friend Function MakeIdentifier(keyword As KeywordSyntax) As IdentifierTokenSyntax
Return MakeIdentifier(keyword.Text,
keyword.Kind,
False,
keyword.Text,
TypeCharacter.None,
keyword.GetLeadingTrivia,
keyword.GetTrailingTrivia)
End Function
Private Function MakeIdentifier(spelling As String,
contextualKind As SyntaxKind,
isBracketed As Boolean,
BaseSpelling As String,
TypeCharacter As TypeCharacter,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode),
followingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode)) As IdentifierTokenSyntax
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim id As IdentifierTokenSyntax = Nothing
If _idTable.TryGetValue(tp, id) Then
Return id
End If
If contextualKind <> SyntaxKind.IdentifierToken OrElse
isBracketed = True OrElse
TypeCharacter <> TypeCharacter.None Then
id = SyntaxFactory.Identifier(spelling, contextualKind, isBracketed, BaseSpelling, TypeCharacter, precedingTrivia.Node, followingTrivia.Node)
Else
id = SyntaxFactory.Identifier(spelling, precedingTrivia.Node, followingTrivia.Node)
End If
_idTable.Add(tp, id)
Return id
End Function
#End Region
#Region "Keywords"
Private Function MakeKeyword(tokenType As SyntaxKind,
spelling As String,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As KeywordSyntax
Dim followingTrivia = ScanSingleLineTrivia()
Return MakeKeyword(tokenType,
spelling,
precedingTrivia,
followingTrivia)
End Function
Friend Function MakeKeyword(identifier As IdentifierTokenSyntax) As KeywordSyntax
Debug.Assert(identifier.PossibleKeywordKind <> SyntaxKind.IdentifierToken AndAlso
Not identifier.IsBracketed AndAlso
(identifier.TypeCharacter = TypeCharacter.None OrElse identifier.PossibleKeywordKind = SyntaxKind.MidKeyword))
Return MakeKeyword(identifier.PossibleKeywordKind,
identifier.Text,
identifier.GetLeadingTrivia,
identifier.GetTrailingTrivia)
End Function
Friend Function MakeKeyword(xmlName As XmlNameTokenSyntax) As KeywordSyntax
Debug.Assert(xmlName.PossibleKeywordKind <> SyntaxKind.XmlNameToken)
Return MakeKeyword(xmlName.PossibleKeywordKind,
xmlName.Text,
xmlName.GetLeadingTrivia,
xmlName.GetTrailingTrivia)
End Function
Private Function MakeKeyword(tokenType As SyntaxKind,
spelling As String,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode),
followingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode)) As KeywordSyntax
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim kw As KeywordSyntax = Nothing
If _kwTable.TryGetValue(tp, kw) Then
Return kw
End If
kw = New KeywordSyntax(tokenType, spelling, precedingTrivia.Node, followingTrivia.Node)
_kwTable.Add(tp, kw)
Return kw
End Function
#End Region
#Region "Punctuation"
Friend Function MakePunctuationToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
spelling As String,
kind As SyntaxKind) As PunctuationSyntax
Dim followingTrivia = ScanSingleLineTrivia()
Return MakePunctuationToken(kind, spelling, precedingTrivia, followingTrivia)
End Function
Private Function MakePunctuationToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
length As Integer,
kind As SyntaxKind) As PunctuationSyntax
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Return MakePunctuationToken(kind, spelling, precedingTrivia, followingTrivia)
End Function
Friend Function MakePunctuationToken(kind As SyntaxKind,
spelling As String,
precedingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode),
followingTrivia As CoreInternalSyntax.SyntaxList(Of GreenNode)
) As PunctuationSyntax
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As PunctuationSyntax = Nothing
If _punctTable.TryGetValue(tp, p) Then
Return p
End If
p = New PunctuationSyntax(kind, spelling, precedingTrivia.Node, followingTrivia.Node)
_punctTable.Add(tp, p)
Return p
End Function
Private Function MakeOpenParenToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_LEFT_PARENTHESIS_STRING, "(")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.OpenParenToken)
End Function
Private Function MakeCloseParenToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_RIGHT_PARENTHESIS_STRING, ")")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CloseParenToken)
End Function
Private Function MakeDotToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_FULL_STOP_STRING, ".")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.DotToken)
End Function
Private Function MakeCommaToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_COMMA_STRING, ",")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CommaToken)
End Function
Private Function MakeEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_EQUALS_SIGN_STRING, "=")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.EqualsToken)
End Function
Private Function MakeHashToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_NUMBER_SIGN_STRING, "#")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.HashToken)
End Function
Private Function MakeAmpersandToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_AMPERSAND_STRING, "&")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.AmpersandToken)
End Function
Private Function MakeOpenBraceToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_LEFT_CURLY_BRACKET_STRING, "{")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.OpenBraceToken)
End Function
Private Function MakeCloseBraceToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_RIGHT_CURLY_BRACKET_STRING, "}")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CloseBraceToken)
End Function
Private Function MakeColonToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Debug.Assert(Peek() = If(charIsFullWidth, FULLWIDTH_COLON, ":"c))
Debug.Assert(Not precedingTrivia.Any())
Dim width = _endOfTerminatorTrivia - _lineBufferOffset
Debug.Assert(width = 1)
AdvanceChar(width)
' Colon does not consume trailing trivia
Return SyntaxFactory.ColonToken
End Function
Private Function MakeEmptyToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, "", SyntaxKind.EmptyToken)
End Function
Private Function MakePlusToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_PLUS_SIGN_STRING, "+")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.PlusToken)
End Function
Private Function MakeMinusToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_HYPHEN_MINUS_STRING, "-")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.MinusToken)
End Function
Private Function MakeAsteriskToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_ASTERISK_STRING, "*")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.AsteriskToken)
End Function
Private Function MakeSlashToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_SOLIDUS_STRING, "/")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.SlashToken)
End Function
Private Function MakeBackslashToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_REVERSE_SOLIDUS_STRING, "\")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.BackslashToken)
End Function
Private Function MakeCaretToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_CIRCUMFLEX_ACCENT_STRING, "^")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.CaretToken)
End Function
Private Function MakeExclamationToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_EXCLAMATION_MARK_STRING, "!")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.ExclamationToken)
End Function
Private Function MakeQuestionToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_QUESTION_MARK_STRING, "?")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.QuestionToken)
End Function
Private Function MakeGreaterThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_GREATER_THAN_SIGN_STRING, ">")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.GreaterThanToken)
End Function
Private Function MakeLessThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_LESS_THAN_SIGN_STRING, "<")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.LessThanToken)
End Function
' ==== TOKENS WITH NOT FIXED SPELLING
Private Function MakeStatementTerminatorToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), width As Integer) As PunctuationSyntax
Debug.Assert(_endOfTerminatorTrivia = _lineBufferOffset + width)
Debug.Assert(width = 1 OrElse width = 2)
Debug.Assert(Not precedingTrivia.Any())
AdvanceChar(width)
' Statement terminator does not consume trailing trivia
Return SyntaxFactory.StatementTerminatorToken
End Function
Private Function MakeAmpersandEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.AmpersandEqualsToken)
End Function
Private Function MakeColonEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.ColonEqualsToken)
End Function
Private Function MakePlusEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.PlusEqualsToken)
End Function
Private Function MakeMinusEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.MinusEqualsToken)
End Function
Private Function MakeAsteriskEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.AsteriskEqualsToken)
End Function
Private Function MakeSlashEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.SlashEqualsToken)
End Function
Private Function MakeBackSlashEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.BackslashEqualsToken)
End Function
Private Function MakeCaretEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.CaretEqualsToken)
End Function
Private Function MakeGreaterThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.GreaterThanEqualsToken)
End Function
Private Function MakeLessThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanEqualsToken)
End Function
Private Function MakeLessThanGreaterThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanGreaterThanToken)
End Function
Private Function MakeLessThanLessThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanLessThanToken)
End Function
Private Function MakeGreaterThanGreaterThanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.GreaterThanGreaterThanToken)
End Function
Private Function MakeLessThanLessThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.LessThanLessThanEqualsToken)
End Function
Private Function MakeGreaterThanGreaterThanEqualsToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer) As PunctuationSyntax
Return MakePunctuationToken(precedingTrivia, length, SyntaxKind.GreaterThanGreaterThanEqualsToken)
End Function
Private Function MakeAtToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As PunctuationSyntax
Dim spelling = If(charIsFullWidth, FULLWIDTH_COMMERCIAL_AT_STRING, "@")
AdvanceChar()
Return MakePunctuationToken(precedingTrivia, spelling, SyntaxKind.AtToken)
End Function
#End Region
#Region "Literals"
Private Function MakeIntegerLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
base As LiteralBase,
typeCharacter As TypeCharacter,
integralValue As ULong,
length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.IntegerLiteralToken(
spelling,
base,
typeCharacter,
integralValue,
precedingTrivia.Node,
followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeCharacterLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), value As Char, length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.CharacterLiteralToken(spelling, value, precedingTrivia.Node, followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeDateLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), value As DateTime, length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.DateLiteralToken(spelling, value, precedingTrivia.Node, followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeFloatingLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
typeCharacter As TypeCharacter,
floatingValue As Double,
length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.FloatingLiteralToken(
spelling,
typeCharacter,
floatingValue,
precedingTrivia.Node,
followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
Private Function MakeDecimalLiteralToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode),
typeCharacter As TypeCharacter,
decimalValue As Decimal,
length As Integer) As SyntaxToken
Dim spelling = GetText(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim tp As New TokenParts(precedingTrivia, followingTrivia, spelling)
Dim p As SyntaxToken = Nothing
If _literalTable.TryGetValue(tp, p) Then
Return p
End If
p = SyntaxFactory.DecimalLiteralToken(
spelling,
typeCharacter,
decimalValue,
precedingTrivia.Node,
followingTrivia.Node)
_literalTable.Add(tp, p)
Return p
End Function
#End Region
' BAD TOKEN
Private Function MakeBadToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), length As Integer, errId As ERRID) As SyntaxToken
Dim spelling = GetTextNotInterned(length)
Dim followingTrivia = ScanSingleLineTrivia()
Dim result1 = SyntaxFactory.BadToken(SyntaxSubKind.None, spelling, precedingTrivia.Node, followingTrivia.Node)
Dim errResult1 = result1.AddError(ErrorFactory.ErrorInfo(errId))
Return DirectCast(errResult1, SyntaxToken)
End Function
Private Shared Function MakeEofToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken
Return SyntaxFactory.Token(precedingTrivia.Node, SyntaxKind.EndOfFileToken, Nothing, String.Empty)
End Function
Private ReadOnly _simpleEof As SyntaxToken = SyntaxFactory.Token(Nothing, SyntaxKind.EndOfFileToken, Nothing, String.Empty)
Private Function MakeEofToken() As SyntaxToken
Return _simpleEof
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Tools/ExternalAccess/FSharp/Editor/Shared/Utilities/FSharpClassificationTypeMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Shared.Utilities
{
[Export]
internal class FSharpClassificationTypeMap
{
private readonly Dictionary<string, IClassificationType> _identityMap;
private readonly IClassificationTypeRegistryService _registryService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpClassificationTypeMap(IClassificationTypeRegistryService registryService)
{
_registryService = registryService;
// Prepopulate the identity map with the constant string values from ClassificationTypeNames
var fields = typeof(ClassificationTypeNames).GetFields();
_identityMap = new Dictionary<string, IClassificationType>(fields.Length, ReferenceEqualityComparer.Instance);
foreach (var field in fields)
{
// The strings returned from reflection do not have reference-identity
// with the string constants used by the compiler. Fortunately, a call
// to string.Intern fixes them.
var value = string.Intern((string)field.GetValue(null));
_identityMap.Add(value, registryService.GetClassificationType(value));
}
}
public IClassificationType GetClassificationType(string name)
{
var type = GetClassificationTypeWorker(name);
if (type == null)
{
FatalError.ReportAndCatch(new Exception($"classification type doesn't exist for {name}"));
}
return type ?? GetClassificationTypeWorker(ClassificationTypeNames.Text);
}
private IClassificationType GetClassificationTypeWorker(string name)
{
return _identityMap.TryGetValue(name, out var result)
? result
: _registryService.GetClassificationType(name);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Shared.Utilities
{
[Export]
internal class FSharpClassificationTypeMap
{
private readonly Dictionary<string, IClassificationType> _identityMap;
private readonly IClassificationTypeRegistryService _registryService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpClassificationTypeMap(IClassificationTypeRegistryService registryService)
{
_registryService = registryService;
// Prepopulate the identity map with the constant string values from ClassificationTypeNames
var fields = typeof(ClassificationTypeNames).GetFields();
_identityMap = new Dictionary<string, IClassificationType>(fields.Length, ReferenceEqualityComparer.Instance);
foreach (var field in fields)
{
// The strings returned from reflection do not have reference-identity
// with the string constants used by the compiler. Fortunately, a call
// to string.Intern fixes them.
var value = string.Intern((string)field.GetValue(null));
_identityMap.Add(value, registryService.GetClassificationType(value));
}
}
public IClassificationType GetClassificationType(string name)
{
var type = GetClassificationTypeWorker(name);
if (type == null)
{
FatalError.ReportAndCatch(new Exception($"classification type doesn't exist for {name}"));
}
return type ?? GetClassificationTypeWorker(ClassificationTypeNames.Text);
}
private IClassificationType GetClassificationTypeWorker(string name)
{
return _identityMap.TryGetValue(name, out var result)
? result
: _registryService.GetClassificationType(name);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/CSharp/Test/Emit/CodeGen/IndexerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class IndexerTests : CSharpTestBase
{
#region Declarations
[Fact]
public void ReadWriteIndexer()
{
var text = @"
class C
{
public int this[int x] { get { return x; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void ReadOnlyIndexer()
{
var text = @"
class C
{
public int this[int x, int y] { get { return x; } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x, System.Int32 y].get", null),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readonly instance System.Int32 Item(System.Int32 x, System.Int32 y)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item(System.Int32 x, System.Int32 y) cil managed")
});
}
[Fact]
public void WriteOnlyIndexer()
{
var text = @"
class C
{
public int this[int x, int y, int z] { set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, null, "void C.this[System.Int32 x, System.Int32 y, System.Int32 z].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property writeonly instance System.Int32 Item(System.Int32 x, System.Int32 y, System.Int32 z)"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item(System.Int32 x, System.Int32 y, System.Int32 z, System.Int32 value) cil managed")
});
}
[Fact]
public void GenericIndexer()
{
var text = @"
class C<T>
{
public T this[T x] { get { return x; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "T C<T>.this[T x].get", "void C<T>.this[T x].set"),
expectedSignatures: new[]
{
Signature("C`1", "Item", ".property readwrite instance T Item(T x)"),
Signature("C`1", "get_Item", ".method public hidebysig specialname instance T get_Item(T x) cil managed"),
Signature("C`1", "set_Item", ".method public hidebysig specialname instance System.Void set_Item(T x, T value) cil managed")
});
}
[Fact]
public void IndexerWithOptionalParameters()
{
var text = @"
class C
{
public int this[int x = 1, int y = 2] { get { return x; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[[System.Int32 x = 1], [System.Int32 y = 2]].get", "void C.this[[System.Int32 x = 1], [System.Int32 y = 2]].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item([opt] System.Int32 x = 1, [opt] System.Int32 y = 2)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item([opt] System.Int32 x = 1, [opt] System.Int32 y = 2) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item([opt] System.Int32 x = 1, [opt] System.Int32 y = 2, System.Int32 value) cil managed")
});
}
[Fact]
public void IndexerWithParameterArray()
{
var text = @"
class C
{
public int this[params int[] x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[params System.Int32[] x].get", "void C.this[params System.Int32[] x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item([System.ParamArrayAttribute()] System.Int32[] x)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item([System.ParamArrayAttribute()] System.Int32[] x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item([System.ParamArrayAttribute()] System.Int32[] x, System.Int32 value) cil managed")
});
}
[Fact]
public void ExplicitInterfaceImplementation()
{
var text = @"
interface I
{
int this[int x] { get; set; }
}
class C : I
{
int I.this[int x] { get { return 0; } set { } }
}
";
System.Action<ModuleSymbol> validator = module =>
{
// Can't use ValidateIndexer because explicit implementations aren't indexers in metadata.
var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var indexer = @class.GetMembers().Where(member => member.Kind == SymbolKind.Property).Cast<PropertySymbol>().Single();
Assert.False(indexer.IsIndexer);
Assert.True(indexer.MustCallMethodsDirectly); //since has parameters, but isn't an indexer
Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility);
Assert.False(indexer.IsStatic);
var getMethod = indexer.GetMethod;
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, getMethod.MethodKind); //since CallMethodsDirectly
Assert.Equal("System.Int32 C.I.get_Item(System.Int32 x)", getMethod.ToTestDisplayString());
getMethod.CheckAccessorModifiers(indexer);
var setMethod = indexer.SetMethod;
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, setMethod.MethodKind); //since CallMethodsDirectly
Assert.Equal("void C.I.set_Item(System.Int32 x, System.Int32 value)", setMethod.ToTestDisplayString());
setMethod.CheckAccessorModifiers(indexer);
};
var compVerifier = CompileAndVerify(text, symbolValidator: validator, expectedSignatures: new[]
{
Signature("C", "I.Item", ".property readwrite System.Int32 I.Item(System.Int32 x)"),
Signature("C", "I.get_Item", ".method private hidebysig newslot specialname virtual final instance System.Int32 I.get_Item(System.Int32 x) cil managed"),
Signature("C", "I.set_Item", ".method private hidebysig newslot specialname virtual final instance System.Void I.set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void ImplicitInterfaceImplementation()
{
var text = @"
interface I
{
int this[int x] { get; set; }
}
class C : I
{
public int this[int x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig newslot specialname virtual final instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig newslot specialname virtual final instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void Overriding()
{
var text = @"
class B
{
public virtual int this[int x] { get { return 0; } set { } }
}
class C : B
{
public override sealed int this[int x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig specialname virtual final instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname virtual final instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void Hiding()
{
var text = @"
class B
{
public virtual int this[int x] { get { return 0; } set { } }
}
class C : B
{
public new virtual int this[int x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig newslot specialname virtual instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig newslot specialname virtual instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
// NOTE: assumes there's a single indexer (type = int) in a type C.
private static void ValidateIndexer(ModuleSymbol module, string getterDisplayString, string setterDisplayString)
{
var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var indexer = @class.Indexers.Single();
Assert.Equal(SymbolKind.Property, indexer.Kind);
Assert.True(indexer.IsIndexer);
Assert.False(indexer.MustCallMethodsDirectly);
Assert.Equal(Accessibility.Public, indexer.DeclaredAccessibility);
Assert.False(indexer.IsStatic);
var getMethod = indexer.GetMethod;
if (getterDisplayString == null)
{
Assert.Null(getMethod);
}
else
{
Assert.Equal(MethodKind.PropertyGet, getMethod.MethodKind);
Assert.Equal(getterDisplayString, getMethod.ToTestDisplayString());
getMethod.CheckAccessorShape(indexer);
}
var setMethod = indexer.SetMethod;
if (setterDisplayString == null)
{
Assert.Null(setMethod);
}
else
{
Assert.Equal(MethodKind.PropertySet, setMethod.MethodKind);
Assert.Equal(setterDisplayString, setMethod.ToTestDisplayString());
setMethod.CheckAccessorShape(indexer);
}
}
#endregion Declarations
#region Lowering
private const string TypeWithIndexers = @"
public class C
{
public static int Goo(int x)
{
System.Console.Write(x + "","");
return x * 10;
}
public int this[int x, int y = 9]
{
get
{
System.Console.Write(x + "","");
System.Console.Write(y + "","");
return -(x + y);
}
set
{
System.Console.Write(x + "","");
System.Console.Write(y + "","");
System.Console.Write(value + "","");
}
}
public int this[params int[] x]
{
get
{
foreach (var i in x) System.Console.Write(i + "","");
return -(x.Length);
}
set
{
foreach (var i in x) System.Console.Write(i + "","");
System.Console.Write(value + "","");
}
}
}
";
[Fact]
public void LoweringRead()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
int x;
//// Normal
x = c[C.Goo(1), C.Goo(2)];
System.Console.WriteLine();
//// Named parameters
x = c[C.Goo(1), y: C.Goo(2)]; //NB: Dev10 gets this wrong (2,1,10,20)
System.Console.WriteLine();
x = c[x: C.Goo(1), y: C.Goo(2)];
System.Console.WriteLine();
x = c[y: C.Goo(2), x: C.Goo(1)];
System.Console.WriteLine();
//// Optional parameters
x = c[C.Goo(1)];
System.Console.WriteLine();
x = c[x: C.Goo(1)];
System.Console.WriteLine();
//// Parameter arrays
x = c[C.Goo(1), C.Goo(2), C.Goo(3)];
System.Console.WriteLine();
x = c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }];
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
1,2,10,20,
1,2,10,20,
1,2,10,20,
2,1,10,20,
1,10,9,
1,10,9,
1,2,3,10,20,30,
1,2,3,10,20,30,
");
}
[Fact]
public void LoweringReadIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
int x;
//// Normal
x = c[1, 2];
//// Named parameters
x = c[1, y: 2];
x = c[x: 1, y: 2];
x = c[y: 2, x: 1];
//// Optional parameters
x = c[1];
x = c[x: 1];
//// Parameter arrays
x = c[1, 2, 3];
x = c[new int[] { 1, 2, 3 }];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 111 (0x6f)
.maxstack 4
.locals init (C V_0) //c
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: ldc.i4.2
IL_0009: callvirt ""int C.this[int, int].get""
IL_000e: pop
IL_000f: ldloc.0
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: callvirt ""int C.this[int, int].get""
IL_0017: pop
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: ldc.i4.2
IL_001b: callvirt ""int C.this[int, int].get""
IL_0020: pop
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: callvirt ""int C.this[int, int].get""
IL_0029: pop
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: ldc.i4.s 9
IL_002e: callvirt ""int C.this[int, int].get""
IL_0033: pop
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldc.i4.s 9
IL_0038: callvirt ""int C.this[int, int].get""
IL_003d: pop
IL_003e: ldloc.0
IL_003f: ldc.i4.3
IL_0040: newarr ""int""
IL_0045: dup
IL_0046: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_004b: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0050: callvirt ""int C.this[params int[]].get""
IL_0055: pop
IL_0056: ldloc.0
IL_0057: ldc.i4.3
IL_0058: newarr ""int""
IL_005d: dup
IL_005e: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_0063: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0068: callvirt ""int C.this[params int[]].get""
IL_006d: pop
IL_006e: ret
}
");
}
[Fact]
public void LoweringAssignment()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[C.Goo(1), C.Goo(2)] = C.Goo(3);
System.Console.WriteLine();
//// Named parameters
c[C.Goo(1), y: C.Goo(2)] = C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1), y: C.Goo(2)] = C.Goo(3); //NB: dev10 gets this wrong (2,1,3,10,20,30,)
System.Console.WriteLine();
c[y: C.Goo(2), x: C.Goo(1)] = C.Goo(3);
System.Console.WriteLine();
//// Optional parameters
c[C.Goo(1)] = C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1)] = C.Goo(3);
System.Console.WriteLine();
//// Parameter arrays
c[C.Goo(1), C.Goo(2), C.Goo(3)] = C.Goo(4);
System.Console.WriteLine();
c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }] = C.Goo(4);
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
1,2,3,10,20,30,
1,2,3,10,20,30,
1,2,3,10,20,30,
2,1,3,10,20,30,
1,3,10,9,30,
1,3,10,9,30,
1,2,3,4,10,20,30,40,
1,2,3,4,10,20,30,40,
");
}
[Fact]
public void LoweringAssignmentIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[1, 2] = 3;
//// Named parameters
c[1, y: 2] = 3;
c[x: 1, y: 2] = 3;
c[y: 2, x: 1] = 3;
//// Optional parameters
c[1] = 3;
c[x: 1] = 3;
//// Parameter arrays
c[1, 2, 3] = 4;
c[new int[] { 1, 2, 3 }] = 4;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 111 (0x6f)
.maxstack 4
.locals init (C V_0) //c
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: ldc.i4.2
IL_0009: ldc.i4.3
IL_000a: callvirt ""void C.this[int, int].set""
IL_000f: ldloc.0
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: ldc.i4.3
IL_0013: callvirt ""void C.this[int, int].set""
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: ldc.i4.2
IL_001b: ldc.i4.3
IL_001c: callvirt ""void C.this[int, int].set""
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: ldc.i4.3
IL_0025: callvirt ""void C.this[int, int].set""
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: ldc.i4.s 9
IL_002e: ldc.i4.3
IL_002f: callvirt ""void C.this[int, int].set""
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldc.i4.s 9
IL_0038: ldc.i4.3
IL_0039: callvirt ""void C.this[int, int].set""
IL_003e: ldloc.0
IL_003f: ldc.i4.3
IL_0040: newarr ""int""
IL_0045: dup
IL_0046: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_004b: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0050: ldc.i4.4
IL_0051: callvirt ""void C.this[params int[]].set""
IL_0056: ldloc.0
IL_0057: ldc.i4.3
IL_0058: newarr ""int""
IL_005d: dup
IL_005e: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_0063: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0068: ldc.i4.4
IL_0069: callvirt ""void C.this[params int[]].set""
IL_006e: ret
}
");
}
[Fact]
public void LoweringIncrement()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[C.Goo(1), C.Goo(2)]++;
System.Console.WriteLine();
//// Named parameters
c[C.Goo(1), y: C.Goo(2)]++;
System.Console.WriteLine();
c[x: C.Goo(1), y: C.Goo(2)]++; //NB: dev10 gets this wrong (2,1,10,20,10,20,-29,)
System.Console.WriteLine();
c[y: C.Goo(2), x: C.Goo(1)]++;
System.Console.WriteLine();
//// Optional parameters
c[C.Goo(1)]++;
System.Console.WriteLine();
c[x: C.Goo(1)]++;
System.Console.WriteLine();
//// Parameter arrays
c[C.Goo(1), C.Goo(2), C.Goo(3)]++;
System.Console.WriteLine();
c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }]++;
System.Console.WriteLine();
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: @"
1,2,10,20,10,20,-29,
1,2,10,20,10,20,-29,
1,2,10,20,10,20,-29,
2,1,10,20,10,20,-29,
1,10,9,10,9,-18,
1,10,9,10,9,-18,
1,2,3,10,20,30,10,20,30,-2,
1,2,3,10,20,30,10,20,30,-2,
");
}
[Fact]
public void LoweringIncrementIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[1, 2]++;
//// Named parameters
c[1, y: 2]++;
c[x: 1, y: 2]++;
c[y: 2, x: 1]++;
//// Optional parameters
c[1]++;
c[x: 1]++;
//// Parameter arrays
c[1, 2, 3]++;
c[new int[] { 1, 2, 3 }]++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 207 (0xcf)
.maxstack 5
.locals init (C V_0, //c
int V_1,
C V_2,
int[] V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: ldc.i4.2
IL_000a: callvirt ""int C.this[int, int].get""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: ldloc.1
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: callvirt ""void C.this[int, int].set""
IL_001a: ldloc.0
IL_001b: dup
IL_001c: ldc.i4.1
IL_001d: ldc.i4.2
IL_001e: callvirt ""int C.this[int, int].get""
IL_0023: stloc.1
IL_0024: ldc.i4.1
IL_0025: ldc.i4.2
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: callvirt ""void C.this[int, int].set""
IL_002e: ldloc.0
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.2
IL_0032: callvirt ""int C.this[int, int].get""
IL_0037: stloc.1
IL_0038: ldc.i4.1
IL_0039: ldc.i4.2
IL_003a: ldloc.1
IL_003b: ldc.i4.1
IL_003c: add
IL_003d: callvirt ""void C.this[int, int].set""
IL_0042: ldloc.0
IL_0043: dup
IL_0044: ldc.i4.1
IL_0045: ldc.i4.2
IL_0046: callvirt ""int C.this[int, int].get""
IL_004b: stloc.1
IL_004c: ldc.i4.1
IL_004d: ldc.i4.2
IL_004e: ldloc.1
IL_004f: ldc.i4.1
IL_0050: add
IL_0051: callvirt ""void C.this[int, int].set""
IL_0056: ldloc.0
IL_0057: dup
IL_0058: ldc.i4.1
IL_0059: ldc.i4.s 9
IL_005b: callvirt ""int C.this[int, int].get""
IL_0060: stloc.1
IL_0061: ldc.i4.1
IL_0062: ldc.i4.s 9
IL_0064: ldloc.1
IL_0065: ldc.i4.1
IL_0066: add
IL_0067: callvirt ""void C.this[int, int].set""
IL_006c: ldloc.0
IL_006d: dup
IL_006e: ldc.i4.1
IL_006f: ldc.i4.s 9
IL_0071: callvirt ""int C.this[int, int].get""
IL_0076: stloc.1
IL_0077: ldc.i4.1
IL_0078: ldc.i4.s 9
IL_007a: ldloc.1
IL_007b: ldc.i4.1
IL_007c: add
IL_007d: callvirt ""void C.this[int, int].set""
IL_0082: ldloc.0
IL_0083: stloc.2
IL_0084: ldc.i4.3
IL_0085: newarr ""int""
IL_008a: dup
IL_008b: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_0090: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0095: stloc.3
IL_0096: ldloc.2
IL_0097: ldloc.3
IL_0098: callvirt ""int C.this[params int[]].get""
IL_009d: stloc.1
IL_009e: ldloc.2
IL_009f: ldloc.3
IL_00a0: ldloc.1
IL_00a1: ldc.i4.1
IL_00a2: add
IL_00a3: callvirt ""void C.this[params int[]].set""
IL_00a8: ldloc.0
IL_00a9: stloc.2
IL_00aa: ldc.i4.3
IL_00ab: newarr ""int""
IL_00b0: dup
IL_00b1: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_00b6: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_00bb: stloc.3
IL_00bc: ldloc.2
IL_00bd: ldloc.3
IL_00be: callvirt ""int C.this[params int[]].get""
IL_00c3: stloc.1
IL_00c4: ldloc.2
IL_00c5: ldloc.3
IL_00c6: ldloc.1
IL_00c7: ldc.i4.1
IL_00c8: add
IL_00c9: callvirt ""void C.this[params int[]].set""
IL_00ce: ret
}
");
}
[Fact]
public void LoweringCompoundAssignment()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[C.Goo(1), C.Goo(2)] += C.Goo(3);
System.Console.WriteLine();
//// Named parameters
c[C.Goo(1), y: C.Goo(2)] += C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1), y: C.Goo(2)] += C.Goo(3); //NB: dev10 gets this wrong (2,1,10,20,3,10,20,0,)
System.Console.WriteLine();
c[y: C.Goo(2), x: C.Goo(1)] += C.Goo(3);
System.Console.WriteLine();
//// Optional parameters
c[C.Goo(1)] += C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1)] += C.Goo(3);
System.Console.WriteLine();
//// Parameter arrays
c[C.Goo(1), C.Goo(2), C.Goo(3)] += C.Goo(4);
System.Console.WriteLine();
c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }] += C.Goo(4);
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
1,2,10,20,3,10,20,0,
1,2,10,20,3,10,20,0,
1,2,10,20,3,10,20,0,
2,1,10,20,3,10,20,0,
1,10,9,3,10,9,11,
1,10,9,3,10,9,11,
1,2,3,10,20,30,4,10,20,30,37,
1,2,3,10,20,30,4,10,20,30,37,
");
}
[Fact]
public void LoweringCompoundAssignmentIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[1, 2] += 3;
System.Console.WriteLine();
//// Named parameters
c[1, y: 2] += 3;
System.Console.WriteLine();
c[x: 1, y: 2] += 3; //NB: dev10 gets this wrong (2,1,10,20,3,10,20,0,)
System.Console.WriteLine();
c[y: 2, x: 1] += 3;
System.Console.WriteLine();
//// Optional parameters
c[1] += 3;
System.Console.WriteLine();
c[x: 1] += 3;
System.Console.WriteLine();
//// Parameter arrays
c[1, 2, 3] += 4;
System.Console.WriteLine();
c[new int[] { 1, 2, 3 }] += 4;
System.Console.WriteLine();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 243 (0xf3)
.maxstack 6
.locals init (C V_0, //c
C V_1,
int[] V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.1
IL_000a: ldc.i4.2
IL_000b: ldloc.1
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: callvirt ""int C.this[int, int].get""
IL_0013: ldc.i4.3
IL_0014: add
IL_0015: callvirt ""void C.this[int, int].set""
IL_001a: call ""void System.Console.WriteLine()""
IL_001f: ldloc.0
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: ldloc.1
IL_0025: ldc.i4.1
IL_0026: ldc.i4.2
IL_0027: callvirt ""int C.this[int, int].get""
IL_002c: ldc.i4.3
IL_002d: add
IL_002e: callvirt ""void C.this[int, int].set""
IL_0033: call ""void System.Console.WriteLine()""
IL_0038: ldloc.0
IL_0039: stloc.1
IL_003a: ldloc.1
IL_003b: ldc.i4.1
IL_003c: ldc.i4.2
IL_003d: ldloc.1
IL_003e: ldc.i4.1
IL_003f: ldc.i4.2
IL_0040: callvirt ""int C.this[int, int].get""
IL_0045: ldc.i4.3
IL_0046: add
IL_0047: callvirt ""void C.this[int, int].set""
IL_004c: call ""void System.Console.WriteLine()""
IL_0051: ldloc.0
IL_0052: stloc.1
IL_0053: ldloc.1
IL_0054: ldc.i4.1
IL_0055: ldc.i4.2
IL_0056: ldloc.1
IL_0057: ldc.i4.1
IL_0058: ldc.i4.2
IL_0059: callvirt ""int C.this[int, int].get""
IL_005e: ldc.i4.3
IL_005f: add
IL_0060: callvirt ""void C.this[int, int].set""
IL_0065: call ""void System.Console.WriteLine()""
IL_006a: ldloc.0
IL_006b: stloc.1
IL_006c: ldloc.1
IL_006d: ldc.i4.1
IL_006e: ldc.i4.s 9
IL_0070: ldloc.1
IL_0071: ldc.i4.1
IL_0072: ldc.i4.s 9
IL_0074: callvirt ""int C.this[int, int].get""
IL_0079: ldc.i4.3
IL_007a: add
IL_007b: callvirt ""void C.this[int, int].set""
IL_0080: call ""void System.Console.WriteLine()""
IL_0085: ldloc.0
IL_0086: stloc.1
IL_0087: ldloc.1
IL_0088: ldc.i4.1
IL_0089: ldc.i4.s 9
IL_008b: ldloc.1
IL_008c: ldc.i4.1
IL_008d: ldc.i4.s 9
IL_008f: callvirt ""int C.this[int, int].get""
IL_0094: ldc.i4.3
IL_0095: add
IL_0096: callvirt ""void C.this[int, int].set""
IL_009b: call ""void System.Console.WriteLine()""
IL_00a0: ldloc.0
IL_00a1: stloc.1
IL_00a2: ldc.i4.3
IL_00a3: newarr ""int""
IL_00a8: dup
IL_00a9: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_00ae: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_00b3: stloc.2
IL_00b4: ldloc.1
IL_00b5: ldloc.2
IL_00b6: ldloc.1
IL_00b7: ldloc.2
IL_00b8: callvirt ""int C.this[params int[]].get""
IL_00bd: ldc.i4.4
IL_00be: add
IL_00bf: callvirt ""void C.this[params int[]].set""
IL_00c4: call ""void System.Console.WriteLine()""
IL_00c9: ldloc.0
IL_00ca: stloc.1
IL_00cb: ldc.i4.3
IL_00cc: newarr ""int""
IL_00d1: dup
IL_00d2: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_00d7: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_00dc: stloc.2
IL_00dd: ldloc.1
IL_00de: ldloc.2
IL_00df: ldloc.1
IL_00e0: ldloc.2
IL_00e1: callvirt ""int C.this[params int[]].get""
IL_00e6: ldc.i4.4
IL_00e7: add
IL_00e8: callvirt ""void C.this[params int[]].set""
IL_00ed: call ""void System.Console.WriteLine()""
IL_00f2: ret
}
");
}
[Fact]
public void LoweringComplex()
{
var text = TypeWithIndexers + @"
class Test
{
static C NewC()
{
System.Console.Write(""N,"");
return new C();
}
static void Main()
{
NewC()[y: C.Goo(1), x: NewC()[C.Goo(2)]] = NewC()[x: C.Goo(3), y: NewC()[C.Goo(4)]] += NewC()[C.Goo(5), C.Goo(6), NewC()[C.Goo(7)]]++;
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
N,1,N,2,20,9,N,3,N,4,40,9,30,-49,N,5,6,N,7,70,9,50,60,-79,50,60,-79,-2,30,-49,16,-29,10,16,
");
}
[Fact]
public void BoxingParameterArrayArguments()
{
var text = TypeWithIndexers + @"
class Test
{
int this[params object[] args] { get { return args.Length; } }
static void Main()
{
System.Console.WriteLine(new Test()[1, 2]);
}
}
";
var verifier = CompileAndVerify(text, expectedOutput: @"2");
verifier.VerifyIL("Test.Main", @"
{
// Code size 40 (0x28)
.maxstack 5
IL_0000: newobj ""Test..ctor()""
IL_0005: ldc.i4.2
IL_0006: newarr ""object""
IL_000b: dup
IL_000c: ldc.i4.0
IL_000d: ldc.i4.1
IL_000e: box ""int""
IL_0013: stelem.ref
IL_0014: dup
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: box ""int""
IL_001c: stelem.ref
IL_001d: call ""int Test.this[params object[]].get""
IL_0022: call ""void System.Console.WriteLine(int)""
IL_0027: ret
}
");
}
[Fact]
public void IndexerOverrideNotAllAccessors_DefaultParameterValues()
{
var text = @"
using System;
class Base
{
public virtual int this[int x, int y = 1]
{
get
{
Console.WriteLine(""Base.get y: "" + y);
return y;
}
set { Console.WriteLine(""Base.set y: "" + y); }
}
}
class Override : Base
{
public override int this[int x, int y = 2]
{
set { Console.WriteLine(""Override.set y: "" + y); }
}
}
class Program
{
static void Main()
{
Base b = new Base();
_ = b[0];
b[0] = 0;
Override o = new Override();
_ = o[0];
o[0] = 0;
o[0] += 0;
}
}
";
CompileAndVerify(text, expectedOutput:
@"Base.get y: 1
Base.set y: 1
Base.get y: 1
Override.set y: 2
Base.get y: 1
Override.set y: 1
");
}
#endregion Lowering
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class IndexerTests : CSharpTestBase
{
#region Declarations
[Fact]
public void ReadWriteIndexer()
{
var text = @"
class C
{
public int this[int x] { get { return x; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void ReadOnlyIndexer()
{
var text = @"
class C
{
public int this[int x, int y] { get { return x; } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x, System.Int32 y].get", null),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readonly instance System.Int32 Item(System.Int32 x, System.Int32 y)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item(System.Int32 x, System.Int32 y) cil managed")
});
}
[Fact]
public void WriteOnlyIndexer()
{
var text = @"
class C
{
public int this[int x, int y, int z] { set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, null, "void C.this[System.Int32 x, System.Int32 y, System.Int32 z].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property writeonly instance System.Int32 Item(System.Int32 x, System.Int32 y, System.Int32 z)"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item(System.Int32 x, System.Int32 y, System.Int32 z, System.Int32 value) cil managed")
});
}
[Fact]
public void GenericIndexer()
{
var text = @"
class C<T>
{
public T this[T x] { get { return x; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "T C<T>.this[T x].get", "void C<T>.this[T x].set"),
expectedSignatures: new[]
{
Signature("C`1", "Item", ".property readwrite instance T Item(T x)"),
Signature("C`1", "get_Item", ".method public hidebysig specialname instance T get_Item(T x) cil managed"),
Signature("C`1", "set_Item", ".method public hidebysig specialname instance System.Void set_Item(T x, T value) cil managed")
});
}
[Fact]
public void IndexerWithOptionalParameters()
{
var text = @"
class C
{
public int this[int x = 1, int y = 2] { get { return x; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[[System.Int32 x = 1], [System.Int32 y = 2]].get", "void C.this[[System.Int32 x = 1], [System.Int32 y = 2]].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item([opt] System.Int32 x = 1, [opt] System.Int32 y = 2)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item([opt] System.Int32 x = 1, [opt] System.Int32 y = 2) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item([opt] System.Int32 x = 1, [opt] System.Int32 y = 2, System.Int32 value) cil managed")
});
}
[Fact]
public void IndexerWithParameterArray()
{
var text = @"
class C
{
public int this[params int[] x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[params System.Int32[] x].get", "void C.this[params System.Int32[] x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item([System.ParamArrayAttribute()] System.Int32[] x)"),
Signature("C", "get_Item", ".method public hidebysig specialname instance System.Int32 get_Item([System.ParamArrayAttribute()] System.Int32[] x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname instance System.Void set_Item([System.ParamArrayAttribute()] System.Int32[] x, System.Int32 value) cil managed")
});
}
[Fact]
public void ExplicitInterfaceImplementation()
{
var text = @"
interface I
{
int this[int x] { get; set; }
}
class C : I
{
int I.this[int x] { get { return 0; } set { } }
}
";
System.Action<ModuleSymbol> validator = module =>
{
// Can't use ValidateIndexer because explicit implementations aren't indexers in metadata.
var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var indexer = @class.GetMembers().Where(member => member.Kind == SymbolKind.Property).Cast<PropertySymbol>().Single();
Assert.False(indexer.IsIndexer);
Assert.True(indexer.MustCallMethodsDirectly); //since has parameters, but isn't an indexer
Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility);
Assert.False(indexer.IsStatic);
var getMethod = indexer.GetMethod;
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, getMethod.MethodKind); //since CallMethodsDirectly
Assert.Equal("System.Int32 C.I.get_Item(System.Int32 x)", getMethod.ToTestDisplayString());
getMethod.CheckAccessorModifiers(indexer);
var setMethod = indexer.SetMethod;
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, setMethod.MethodKind); //since CallMethodsDirectly
Assert.Equal("void C.I.set_Item(System.Int32 x, System.Int32 value)", setMethod.ToTestDisplayString());
setMethod.CheckAccessorModifiers(indexer);
};
var compVerifier = CompileAndVerify(text, symbolValidator: validator, expectedSignatures: new[]
{
Signature("C", "I.Item", ".property readwrite System.Int32 I.Item(System.Int32 x)"),
Signature("C", "I.get_Item", ".method private hidebysig newslot specialname virtual final instance System.Int32 I.get_Item(System.Int32 x) cil managed"),
Signature("C", "I.set_Item", ".method private hidebysig newslot specialname virtual final instance System.Void I.set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void ImplicitInterfaceImplementation()
{
var text = @"
interface I
{
int this[int x] { get; set; }
}
class C : I
{
public int this[int x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig newslot specialname virtual final instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig newslot specialname virtual final instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void Overriding()
{
var text = @"
class B
{
public virtual int this[int x] { get { return 0; } set { } }
}
class C : B
{
public override sealed int this[int x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig specialname virtual final instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig specialname virtual final instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
[Fact]
public void Hiding()
{
var text = @"
class B
{
public virtual int this[int x] { get { return 0; } set { } }
}
class C : B
{
public new virtual int this[int x] { get { return 0; } set { } }
}
";
var compVerifier = CompileAndVerify(text,
symbolValidator: module => ValidateIndexer(module, "System.Int32 C.this[System.Int32 x].get", "void C.this[System.Int32 x].set"),
expectedSignatures: new[]
{
Signature("C", "Item", ".property readwrite instance System.Int32 Item(System.Int32 x)"),
Signature("C", "get_Item", ".method public hidebysig newslot specialname virtual instance System.Int32 get_Item(System.Int32 x) cil managed"),
Signature("C", "set_Item", ".method public hidebysig newslot specialname virtual instance System.Void set_Item(System.Int32 x, System.Int32 value) cil managed")
});
}
// NOTE: assumes there's a single indexer (type = int) in a type C.
private static void ValidateIndexer(ModuleSymbol module, string getterDisplayString, string setterDisplayString)
{
var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var indexer = @class.Indexers.Single();
Assert.Equal(SymbolKind.Property, indexer.Kind);
Assert.True(indexer.IsIndexer);
Assert.False(indexer.MustCallMethodsDirectly);
Assert.Equal(Accessibility.Public, indexer.DeclaredAccessibility);
Assert.False(indexer.IsStatic);
var getMethod = indexer.GetMethod;
if (getterDisplayString == null)
{
Assert.Null(getMethod);
}
else
{
Assert.Equal(MethodKind.PropertyGet, getMethod.MethodKind);
Assert.Equal(getterDisplayString, getMethod.ToTestDisplayString());
getMethod.CheckAccessorShape(indexer);
}
var setMethod = indexer.SetMethod;
if (setterDisplayString == null)
{
Assert.Null(setMethod);
}
else
{
Assert.Equal(MethodKind.PropertySet, setMethod.MethodKind);
Assert.Equal(setterDisplayString, setMethod.ToTestDisplayString());
setMethod.CheckAccessorShape(indexer);
}
}
#endregion Declarations
#region Lowering
private const string TypeWithIndexers = @"
public class C
{
public static int Goo(int x)
{
System.Console.Write(x + "","");
return x * 10;
}
public int this[int x, int y = 9]
{
get
{
System.Console.Write(x + "","");
System.Console.Write(y + "","");
return -(x + y);
}
set
{
System.Console.Write(x + "","");
System.Console.Write(y + "","");
System.Console.Write(value + "","");
}
}
public int this[params int[] x]
{
get
{
foreach (var i in x) System.Console.Write(i + "","");
return -(x.Length);
}
set
{
foreach (var i in x) System.Console.Write(i + "","");
System.Console.Write(value + "","");
}
}
}
";
[Fact]
public void LoweringRead()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
int x;
//// Normal
x = c[C.Goo(1), C.Goo(2)];
System.Console.WriteLine();
//// Named parameters
x = c[C.Goo(1), y: C.Goo(2)]; //NB: Dev10 gets this wrong (2,1,10,20)
System.Console.WriteLine();
x = c[x: C.Goo(1), y: C.Goo(2)];
System.Console.WriteLine();
x = c[y: C.Goo(2), x: C.Goo(1)];
System.Console.WriteLine();
//// Optional parameters
x = c[C.Goo(1)];
System.Console.WriteLine();
x = c[x: C.Goo(1)];
System.Console.WriteLine();
//// Parameter arrays
x = c[C.Goo(1), C.Goo(2), C.Goo(3)];
System.Console.WriteLine();
x = c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }];
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
1,2,10,20,
1,2,10,20,
1,2,10,20,
2,1,10,20,
1,10,9,
1,10,9,
1,2,3,10,20,30,
1,2,3,10,20,30,
");
}
[Fact]
public void LoweringReadIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
int x;
//// Normal
x = c[1, 2];
//// Named parameters
x = c[1, y: 2];
x = c[x: 1, y: 2];
x = c[y: 2, x: 1];
//// Optional parameters
x = c[1];
x = c[x: 1];
//// Parameter arrays
x = c[1, 2, 3];
x = c[new int[] { 1, 2, 3 }];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 111 (0x6f)
.maxstack 4
.locals init (C V_0) //c
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: ldc.i4.2
IL_0009: callvirt ""int C.this[int, int].get""
IL_000e: pop
IL_000f: ldloc.0
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: callvirt ""int C.this[int, int].get""
IL_0017: pop
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: ldc.i4.2
IL_001b: callvirt ""int C.this[int, int].get""
IL_0020: pop
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: callvirt ""int C.this[int, int].get""
IL_0029: pop
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: ldc.i4.s 9
IL_002e: callvirt ""int C.this[int, int].get""
IL_0033: pop
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldc.i4.s 9
IL_0038: callvirt ""int C.this[int, int].get""
IL_003d: pop
IL_003e: ldloc.0
IL_003f: ldc.i4.3
IL_0040: newarr ""int""
IL_0045: dup
IL_0046: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_004b: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0050: callvirt ""int C.this[params int[]].get""
IL_0055: pop
IL_0056: ldloc.0
IL_0057: ldc.i4.3
IL_0058: newarr ""int""
IL_005d: dup
IL_005e: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_0063: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0068: callvirt ""int C.this[params int[]].get""
IL_006d: pop
IL_006e: ret
}
");
}
[Fact]
public void LoweringAssignment()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[C.Goo(1), C.Goo(2)] = C.Goo(3);
System.Console.WriteLine();
//// Named parameters
c[C.Goo(1), y: C.Goo(2)] = C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1), y: C.Goo(2)] = C.Goo(3); //NB: dev10 gets this wrong (2,1,3,10,20,30,)
System.Console.WriteLine();
c[y: C.Goo(2), x: C.Goo(1)] = C.Goo(3);
System.Console.WriteLine();
//// Optional parameters
c[C.Goo(1)] = C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1)] = C.Goo(3);
System.Console.WriteLine();
//// Parameter arrays
c[C.Goo(1), C.Goo(2), C.Goo(3)] = C.Goo(4);
System.Console.WriteLine();
c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }] = C.Goo(4);
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
1,2,3,10,20,30,
1,2,3,10,20,30,
1,2,3,10,20,30,
2,1,3,10,20,30,
1,3,10,9,30,
1,3,10,9,30,
1,2,3,4,10,20,30,40,
1,2,3,4,10,20,30,40,
");
}
[Fact]
public void LoweringAssignmentIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[1, 2] = 3;
//// Named parameters
c[1, y: 2] = 3;
c[x: 1, y: 2] = 3;
c[y: 2, x: 1] = 3;
//// Optional parameters
c[1] = 3;
c[x: 1] = 3;
//// Parameter arrays
c[1, 2, 3] = 4;
c[new int[] { 1, 2, 3 }] = 4;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 111 (0x6f)
.maxstack 4
.locals init (C V_0) //c
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.1
IL_0008: ldc.i4.2
IL_0009: ldc.i4.3
IL_000a: callvirt ""void C.this[int, int].set""
IL_000f: ldloc.0
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: ldc.i4.3
IL_0013: callvirt ""void C.this[int, int].set""
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: ldc.i4.2
IL_001b: ldc.i4.3
IL_001c: callvirt ""void C.this[int, int].set""
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: ldc.i4.3
IL_0025: callvirt ""void C.this[int, int].set""
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: ldc.i4.s 9
IL_002e: ldc.i4.3
IL_002f: callvirt ""void C.this[int, int].set""
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldc.i4.s 9
IL_0038: ldc.i4.3
IL_0039: callvirt ""void C.this[int, int].set""
IL_003e: ldloc.0
IL_003f: ldc.i4.3
IL_0040: newarr ""int""
IL_0045: dup
IL_0046: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_004b: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0050: ldc.i4.4
IL_0051: callvirt ""void C.this[params int[]].set""
IL_0056: ldloc.0
IL_0057: ldc.i4.3
IL_0058: newarr ""int""
IL_005d: dup
IL_005e: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_0063: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0068: ldc.i4.4
IL_0069: callvirt ""void C.this[params int[]].set""
IL_006e: ret
}
");
}
[Fact]
public void LoweringIncrement()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[C.Goo(1), C.Goo(2)]++;
System.Console.WriteLine();
//// Named parameters
c[C.Goo(1), y: C.Goo(2)]++;
System.Console.WriteLine();
c[x: C.Goo(1), y: C.Goo(2)]++; //NB: dev10 gets this wrong (2,1,10,20,10,20,-29,)
System.Console.WriteLine();
c[y: C.Goo(2), x: C.Goo(1)]++;
System.Console.WriteLine();
//// Optional parameters
c[C.Goo(1)]++;
System.Console.WriteLine();
c[x: C.Goo(1)]++;
System.Console.WriteLine();
//// Parameter arrays
c[C.Goo(1), C.Goo(2), C.Goo(3)]++;
System.Console.WriteLine();
c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }]++;
System.Console.WriteLine();
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: @"
1,2,10,20,10,20,-29,
1,2,10,20,10,20,-29,
1,2,10,20,10,20,-29,
2,1,10,20,10,20,-29,
1,10,9,10,9,-18,
1,10,9,10,9,-18,
1,2,3,10,20,30,10,20,30,-2,
1,2,3,10,20,30,10,20,30,-2,
");
}
[Fact]
public void LoweringIncrementIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[1, 2]++;
//// Named parameters
c[1, y: 2]++;
c[x: 1, y: 2]++;
c[y: 2, x: 1]++;
//// Optional parameters
c[1]++;
c[x: 1]++;
//// Parameter arrays
c[1, 2, 3]++;
c[new int[] { 1, 2, 3 }]++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 207 (0xcf)
.maxstack 5
.locals init (C V_0, //c
int V_1,
C V_2,
int[] V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: ldc.i4.2
IL_000a: callvirt ""int C.this[int, int].get""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: ldc.i4.2
IL_0012: ldloc.1
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: callvirt ""void C.this[int, int].set""
IL_001a: ldloc.0
IL_001b: dup
IL_001c: ldc.i4.1
IL_001d: ldc.i4.2
IL_001e: callvirt ""int C.this[int, int].get""
IL_0023: stloc.1
IL_0024: ldc.i4.1
IL_0025: ldc.i4.2
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: callvirt ""void C.this[int, int].set""
IL_002e: ldloc.0
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.2
IL_0032: callvirt ""int C.this[int, int].get""
IL_0037: stloc.1
IL_0038: ldc.i4.1
IL_0039: ldc.i4.2
IL_003a: ldloc.1
IL_003b: ldc.i4.1
IL_003c: add
IL_003d: callvirt ""void C.this[int, int].set""
IL_0042: ldloc.0
IL_0043: dup
IL_0044: ldc.i4.1
IL_0045: ldc.i4.2
IL_0046: callvirt ""int C.this[int, int].get""
IL_004b: stloc.1
IL_004c: ldc.i4.1
IL_004d: ldc.i4.2
IL_004e: ldloc.1
IL_004f: ldc.i4.1
IL_0050: add
IL_0051: callvirt ""void C.this[int, int].set""
IL_0056: ldloc.0
IL_0057: dup
IL_0058: ldc.i4.1
IL_0059: ldc.i4.s 9
IL_005b: callvirt ""int C.this[int, int].get""
IL_0060: stloc.1
IL_0061: ldc.i4.1
IL_0062: ldc.i4.s 9
IL_0064: ldloc.1
IL_0065: ldc.i4.1
IL_0066: add
IL_0067: callvirt ""void C.this[int, int].set""
IL_006c: ldloc.0
IL_006d: dup
IL_006e: ldc.i4.1
IL_006f: ldc.i4.s 9
IL_0071: callvirt ""int C.this[int, int].get""
IL_0076: stloc.1
IL_0077: ldc.i4.1
IL_0078: ldc.i4.s 9
IL_007a: ldloc.1
IL_007b: ldc.i4.1
IL_007c: add
IL_007d: callvirt ""void C.this[int, int].set""
IL_0082: ldloc.0
IL_0083: stloc.2
IL_0084: ldc.i4.3
IL_0085: newarr ""int""
IL_008a: dup
IL_008b: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_0090: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0095: stloc.3
IL_0096: ldloc.2
IL_0097: ldloc.3
IL_0098: callvirt ""int C.this[params int[]].get""
IL_009d: stloc.1
IL_009e: ldloc.2
IL_009f: ldloc.3
IL_00a0: ldloc.1
IL_00a1: ldc.i4.1
IL_00a2: add
IL_00a3: callvirt ""void C.this[params int[]].set""
IL_00a8: ldloc.0
IL_00a9: stloc.2
IL_00aa: ldc.i4.3
IL_00ab: newarr ""int""
IL_00b0: dup
IL_00b1: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_00b6: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_00bb: stloc.3
IL_00bc: ldloc.2
IL_00bd: ldloc.3
IL_00be: callvirt ""int C.this[params int[]].get""
IL_00c3: stloc.1
IL_00c4: ldloc.2
IL_00c5: ldloc.3
IL_00c6: ldloc.1
IL_00c7: ldc.i4.1
IL_00c8: add
IL_00c9: callvirt ""void C.this[params int[]].set""
IL_00ce: ret
}
");
}
[Fact]
public void LoweringCompoundAssignment()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[C.Goo(1), C.Goo(2)] += C.Goo(3);
System.Console.WriteLine();
//// Named parameters
c[C.Goo(1), y: C.Goo(2)] += C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1), y: C.Goo(2)] += C.Goo(3); //NB: dev10 gets this wrong (2,1,10,20,3,10,20,0,)
System.Console.WriteLine();
c[y: C.Goo(2), x: C.Goo(1)] += C.Goo(3);
System.Console.WriteLine();
//// Optional parameters
c[C.Goo(1)] += C.Goo(3);
System.Console.WriteLine();
c[x: C.Goo(1)] += C.Goo(3);
System.Console.WriteLine();
//// Parameter arrays
c[C.Goo(1), C.Goo(2), C.Goo(3)] += C.Goo(4);
System.Console.WriteLine();
c[new int[] { C.Goo(1), C.Goo(2), C.Goo(3) }] += C.Goo(4);
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
1,2,10,20,3,10,20,0,
1,2,10,20,3,10,20,0,
1,2,10,20,3,10,20,0,
2,1,10,20,3,10,20,0,
1,10,9,3,10,9,11,
1,10,9,3,10,9,11,
1,2,3,10,20,30,4,10,20,30,37,
1,2,3,10,20,30,4,10,20,30,37,
");
}
[Fact]
public void LoweringCompoundAssignmentIL()
{
var text = TypeWithIndexers + @"
class Test
{
static void Main()
{
C c = new C();
//// Normal
c[1, 2] += 3;
System.Console.WriteLine();
//// Named parameters
c[1, y: 2] += 3;
System.Console.WriteLine();
c[x: 1, y: 2] += 3; //NB: dev10 gets this wrong (2,1,10,20,3,10,20,0,)
System.Console.WriteLine();
c[y: 2, x: 1] += 3;
System.Console.WriteLine();
//// Optional parameters
c[1] += 3;
System.Console.WriteLine();
c[x: 1] += 3;
System.Console.WriteLine();
//// Parameter arrays
c[1, 2, 3] += 4;
System.Console.WriteLine();
c[new int[] { 1, 2, 3 }] += 4;
System.Console.WriteLine();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 243 (0xf3)
.maxstack 6
.locals init (C V_0, //c
C V_1,
int[] V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.1
IL_000a: ldc.i4.2
IL_000b: ldloc.1
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: callvirt ""int C.this[int, int].get""
IL_0013: ldc.i4.3
IL_0014: add
IL_0015: callvirt ""void C.this[int, int].set""
IL_001a: call ""void System.Console.WriteLine()""
IL_001f: ldloc.0
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: ldloc.1
IL_0025: ldc.i4.1
IL_0026: ldc.i4.2
IL_0027: callvirt ""int C.this[int, int].get""
IL_002c: ldc.i4.3
IL_002d: add
IL_002e: callvirt ""void C.this[int, int].set""
IL_0033: call ""void System.Console.WriteLine()""
IL_0038: ldloc.0
IL_0039: stloc.1
IL_003a: ldloc.1
IL_003b: ldc.i4.1
IL_003c: ldc.i4.2
IL_003d: ldloc.1
IL_003e: ldc.i4.1
IL_003f: ldc.i4.2
IL_0040: callvirt ""int C.this[int, int].get""
IL_0045: ldc.i4.3
IL_0046: add
IL_0047: callvirt ""void C.this[int, int].set""
IL_004c: call ""void System.Console.WriteLine()""
IL_0051: ldloc.0
IL_0052: stloc.1
IL_0053: ldloc.1
IL_0054: ldc.i4.1
IL_0055: ldc.i4.2
IL_0056: ldloc.1
IL_0057: ldc.i4.1
IL_0058: ldc.i4.2
IL_0059: callvirt ""int C.this[int, int].get""
IL_005e: ldc.i4.3
IL_005f: add
IL_0060: callvirt ""void C.this[int, int].set""
IL_0065: call ""void System.Console.WriteLine()""
IL_006a: ldloc.0
IL_006b: stloc.1
IL_006c: ldloc.1
IL_006d: ldc.i4.1
IL_006e: ldc.i4.s 9
IL_0070: ldloc.1
IL_0071: ldc.i4.1
IL_0072: ldc.i4.s 9
IL_0074: callvirt ""int C.this[int, int].get""
IL_0079: ldc.i4.3
IL_007a: add
IL_007b: callvirt ""void C.this[int, int].set""
IL_0080: call ""void System.Console.WriteLine()""
IL_0085: ldloc.0
IL_0086: stloc.1
IL_0087: ldloc.1
IL_0088: ldc.i4.1
IL_0089: ldc.i4.s 9
IL_008b: ldloc.1
IL_008c: ldc.i4.1
IL_008d: ldc.i4.s 9
IL_008f: callvirt ""int C.this[int, int].get""
IL_0094: ldc.i4.3
IL_0095: add
IL_0096: callvirt ""void C.this[int, int].set""
IL_009b: call ""void System.Console.WriteLine()""
IL_00a0: ldloc.0
IL_00a1: stloc.1
IL_00a2: ldc.i4.3
IL_00a3: newarr ""int""
IL_00a8: dup
IL_00a9: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_00ae: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_00b3: stloc.2
IL_00b4: ldloc.1
IL_00b5: ldloc.2
IL_00b6: ldloc.1
IL_00b7: ldloc.2
IL_00b8: callvirt ""int C.this[params int[]].get""
IL_00bd: ldc.i4.4
IL_00be: add
IL_00bf: callvirt ""void C.this[params int[]].set""
IL_00c4: call ""void System.Console.WriteLine()""
IL_00c9: ldloc.0
IL_00ca: stloc.1
IL_00cb: ldc.i4.3
IL_00cc: newarr ""int""
IL_00d1: dup
IL_00d2: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_00d7: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_00dc: stloc.2
IL_00dd: ldloc.1
IL_00de: ldloc.2
IL_00df: ldloc.1
IL_00e0: ldloc.2
IL_00e1: callvirt ""int C.this[params int[]].get""
IL_00e6: ldc.i4.4
IL_00e7: add
IL_00e8: callvirt ""void C.this[params int[]].set""
IL_00ed: call ""void System.Console.WriteLine()""
IL_00f2: ret
}
");
}
[Fact]
public void LoweringComplex()
{
var text = TypeWithIndexers + @"
class Test
{
static C NewC()
{
System.Console.Write(""N,"");
return new C();
}
static void Main()
{
NewC()[y: C.Goo(1), x: NewC()[C.Goo(2)]] = NewC()[x: C.Goo(3), y: NewC()[C.Goo(4)]] += NewC()[C.Goo(5), C.Goo(6), NewC()[C.Goo(7)]]++;
System.Console.WriteLine();
}
}
";
CompileAndVerify(text, expectedOutput: @"
N,1,N,2,20,9,N,3,N,4,40,9,30,-49,N,5,6,N,7,70,9,50,60,-79,50,60,-79,-2,30,-49,16,-29,10,16,
");
}
[Fact]
public void BoxingParameterArrayArguments()
{
var text = TypeWithIndexers + @"
class Test
{
int this[params object[] args] { get { return args.Length; } }
static void Main()
{
System.Console.WriteLine(new Test()[1, 2]);
}
}
";
var verifier = CompileAndVerify(text, expectedOutput: @"2");
verifier.VerifyIL("Test.Main", @"
{
// Code size 40 (0x28)
.maxstack 5
IL_0000: newobj ""Test..ctor()""
IL_0005: ldc.i4.2
IL_0006: newarr ""object""
IL_000b: dup
IL_000c: ldc.i4.0
IL_000d: ldc.i4.1
IL_000e: box ""int""
IL_0013: stelem.ref
IL_0014: dup
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: box ""int""
IL_001c: stelem.ref
IL_001d: call ""int Test.this[params object[]].get""
IL_0022: call ""void System.Console.WriteLine(int)""
IL_0027: ret
}
");
}
[Fact]
public void IndexerOverrideNotAllAccessors_DefaultParameterValues()
{
var text = @"
using System;
class Base
{
public virtual int this[int x, int y = 1]
{
get
{
Console.WriteLine(""Base.get y: "" + y);
return y;
}
set { Console.WriteLine(""Base.set y: "" + y); }
}
}
class Override : Base
{
public override int this[int x, int y = 2]
{
set { Console.WriteLine(""Override.set y: "" + y); }
}
}
class Program
{
static void Main()
{
Base b = new Base();
_ = b[0];
b[0] = 0;
Override o = new Override();
_ = o[0];
o[0] = 0;
o[0] += 0;
}
}
";
CompileAndVerify(text, expectedOutput:
@"Base.get y: 1
Base.set y: 1
Base.get y: 1
Override.set y: 2
Base.get y: 1
Override.set y: 1
");
}
#endregion Lowering
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpGenerateTypeDialog.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess;
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 CSharpGenerateTypeDialog : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
private GenerateTypeDialog_OutOfProc GenerateTypeDialog => VisualStudio.GenerateTypeDialog;
public CSharpGenerateTypeDialog(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpGenerateTypeDialog))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void OpenAndCloseDialog()
{
SetUpEditor(@"class C
{
void Method()
{
$$A a;
}
}
");
VisualStudio.Editor.Verify.CodeAction("Generate new type...",
applyFix: true,
blockUntilComplete: false);
GenerateTypeDialog.VerifyOpen();
GenerateTypeDialog.ClickCancel();
GenerateTypeDialog.VerifyClosed();
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void CSharpToBasic()
{
var vbProj = new ProjectUtils.Project("VBProj");
VisualStudio.SolutionExplorer.AddProject(vbProj, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic);
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
SetUpEditor(@"class C
{
void Method()
{
$$A a;
}
}
");
VisualStudio.Editor.Verify.CodeAction("Generate new type...",
applyFix: true,
blockUntilComplete: false);
GenerateTypeDialog.VerifyOpen();
GenerateTypeDialog.SetAccessibility("public");
GenerateTypeDialog.SetKind("interface");
GenerateTypeDialog.SetTargetProject("VBProj");
GenerateTypeDialog.SetTargetFileToNewName("GenerateTypeTest");
GenerateTypeDialog.ClickOK();
GenerateTypeDialog.VerifyClosed();
VisualStudio.SolutionExplorer.OpenFile(vbProj, "GenerateTypeTest.vb");
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(@"Public Interface A
End Interface
", actualText);
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
actualText = VisualStudio.Editor.GetText();
Assert.Contains(@"using VBProj;
class C
{
void Method()
{
A a;
}
}
", actualText);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess;
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 CSharpGenerateTypeDialog : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
private GenerateTypeDialog_OutOfProc GenerateTypeDialog => VisualStudio.GenerateTypeDialog;
public CSharpGenerateTypeDialog(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpGenerateTypeDialog))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void OpenAndCloseDialog()
{
SetUpEditor(@"class C
{
void Method()
{
$$A a;
}
}
");
VisualStudio.Editor.Verify.CodeAction("Generate new type...",
applyFix: true,
blockUntilComplete: false);
GenerateTypeDialog.VerifyOpen();
GenerateTypeDialog.ClickCancel();
GenerateTypeDialog.VerifyClosed();
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void CSharpToBasic()
{
var vbProj = new ProjectUtils.Project("VBProj");
VisualStudio.SolutionExplorer.AddProject(vbProj, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic);
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
SetUpEditor(@"class C
{
void Method()
{
$$A a;
}
}
");
VisualStudio.Editor.Verify.CodeAction("Generate new type...",
applyFix: true,
blockUntilComplete: false);
GenerateTypeDialog.VerifyOpen();
GenerateTypeDialog.SetAccessibility("public");
GenerateTypeDialog.SetKind("interface");
GenerateTypeDialog.SetTargetProject("VBProj");
GenerateTypeDialog.SetTargetFileToNewName("GenerateTypeTest");
GenerateTypeDialog.ClickOK();
GenerateTypeDialog.VerifyClosed();
VisualStudio.SolutionExplorer.OpenFile(vbProj, "GenerateTypeTest.vb");
var actualText = VisualStudio.Editor.GetText();
Assert.Contains(@"Public Interface A
End Interface
", actualText);
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
actualText = VisualStudio.Editor.GetText();
Assert.Contains(@"using VBProj;
class C
{
void Method()
{
A a;
}
}
", actualText);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest
{
protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider(
Workspace workspace, TestParameters parameters);
protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var refactoring = await GetCodeRefactoringAsync(workspace, parameters);
var actions = refactoring == null
? ImmutableArray<CodeAction>.Empty
: refactoring.CodeActions.Select(n => n.action).AsImmutable();
actions = MassageActions(actions);
return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]);
}
protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters)
=> SpecializedTasks.EmptyImmutableArray<Diagnostic>();
internal async Task<CodeRefactoring> GetCodeRefactoringAsync(
TestWorkspace workspace, TestParameters parameters)
{
return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault();
}
private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var provider = CreateCodeRefactoringProvider(workspace, parameters);
return SpecializedCollections.SingletonEnumerable(
await GetCodeRefactoringAsync(provider, workspace));
}
private static async Task<CodeRefactoring> GetCodeRefactoringAsync(
CodeRefactoringProvider provider,
TestWorkspace workspace)
{
var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1);
Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation");
var span = documentsWithSelections.Single().SelectedSpans.Single();
var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance();
var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id);
var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None);
await provider.ComputeRefactoringsAsync(context);
var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null;
actions.Free();
return result;
}
protected async Task TestActionOnLinkedFiles(
TestWorkspace workspace,
string expectedText,
CodeAction action,
string expectedPreviewContents = null)
{
var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
await VerifyPreviewContents(workspace, expectedPreviewContents, operations);
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None);
foreach (var document in workspace.Documents)
{
var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync();
var actualText = fixedRoot.ToFullString();
Assert.Equal(expectedText, actualText);
}
}
private static async Task VerifyPreviewContents(
TestWorkspace workspace, string expectedPreviewContents,
ImmutableArray<CodeActionOperation> operations)
{
if (expectedPreviewContents != null)
{
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var previews = await editHandler.GetPreviewsAsync(workspace, operations, CancellationToken.None);
var content = (await previews.GetPreviewsAsync())[0];
var diffView = content as DifferenceViewerPreview;
Assert.NotNull(diffView.Viewer);
var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
diffView.Dispose();
Assert.Equal(expectedPreviewContents, previewContents);
}
}
protected static Document GetDocument(TestWorkspace workspace)
=> workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
internal static void EnableOptions(
ImmutableArray<PickMembersOption> options,
params string[] ids)
{
foreach (var id in ids)
{
EnableOption(options, id);
}
}
internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id)
{
var option = options.FirstOrDefault(o => o.Id == id);
if (option != null)
{
option.Value = true;
}
}
internal Task TestWithPickMembersDialogAsync(
string initialMarkup,
string expectedMarkup,
string[] chosenSymbols,
Action<ImmutableArray<PickMembersOption>> optionsCallback = null,
int index = 0,
TestParameters parameters = default)
{
var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback);
return TestInRegularAndScript1Async(
initialMarkup, expectedMarkup,
index,
parameters.WithFixProviderData(pickMembersService));
}
}
[ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable]
internal class TestPickMembersService : IPickMembersService
{
public ImmutableArray<string> MemberNames;
public Action<ImmutableArray<PickMembersOption>> OptionsCallback;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestPickMembersService()
{
}
#pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public TestPickMembersService(
ImmutableArray<string> memberNames,
Action<ImmutableArray<PickMembersOption>> optionsCallback)
{
MemberNames = memberNames;
OptionsCallback = optionsCallback;
}
#pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public PickMembersResult PickMembers(
string title,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
OptionsCallback?.Invoke(options);
return new PickMembersResult(
MemberNames.IsDefault
? members
: MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)),
options,
selectAll);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest
{
protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider(
Workspace workspace, TestParameters parameters);
protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var refactoring = await GetCodeRefactoringAsync(workspace, parameters);
var actions = refactoring == null
? ImmutableArray<CodeAction>.Empty
: refactoring.CodeActions.Select(n => n.action).AsImmutable();
actions = MassageActions(actions);
return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]);
}
protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters)
=> SpecializedTasks.EmptyImmutableArray<Diagnostic>();
internal async Task<CodeRefactoring> GetCodeRefactoringAsync(
TestWorkspace workspace, TestParameters parameters)
{
return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault();
}
private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var provider = CreateCodeRefactoringProvider(workspace, parameters);
return SpecializedCollections.SingletonEnumerable(
await GetCodeRefactoringAsync(provider, workspace));
}
private static async Task<CodeRefactoring> GetCodeRefactoringAsync(
CodeRefactoringProvider provider,
TestWorkspace workspace)
{
var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1);
Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation");
var span = documentsWithSelections.Single().SelectedSpans.Single();
var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance();
var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id);
var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None);
await provider.ComputeRefactoringsAsync(context);
var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null;
actions.Free();
return result;
}
protected async Task TestActionOnLinkedFiles(
TestWorkspace workspace,
string expectedText,
CodeAction action,
string expectedPreviewContents = null)
{
var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
await VerifyPreviewContents(workspace, expectedPreviewContents, operations);
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None);
foreach (var document in workspace.Documents)
{
var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync();
var actualText = fixedRoot.ToFullString();
Assert.Equal(expectedText, actualText);
}
}
private static async Task VerifyPreviewContents(
TestWorkspace workspace, string expectedPreviewContents,
ImmutableArray<CodeActionOperation> operations)
{
if (expectedPreviewContents != null)
{
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var previews = await editHandler.GetPreviewsAsync(workspace, operations, CancellationToken.None);
var content = (await previews.GetPreviewsAsync())[0];
var diffView = content as DifferenceViewerPreview;
Assert.NotNull(diffView.Viewer);
var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
diffView.Dispose();
Assert.Equal(expectedPreviewContents, previewContents);
}
}
protected static Document GetDocument(TestWorkspace workspace)
=> workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
internal static void EnableOptions(
ImmutableArray<PickMembersOption> options,
params string[] ids)
{
foreach (var id in ids)
{
EnableOption(options, id);
}
}
internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id)
{
var option = options.FirstOrDefault(o => o.Id == id);
if (option != null)
{
option.Value = true;
}
}
internal Task TestWithPickMembersDialogAsync(
string initialMarkup,
string expectedMarkup,
string[] chosenSymbols,
Action<ImmutableArray<PickMembersOption>> optionsCallback = null,
int index = 0,
TestParameters parameters = default)
{
var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback);
return TestInRegularAndScript1Async(
initialMarkup, expectedMarkup,
index,
parameters.WithFixProviderData(pickMembersService));
}
}
[ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable]
internal class TestPickMembersService : IPickMembersService
{
public ImmutableArray<string> MemberNames;
public Action<ImmutableArray<PickMembersOption>> OptionsCallback;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestPickMembersService()
{
}
#pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public TestPickMembersService(
ImmutableArray<string> memberNames,
Action<ImmutableArray<PickMembersOption>> optionsCallback)
{
MemberNames = memberNames;
OptionsCallback = optionsCallback;
}
#pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public PickMembersResult PickMembers(
string title,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
OptionsCallback?.Invoke(options);
return new PickMembersResult(
MemberNames.IsDefault
? members
: MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)),
options,
selectAll);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
internal class NameSimplifier : AbstractCSharpSimplifier<NameSyntax, TypeSyntax>
{
public static readonly NameSimplifier Instance = new();
private NameSimplifier()
{
}
public override bool TrySimplify(
NameSyntax name,
SemanticModel semanticModel,
OptionSet optionSet,
out TypeSyntax replacementNode,
out TextSpan issueSpan,
CancellationToken cancellationToken)
{
replacementNode = null;
issueSpan = default;
if (name.IsVar)
{
return false;
}
// we should not simplify a name of a namespace declaration
if (IsPartOfNamespaceDeclarationName(name))
{
return false;
}
// We can simplify Qualified names and AliasQualifiedNames. Generally, if we have
// something like "A.B.C.D", we only consider the full thing something we can simplify.
// However, in the case of "A.B.C<>.D", then we'll only consider simplifying up to the
// first open name. This is because if we remove the open name, we'll often change
// meaning as "D" will bind to C<T>.D which is different than C<>.D!
if (name is QualifiedNameSyntax qualifiedName)
{
var left = qualifiedName.Left;
if (ContainsOpenName(left))
{
// Don't simplify A.B<>.C
return false;
}
}
// 1. see whether binding the name binds to a symbol/type. if not, it is ambiguous and
// nothing we can do here.
var symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name);
if (symbol == null)
{
return false;
}
// treat constructor names as types
var method = symbol as IMethodSymbol;
if (method.IsConstructor())
{
symbol = method.ContainingType;
}
if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName)
{
var genericName = (GenericNameSyntax)name;
replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier)
.WithLeadingTrivia(genericName.GetLeadingTrivia())
.WithTrailingTrivia(genericName.GetTrailingTrivia());
issueSpan = genericName.TypeArgumentList.Span;
return CanReplaceWithReducedName(
name, replacementNode, semanticModel, cancellationToken);
}
if (!(symbol is INamespaceOrTypeSymbol))
{
return false;
}
if (name.HasAnnotations(SpecialTypeAnnotation.Kind))
{
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
name.GetLeadingTrivia(),
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
name.GetTrailingTrivia()));
issueSpan = name.Span;
return CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
}
else
{
if (!name.IsRightSideOfDotOrColonColon())
{
if (TryReplaceExpressionWithAlias(name, semanticModel, symbol, cancellationToken, out var aliasReplacement))
{
// get the token text as it appears in source code to preserve e.g. Unicode character escaping
var text = aliasReplacement.Name;
var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault();
if (syntaxRef != null)
{
var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier;
text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString();
}
var identifierToken = SyntaxFactory.Identifier(
name.GetLeadingTrivia(),
SyntaxKind.IdentifierToken,
text,
aliasReplacement.Name,
name.GetTrailingTrivia());
identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name);
replacementNode = SyntaxFactory.IdentifierName(identifierToken);
// Merge annotation to new syntax node
var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
replacementNode = ((SimpleNameSyntax)replacementNode).WithIdentifier(identifierToken);
issueSpan = name.Span;
// In case the alias name is the same as the last name of the alias target, we only include
// the left part of the name in the unnecessary span to Not confuse uses.
if (name.Kind() == SyntaxKind.QualifiedName)
{
var qualifiedName3 = (QualifiedNameSyntax)name;
if (qualifiedName3.Right.Identifier.ValueText == identifierToken.ValueText)
{
issueSpan = qualifiedName3.Left.Span;
}
}
// first check if this would be a valid reduction
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
// in case this alias name ends with "Attribute", we're going to see if we can also
// remove that suffix.
if (TryReduceAttributeSuffix(
name,
identifierToken,
out var replacementNodeWithoutAttributeSuffix,
out var issueSpanWithoutAttributeSuffix))
{
if (CanReplaceWithReducedName(name, replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken))
{
replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix);
issueSpan = issueSpanWithoutAttributeSuffix;
}
}
return true;
}
return false;
}
var nameHasNoAlias = false;
if (name is SimpleNameSyntax simpleName)
{
if (!simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind))
{
nameHasNoAlias = true;
}
}
if (name is QualifiedNameSyntax qualifiedName2)
{
if (!qualifiedName2.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
if (name is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Name is SimpleNameSyntax &&
!aliasQualifiedName.Name.Identifier.HasAnnotations(AliasAnnotation.Kind) &&
!aliasQualifiedName.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
var aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken);
if (nameHasNoAlias && aliasInfo == null)
{
// Don't simplify to predefined type if name is part of a QualifiedName.
// QualifiedNames can't contain PredefinedTypeNames (although MemberAccessExpressions can).
// In other words, the left side of a QualifiedName can't be a PredefinedTypeName.
var inDeclarationContext = PreferPredefinedTypeKeywordInDeclarations(name, optionSet, semanticModel);
var inMemberAccessContext = PreferPredefinedTypeKeywordInMemberAccess(name, optionSet, semanticModel);
if (!name.Parent.IsKind(SyntaxKind.QualifiedName) && (inDeclarationContext || inMemberAccessContext))
{
// See if we can simplify this name (like System.Int32) to a built-in type (like 'int').
// If not, we'll still fall through and see if we can convert it to Int32.
var codeStyleOptionName = inDeclarationContext
? nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration)
: nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess);
var type = semanticModel.GetTypeInfo(name, cancellationToken).Type;
if (type != null)
{
var keywordKind = GetPredefinedKeywordKind(type.SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
else
{
var typeSymbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol;
if (typeSymbol.IsKind(SymbolKind.NamedType))
{
var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)typeSymbol).SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
}
}
}
// Nullable rewrite: Nullable<int> -> int?
// Don't rewrite in the case where Nullable<int> is part of some qualified name like Nullable<int>.Something
if (!name.IsVar && symbol.Kind == SymbolKind.NamedType && !name.IsLeftSideOfQualifiedName())
{
var type = (INamedTypeSymbol)symbol;
if (aliasInfo == null && CanSimplifyNullable(type, name, semanticModel))
{
GenericNameSyntax genericName;
if (name.Kind() == SyntaxKind.QualifiedName)
{
genericName = (GenericNameSyntax)((QualifiedNameSyntax)name).Right;
}
else
{
genericName = (GenericNameSyntax)name;
}
var oldType = genericName.TypeArgumentList.Arguments.First();
if (oldType.Kind() == SyntaxKind.OmittedTypeArgument)
{
return false;
}
replacementNode = SyntaxFactory.NullableType(oldType)
.WithLeadingTrivia(name.GetLeadingTrivia())
.WithTrailingTrivia(name.GetTrailingTrivia());
issueSpan = name.Span;
// we need to simplify the whole qualified name at once, because replacing the identifier on the left in
// System.Nullable<int> alone would be illegal.
// If this fails we want to continue to try at least to remove the System if possible.
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
return true;
}
}
}
}
SyntaxToken identifier;
switch (name.Kind())
{
case SyntaxKind.AliasQualifiedName:
var simpleName = ((AliasQualifiedNameSyntax)name).Name
.WithLeadingTrivia(name.GetLeadingTrivia());
simpleName = simpleName.ReplaceToken(simpleName.Identifier,
((AliasQualifiedNameSyntax)name).Name.Identifier.CopyAnnotationsTo(
simpleName.Identifier.WithLeadingTrivia(
((AliasQualifiedNameSyntax)name).Alias.Identifier.LeadingTrivia)));
replacementNode = simpleName;
issueSpan = ((AliasQualifiedNameSyntax)name).Alias.Span;
break;
case SyntaxKind.QualifiedName:
replacementNode = ((QualifiedNameSyntax)name).Right.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = ((QualifiedNameSyntax)name).Left.Span;
break;
case SyntaxKind.IdentifierName:
identifier = ((IdentifierNameSyntax)name).Identifier;
// we can try to remove the Attribute suffix if this is the attribute name
TryReduceAttributeSuffix(name, identifier, out replacementNode, out issueSpan);
break;
}
}
if (replacementNode == null)
{
return false;
}
// We may be looking at a name `X.Y` seeing if we can replace it with `Y`. However, in
// order to know for sure, we actually have to look slightly higher at `X.Y.Z` to see if
// it can simplify to `Y.Z`. This is because in the `Color Color` case we can only tell
// if we can reduce by looking by also looking at what comes next to see if it will
// cause the simplified name to bind to the instance or static side.
if (TryReduceCrefColorColor(name, replacementNode, semanticModel, cancellationToken))
{
return true;
}
return CanReplaceWithReducedName(name, replacementNode, semanticModel, cancellationToken);
}
private static bool TryReduceCrefColorColor(
NameSyntax name, TypeSyntax replacement,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!name.InsideCrefReference())
return false;
if (name.Parent is QualifiedCrefSyntax qualifiedCrefParent && qualifiedCrefParent.Container == name)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B.C with C. In this case the parent of A.B.C is A.B.C.D which is a
// QualifiedCrefSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedCref(replacement, qualifiedCrefParent.Member);
if (QualifiedCrefSimplifier.CanSimplifyWithReplacement(qualifiedCrefParent, semanticModel, qualifiedReplacement, cancellationToken))
return true;
}
else if (name.Parent is QualifiedNameSyntax qualifiedParent && qualifiedParent.Left == name &&
replacement is NameSyntax replacementName)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B with B. In this case the parent of A.B is A.B.C which is a
// QualifiedNameSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedName(replacementName, qualifiedParent.Right);
return CanReplaceWithReducedName(
qualifiedParent, qualifiedReplacement, semanticModel, cancellationToken);
}
return false;
}
private static bool CanSimplifyNullable(INamedTypeSymbol type, NameSyntax name, SemanticModel semanticModel)
{
if (!type.IsNullable())
{
return false;
}
if (type.IsUnboundGenericType)
{
// Don't simplify unbound generic type "Nullable<>".
return false;
}
if (InsideNameOfExpression(name, semanticModel))
{
// Nullable<T> can't be simplified to T? in nameof expressions.
return false;
}
if (!name.InsideCrefReference())
{
// Nullable<T> can always be simplified to T? outside crefs.
return true;
}
if (name.Parent is NameMemberCrefSyntax)
return false;
// Inside crefs, if the T in this Nullable{T} is being declared right here
// then this Nullable{T} is not a constructed generic type and we should
// not offer to simplify this to T?.
//
// For example, we should not offer the simplification in the following cases where
// T does not bind to an existing type / type parameter in the user's code.
// - <see cref="Nullable{T}"/>
// - <see cref="System.Nullable{T}.Value"/>
//
// And we should offer the simplification in the following cases where SomeType and
// SomeMethod bind to a type and method declared elsewhere in the users code.
// - <see cref="SomeType.SomeMethod(Nullable{SomeType})"/>
var argument = type.TypeArguments.SingleOrDefault();
if (argument == null || argument.IsErrorType())
{
return false;
}
var argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault();
if (argumentDecl == null)
{
// The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)).
return true;
}
return !name.Span.Contains(argumentDecl.Span);
}
private static bool CanReplaceWithPredefinedTypeKeywordInContext(
NameSyntax name,
SemanticModel semanticModel,
out TypeSyntax replacementNode,
ref TextSpan issueSpan,
SyntaxKind keywordKind,
string codeStyleOptionName)
{
replacementNode = CreatePredefinedTypeSyntax(name, keywordKind);
issueSpan = name.Span; // we want to show the whole name expression as unnecessary
var canReduce = CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
if (canReduce)
{
replacementNode = replacementNode.WithAdditionalAnnotations(new SyntaxAnnotation(codeStyleOptionName));
}
return canReduce;
}
private static bool TryReduceAttributeSuffix(
NameSyntax name,
SyntaxToken identifierToken,
out TypeSyntax replacementNode,
out TextSpan issueSpan)
{
issueSpan = default;
replacementNode = null;
// we can try to remove the Attribute suffix if this is the attribute name
if (SyntaxFacts.IsAttributeName(name))
{
if (name.Parent.Kind() == SyntaxKind.Attribute || name.IsRightSideOfDotOrColonColon())
{
const string AttributeName = "Attribute";
// an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation
if (identifierToken.ValueText != AttributeName && identifierToken.ValueText.EndsWith(AttributeName, StringComparison.Ordinal) && !identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
{
// weird. the semantic model is able to bind attribute syntax like "[as()]" although it's not valid code.
// so we need another check for keywords manually.
var newAttributeName = identifierToken.ValueText.Substring(0, identifierToken.ValueText.Length - 9);
if (SyntaxFacts.GetKeywordKind(newAttributeName) != SyntaxKind.None)
{
return false;
}
// if this attribute name in source contained Unicode escaping, we will loose it now
// because there is no easy way to determine the substring from identifier->ToString()
// which would be needed to pass to SyntaxFactory.Identifier
// The result is an unescaped Unicode character in source.
// once we remove the Attribute suffix, we can't use an escaped identifier
var newIdentifierToken = identifierToken.CopyAnnotationsTo(
SyntaxFactory.Identifier(
identifierToken.LeadingTrivia,
newAttributeName,
identifierToken.TrailingTrivia));
replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken)
.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = new TextSpan(identifierToken.Span.End - 9, 9);
return true;
}
}
}
return false;
}
/// <summary>
/// Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax
/// must be parented by an namespace declaration and the node itself must be equal to the declaration's Name
/// property.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static bool IsPartOfNamespaceDeclarationName(SyntaxNode node)
{
var parent = node;
while (parent != null)
{
switch (parent.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.QualifiedName:
node = parent;
parent = parent.Parent;
break;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent;
return object.Equals(namespaceDeclaration.Name, node);
default:
return false;
}
}
return false;
}
public static bool CanReplaceWithReducedNameInContext(
NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel)
{
// Check for certain things that would prevent us from reducing this name in this context.
// For example, you can simplify "using a = System.Int32" to "using a = int" as it's simply
// not allowed in the C# grammar.
if (IsNonNameSyntaxInUsingDirective(name, reducedName) ||
WillConflictWithExistingLocal(name, reducedName, semanticModel) ||
IsAmbiguousCast(name, reducedName) ||
IsNullableTypeInPointerExpression(reducedName) ||
IsNotNullableReplaceable(name, reducedName) ||
IsNonReducableQualifiedNameInUsingDirective(semanticModel, name))
{
return false;
}
return true;
}
private static bool ContainsOpenName(NameSyntax name)
{
if (name is QualifiedNameSyntax qualifiedName)
{
return ContainsOpenName(qualifiedName.Left) || ContainsOpenName(qualifiedName.Right);
}
else if (name is GenericNameSyntax genericName)
{
return genericName.IsUnboundGenericName;
}
else
{
return false;
}
}
private static bool CanReplaceWithReducedName(NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken);
if (speculationAnalyzer.ReplacementChangesSemantics())
{
return false;
}
return NameSimplifier.CanReplaceWithReducedNameInContext(name, reducedName, semanticModel);
}
private static bool IsNotNullableReplaceable(NameSyntax name, TypeSyntax reducedName)
{
if (reducedName.IsKind(SyntaxKind.NullableType, out NullableTypeSyntax nullableType))
{
if (nullableType.ElementType.Kind() == SyntaxKind.OmittedTypeArgument)
return true;
return name.IsLeftSideOfDot() || name.IsRightSideOfDot();
}
return false;
}
private static bool IsNullableTypeInPointerExpression(ExpressionSyntax simplifiedNode)
{
// Note: nullable type syntax is not allowed in pointer type syntax
if (simplifiedNode.Kind() == SyntaxKind.NullableType &&
simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax))
{
return true;
}
return false;
}
private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
return
expression.IsParentKind(SyntaxKind.UsingDirective) &&
!(simplifiedNode is NameSyntax);
}
private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
// Can't simplify a type name in a cast expression if it would then cause the cast to be
// parsed differently. For example: (Goo::Bar)+1 is a cast. But if that simplifies to
// (Bar)+1 then that's an arithmetic expression.
if (expression.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) &&
castExpression.Type == expression)
{
var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode);
var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString());
if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression))
{
return true;
}
}
return false;
}
private static bool IsNonReducableQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
// Whereas most of the time we do not want to reduce namespace names, We will
// make an exception for namespaces with the global:: alias.
return IsQualifiedNameInUsingDirective(model, name) &&
!IsGlobalAliasQualifiedName(name);
}
private static bool IsQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
while (name.IsLeftSideOfQualifiedName())
{
name = (NameSyntax)name.Parent;
}
if (name.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax usingDirective) &&
usingDirective.Alias == null)
{
// We're a qualified name in a using. We don't want to reduce this name as people like
// fully qualified names in usings so they can properly tell what the name is resolving
// to.
// However, if this name is actually referencing the special Script class, then we do
// want to allow that to be reduced.
return !IsInScriptClass(model, name);
}
return false;
}
private static bool IsGlobalAliasQualifiedName(NameSyntax name)
{
// Checks whether the `global::` alias is applied to the name
return name is AliasQualifiedNameSyntax aliasName &&
aliasName.Alias.Identifier.IsKind(SyntaxKind.GlobalKeyword);
}
private static bool IsInScriptClass(SemanticModel model, NameSyntax name)
{
var symbol = model.GetSymbolInfo(name).Symbol as INamedTypeSymbol;
while (symbol != null)
{
if (symbol.IsScriptClass)
{
return true;
}
symbol = symbol.ContainingType;
}
return false;
}
private static bool PreferPredefinedTypeKeywordInDeclarations(NameSyntax name, OptionSet optionSet, SemanticModel semanticModel)
{
return !name.IsDirectChildOfMemberAccessExpression() &&
!name.InsideCrefReference() &&
!InsideNameOfExpression(name, semanticModel) &&
SimplificationHelpers.PreferPredefinedTypeKeywordInDeclarations(optionSet, semanticModel.Language);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
internal class NameSimplifier : AbstractCSharpSimplifier<NameSyntax, TypeSyntax>
{
public static readonly NameSimplifier Instance = new();
private NameSimplifier()
{
}
public override bool TrySimplify(
NameSyntax name,
SemanticModel semanticModel,
OptionSet optionSet,
out TypeSyntax replacementNode,
out TextSpan issueSpan,
CancellationToken cancellationToken)
{
replacementNode = null;
issueSpan = default;
if (name.IsVar)
{
return false;
}
// we should not simplify a name of a namespace declaration
if (IsPartOfNamespaceDeclarationName(name))
{
return false;
}
// We can simplify Qualified names and AliasQualifiedNames. Generally, if we have
// something like "A.B.C.D", we only consider the full thing something we can simplify.
// However, in the case of "A.B.C<>.D", then we'll only consider simplifying up to the
// first open name. This is because if we remove the open name, we'll often change
// meaning as "D" will bind to C<T>.D which is different than C<>.D!
if (name is QualifiedNameSyntax qualifiedName)
{
var left = qualifiedName.Left;
if (ContainsOpenName(left))
{
// Don't simplify A.B<>.C
return false;
}
}
// 1. see whether binding the name binds to a symbol/type. if not, it is ambiguous and
// nothing we can do here.
var symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name);
if (symbol == null)
{
return false;
}
// treat constructor names as types
var method = symbol as IMethodSymbol;
if (method.IsConstructor())
{
symbol = method.ContainingType;
}
if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName)
{
var genericName = (GenericNameSyntax)name;
replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier)
.WithLeadingTrivia(genericName.GetLeadingTrivia())
.WithTrailingTrivia(genericName.GetTrailingTrivia());
issueSpan = genericName.TypeArgumentList.Span;
return CanReplaceWithReducedName(
name, replacementNode, semanticModel, cancellationToken);
}
if (!(symbol is INamespaceOrTypeSymbol))
{
return false;
}
if (name.HasAnnotations(SpecialTypeAnnotation.Kind))
{
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
name.GetLeadingTrivia(),
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
name.GetTrailingTrivia()));
issueSpan = name.Span;
return CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
}
else
{
if (!name.IsRightSideOfDotOrColonColon())
{
if (TryReplaceExpressionWithAlias(name, semanticModel, symbol, cancellationToken, out var aliasReplacement))
{
// get the token text as it appears in source code to preserve e.g. Unicode character escaping
var text = aliasReplacement.Name;
var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault();
if (syntaxRef != null)
{
var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier;
text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString();
}
var identifierToken = SyntaxFactory.Identifier(
name.GetLeadingTrivia(),
SyntaxKind.IdentifierToken,
text,
aliasReplacement.Name,
name.GetTrailingTrivia());
identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name);
replacementNode = SyntaxFactory.IdentifierName(identifierToken);
// Merge annotation to new syntax node
var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
replacementNode = ((SimpleNameSyntax)replacementNode).WithIdentifier(identifierToken);
issueSpan = name.Span;
// In case the alias name is the same as the last name of the alias target, we only include
// the left part of the name in the unnecessary span to Not confuse uses.
if (name.Kind() == SyntaxKind.QualifiedName)
{
var qualifiedName3 = (QualifiedNameSyntax)name;
if (qualifiedName3.Right.Identifier.ValueText == identifierToken.ValueText)
{
issueSpan = qualifiedName3.Left.Span;
}
}
// first check if this would be a valid reduction
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
// in case this alias name ends with "Attribute", we're going to see if we can also
// remove that suffix.
if (TryReduceAttributeSuffix(
name,
identifierToken,
out var replacementNodeWithoutAttributeSuffix,
out var issueSpanWithoutAttributeSuffix))
{
if (CanReplaceWithReducedName(name, replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken))
{
replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix);
issueSpan = issueSpanWithoutAttributeSuffix;
}
}
return true;
}
return false;
}
var nameHasNoAlias = false;
if (name is SimpleNameSyntax simpleName)
{
if (!simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind))
{
nameHasNoAlias = true;
}
}
if (name is QualifiedNameSyntax qualifiedName2)
{
if (!qualifiedName2.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
if (name is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Name is SimpleNameSyntax &&
!aliasQualifiedName.Name.Identifier.HasAnnotations(AliasAnnotation.Kind) &&
!aliasQualifiedName.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
var aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken);
if (nameHasNoAlias && aliasInfo == null)
{
// Don't simplify to predefined type if name is part of a QualifiedName.
// QualifiedNames can't contain PredefinedTypeNames (although MemberAccessExpressions can).
// In other words, the left side of a QualifiedName can't be a PredefinedTypeName.
var inDeclarationContext = PreferPredefinedTypeKeywordInDeclarations(name, optionSet, semanticModel);
var inMemberAccessContext = PreferPredefinedTypeKeywordInMemberAccess(name, optionSet, semanticModel);
if (!name.Parent.IsKind(SyntaxKind.QualifiedName) && (inDeclarationContext || inMemberAccessContext))
{
// See if we can simplify this name (like System.Int32) to a built-in type (like 'int').
// If not, we'll still fall through and see if we can convert it to Int32.
var codeStyleOptionName = inDeclarationContext
? nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration)
: nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess);
var type = semanticModel.GetTypeInfo(name, cancellationToken).Type;
if (type != null)
{
var keywordKind = GetPredefinedKeywordKind(type.SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
else
{
var typeSymbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol;
if (typeSymbol.IsKind(SymbolKind.NamedType))
{
var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)typeSymbol).SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
}
}
}
// Nullable rewrite: Nullable<int> -> int?
// Don't rewrite in the case where Nullable<int> is part of some qualified name like Nullable<int>.Something
if (!name.IsVar && symbol.Kind == SymbolKind.NamedType && !name.IsLeftSideOfQualifiedName())
{
var type = (INamedTypeSymbol)symbol;
if (aliasInfo == null && CanSimplifyNullable(type, name, semanticModel))
{
GenericNameSyntax genericName;
if (name.Kind() == SyntaxKind.QualifiedName)
{
genericName = (GenericNameSyntax)((QualifiedNameSyntax)name).Right;
}
else
{
genericName = (GenericNameSyntax)name;
}
var oldType = genericName.TypeArgumentList.Arguments.First();
if (oldType.Kind() == SyntaxKind.OmittedTypeArgument)
{
return false;
}
replacementNode = SyntaxFactory.NullableType(oldType)
.WithLeadingTrivia(name.GetLeadingTrivia())
.WithTrailingTrivia(name.GetTrailingTrivia());
issueSpan = name.Span;
// we need to simplify the whole qualified name at once, because replacing the identifier on the left in
// System.Nullable<int> alone would be illegal.
// If this fails we want to continue to try at least to remove the System if possible.
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
return true;
}
}
}
}
SyntaxToken identifier;
switch (name.Kind())
{
case SyntaxKind.AliasQualifiedName:
var simpleName = ((AliasQualifiedNameSyntax)name).Name
.WithLeadingTrivia(name.GetLeadingTrivia());
simpleName = simpleName.ReplaceToken(simpleName.Identifier,
((AliasQualifiedNameSyntax)name).Name.Identifier.CopyAnnotationsTo(
simpleName.Identifier.WithLeadingTrivia(
((AliasQualifiedNameSyntax)name).Alias.Identifier.LeadingTrivia)));
replacementNode = simpleName;
issueSpan = ((AliasQualifiedNameSyntax)name).Alias.Span;
break;
case SyntaxKind.QualifiedName:
replacementNode = ((QualifiedNameSyntax)name).Right.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = ((QualifiedNameSyntax)name).Left.Span;
break;
case SyntaxKind.IdentifierName:
identifier = ((IdentifierNameSyntax)name).Identifier;
// we can try to remove the Attribute suffix if this is the attribute name
TryReduceAttributeSuffix(name, identifier, out replacementNode, out issueSpan);
break;
}
}
if (replacementNode == null)
{
return false;
}
// We may be looking at a name `X.Y` seeing if we can replace it with `Y`. However, in
// order to know for sure, we actually have to look slightly higher at `X.Y.Z` to see if
// it can simplify to `Y.Z`. This is because in the `Color Color` case we can only tell
// if we can reduce by looking by also looking at what comes next to see if it will
// cause the simplified name to bind to the instance or static side.
if (TryReduceCrefColorColor(name, replacementNode, semanticModel, cancellationToken))
{
return true;
}
return CanReplaceWithReducedName(name, replacementNode, semanticModel, cancellationToken);
}
private static bool TryReduceCrefColorColor(
NameSyntax name, TypeSyntax replacement,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!name.InsideCrefReference())
return false;
if (name.Parent is QualifiedCrefSyntax qualifiedCrefParent && qualifiedCrefParent.Container == name)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B.C with C. In this case the parent of A.B.C is A.B.C.D which is a
// QualifiedCrefSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedCref(replacement, qualifiedCrefParent.Member);
if (QualifiedCrefSimplifier.CanSimplifyWithReplacement(qualifiedCrefParent, semanticModel, qualifiedReplacement, cancellationToken))
return true;
}
else if (name.Parent is QualifiedNameSyntax qualifiedParent && qualifiedParent.Left == name &&
replacement is NameSyntax replacementName)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B with B. In this case the parent of A.B is A.B.C which is a
// QualifiedNameSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedName(replacementName, qualifiedParent.Right);
return CanReplaceWithReducedName(
qualifiedParent, qualifiedReplacement, semanticModel, cancellationToken);
}
return false;
}
private static bool CanSimplifyNullable(INamedTypeSymbol type, NameSyntax name, SemanticModel semanticModel)
{
if (!type.IsNullable())
{
return false;
}
if (type.IsUnboundGenericType)
{
// Don't simplify unbound generic type "Nullable<>".
return false;
}
if (InsideNameOfExpression(name, semanticModel))
{
// Nullable<T> can't be simplified to T? in nameof expressions.
return false;
}
if (!name.InsideCrefReference())
{
// Nullable<T> can always be simplified to T? outside crefs.
return true;
}
if (name.Parent is NameMemberCrefSyntax)
return false;
// Inside crefs, if the T in this Nullable{T} is being declared right here
// then this Nullable{T} is not a constructed generic type and we should
// not offer to simplify this to T?.
//
// For example, we should not offer the simplification in the following cases where
// T does not bind to an existing type / type parameter in the user's code.
// - <see cref="Nullable{T}"/>
// - <see cref="System.Nullable{T}.Value"/>
//
// And we should offer the simplification in the following cases where SomeType and
// SomeMethod bind to a type and method declared elsewhere in the users code.
// - <see cref="SomeType.SomeMethod(Nullable{SomeType})"/>
var argument = type.TypeArguments.SingleOrDefault();
if (argument == null || argument.IsErrorType())
{
return false;
}
var argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault();
if (argumentDecl == null)
{
// The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)).
return true;
}
return !name.Span.Contains(argumentDecl.Span);
}
private static bool CanReplaceWithPredefinedTypeKeywordInContext(
NameSyntax name,
SemanticModel semanticModel,
out TypeSyntax replacementNode,
ref TextSpan issueSpan,
SyntaxKind keywordKind,
string codeStyleOptionName)
{
replacementNode = CreatePredefinedTypeSyntax(name, keywordKind);
issueSpan = name.Span; // we want to show the whole name expression as unnecessary
var canReduce = CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
if (canReduce)
{
replacementNode = replacementNode.WithAdditionalAnnotations(new SyntaxAnnotation(codeStyleOptionName));
}
return canReduce;
}
private static bool TryReduceAttributeSuffix(
NameSyntax name,
SyntaxToken identifierToken,
out TypeSyntax replacementNode,
out TextSpan issueSpan)
{
issueSpan = default;
replacementNode = null;
// we can try to remove the Attribute suffix if this is the attribute name
if (SyntaxFacts.IsAttributeName(name))
{
if (name.Parent.Kind() == SyntaxKind.Attribute || name.IsRightSideOfDotOrColonColon())
{
const string AttributeName = "Attribute";
// an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation
if (identifierToken.ValueText != AttributeName && identifierToken.ValueText.EndsWith(AttributeName, StringComparison.Ordinal) && !identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
{
// weird. the semantic model is able to bind attribute syntax like "[as()]" although it's not valid code.
// so we need another check for keywords manually.
var newAttributeName = identifierToken.ValueText.Substring(0, identifierToken.ValueText.Length - 9);
if (SyntaxFacts.GetKeywordKind(newAttributeName) != SyntaxKind.None)
{
return false;
}
// if this attribute name in source contained Unicode escaping, we will loose it now
// because there is no easy way to determine the substring from identifier->ToString()
// which would be needed to pass to SyntaxFactory.Identifier
// The result is an unescaped Unicode character in source.
// once we remove the Attribute suffix, we can't use an escaped identifier
var newIdentifierToken = identifierToken.CopyAnnotationsTo(
SyntaxFactory.Identifier(
identifierToken.LeadingTrivia,
newAttributeName,
identifierToken.TrailingTrivia));
replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken)
.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = new TextSpan(identifierToken.Span.End - 9, 9);
return true;
}
}
}
return false;
}
/// <summary>
/// Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax
/// must be parented by an namespace declaration and the node itself must be equal to the declaration's Name
/// property.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static bool IsPartOfNamespaceDeclarationName(SyntaxNode node)
{
var parent = node;
while (parent != null)
{
switch (parent.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.QualifiedName:
node = parent;
parent = parent.Parent;
break;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent;
return object.Equals(namespaceDeclaration.Name, node);
default:
return false;
}
}
return false;
}
public static bool CanReplaceWithReducedNameInContext(
NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel)
{
// Check for certain things that would prevent us from reducing this name in this context.
// For example, you can simplify "using a = System.Int32" to "using a = int" as it's simply
// not allowed in the C# grammar.
if (IsNonNameSyntaxInUsingDirective(name, reducedName) ||
WillConflictWithExistingLocal(name, reducedName, semanticModel) ||
IsAmbiguousCast(name, reducedName) ||
IsNullableTypeInPointerExpression(reducedName) ||
IsNotNullableReplaceable(name, reducedName) ||
IsNonReducableQualifiedNameInUsingDirective(semanticModel, name))
{
return false;
}
return true;
}
private static bool ContainsOpenName(NameSyntax name)
{
if (name is QualifiedNameSyntax qualifiedName)
{
return ContainsOpenName(qualifiedName.Left) || ContainsOpenName(qualifiedName.Right);
}
else if (name is GenericNameSyntax genericName)
{
return genericName.IsUnboundGenericName;
}
else
{
return false;
}
}
private static bool CanReplaceWithReducedName(NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken);
if (speculationAnalyzer.ReplacementChangesSemantics())
{
return false;
}
return NameSimplifier.CanReplaceWithReducedNameInContext(name, reducedName, semanticModel);
}
private static bool IsNotNullableReplaceable(NameSyntax name, TypeSyntax reducedName)
{
if (reducedName.IsKind(SyntaxKind.NullableType, out NullableTypeSyntax nullableType))
{
if (nullableType.ElementType.Kind() == SyntaxKind.OmittedTypeArgument)
return true;
return name.IsLeftSideOfDot() || name.IsRightSideOfDot();
}
return false;
}
private static bool IsNullableTypeInPointerExpression(ExpressionSyntax simplifiedNode)
{
// Note: nullable type syntax is not allowed in pointer type syntax
if (simplifiedNode.Kind() == SyntaxKind.NullableType &&
simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax))
{
return true;
}
return false;
}
private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
return
expression.IsParentKind(SyntaxKind.UsingDirective) &&
!(simplifiedNode is NameSyntax);
}
private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
// Can't simplify a type name in a cast expression if it would then cause the cast to be
// parsed differently. For example: (Goo::Bar)+1 is a cast. But if that simplifies to
// (Bar)+1 then that's an arithmetic expression.
if (expression.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) &&
castExpression.Type == expression)
{
var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode);
var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString());
if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression))
{
return true;
}
}
return false;
}
private static bool IsNonReducableQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
// Whereas most of the time we do not want to reduce namespace names, We will
// make an exception for namespaces with the global:: alias.
return IsQualifiedNameInUsingDirective(model, name) &&
!IsGlobalAliasQualifiedName(name);
}
private static bool IsQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
while (name.IsLeftSideOfQualifiedName())
{
name = (NameSyntax)name.Parent;
}
if (name.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax usingDirective) &&
usingDirective.Alias == null)
{
// We're a qualified name in a using. We don't want to reduce this name as people like
// fully qualified names in usings so they can properly tell what the name is resolving
// to.
// However, if this name is actually referencing the special Script class, then we do
// want to allow that to be reduced.
return !IsInScriptClass(model, name);
}
return false;
}
private static bool IsGlobalAliasQualifiedName(NameSyntax name)
{
// Checks whether the `global::` alias is applied to the name
return name is AliasQualifiedNameSyntax aliasName &&
aliasName.Alias.Identifier.IsKind(SyntaxKind.GlobalKeyword);
}
private static bool IsInScriptClass(SemanticModel model, NameSyntax name)
{
var symbol = model.GetSymbolInfo(name).Symbol as INamedTypeSymbol;
while (symbol != null)
{
if (symbol.IsScriptClass)
{
return true;
}
symbol = symbol.ContainingType;
}
return false;
}
private static bool PreferPredefinedTypeKeywordInDeclarations(NameSyntax name, OptionSet optionSet, SemanticModel semanticModel)
{
return !name.IsDirectChildOfMemberAccessExpression() &&
!name.InsideCrefReference() &&
!InsideNameOfExpression(name, semanticModel) &&
SimplificationHelpers.PreferPredefinedTypeKeywordInDeclarations(optionSet, semanticModel.Language);
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/VisualStudio/Xaml/Impl/Features/Structure/IXamlStructureService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Structure
{
internal interface IXamlStructureService : ILanguageService
{
Task<ImmutableArray<XamlStructureTag>> GetStructureTagsAsync(TextDocument document, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Structure
{
internal interface IXamlStructureService : ILanguageService
{
Task<ImmutableArray<XamlStructureTag>> GetStructureTagsAsync(TextDocument document, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/VisualBasicTest/SignatureHelp/MidAssignmentSignatureHelpProviderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp
Public Class MidAssignmentSignatureHelpProviderTests
Inherits AbstractVisualBasicSignatureHelpProviderTests
Friend Overrides Function GetSignatureHelpProviderType() As Type
Return GetType(MidAssignmentSignatureHelpProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForMidAssignmentFirstArgument() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Mid($$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}",
VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string,
VBWorkspaceResources.The_name_of_the_string_variable_to_modify,
currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForMidAssignmentSecondArgument() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Mid(s, $$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}",
VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string,
VBWorkspaceResources.The_one_based_character_position_in_the_string_where_the_replacement_of_text_begins,
currentParameterIndex:=1))
Await TestAsync(markup, expectedOrderedItems)
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForMidAssignmentThirdArgument() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Mid(s, 1, $$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}",
VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string,
VBWorkspaceResources.The_number_of_characters_to_replace_If_omitted_the_length_of_stringExpression_is_used,
currentParameterIndex:=2))
Await TestAsync(markup, expectedOrderedItems)
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=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.Editor.UnitTests.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp
Public Class MidAssignmentSignatureHelpProviderTests
Inherits AbstractVisualBasicSignatureHelpProviderTests
Friend Overrides Function GetSignatureHelpProviderType() As Type
Return GetType(MidAssignmentSignatureHelpProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForMidAssignmentFirstArgument() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Mid($$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}",
VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string,
VBWorkspaceResources.The_name_of_the_string_variable_to_modify,
currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForMidAssignmentSecondArgument() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Mid(s, $$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}",
VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string,
VBWorkspaceResources.The_one_based_character_position_in_the_string_where_the_replacement_of_text_begins,
currentParameterIndex:=1))
Await TestAsync(markup, expectedOrderedItems)
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForMidAssignmentThirdArgument() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Mid(s, 1, $$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"Mid({VBWorkspaceResources.stringName}, {VBWorkspaceResources.startIndex}, [{VBWorkspaceResources.length}]) = {VBWorkspaceResources.stringExpression}",
VBWorkspaceResources.Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string,
VBWorkspaceResources.The_number_of_characters_to_replace_If_omitted_the_length_of_stringExpression_is_used,
currentParameterIndex:=2))
Await TestAsync(markup, expectedOrderedItems)
Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/CSharp/Portable/BoundTree/BoundPattern.cs | // Licensed to the .NET Foundation under one or more 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 partial class BoundPattern
{
/// <summary>
/// Sets <paramref name="innerPattern"/> to the inner pattern after stripping off outer
/// <see cref="BoundNegatedPattern"/>s, and returns true if the original pattern is a
/// negated form of the inner pattern.
/// </summary>
internal bool IsNegated(out BoundPattern innerPattern)
{
innerPattern = this;
bool negated = false;
while (innerPattern is BoundNegatedPattern negatedPattern)
{
negated = !negated;
innerPattern = negatedPattern.Negated;
}
return negated;
}
}
}
| // Licensed to the .NET Foundation under one or more 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 partial class BoundPattern
{
/// <summary>
/// Sets <paramref name="innerPattern"/> to the inner pattern after stripping off outer
/// <see cref="BoundNegatedPattern"/>s, and returns true if the original pattern is a
/// negated form of the inner pattern.
/// </summary>
internal bool IsNegated(out BoundPattern innerPattern)
{
innerPattern = this;
bool negated = false;
while (innerPattern is BoundNegatedPattern negatedPattern)
{
negated = !negated;
innerPattern = negatedPattern.Negated;
}
return negated;
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncExceptionHandlerRewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The purpose of this rewriter is to replace await-containing catch and finally handlers
/// with surrogate replacements that keep actual handler code in regular code blocks.
/// That allows these constructs to be further lowered at the async lowering pass.
/// </summary>
internal sealed class AsyncExceptionHandlerRewriter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private readonly SyntheticBoundNodeFactory _F;
private readonly AwaitInFinallyAnalysis _analysis;
private AwaitCatchFrame _currentAwaitCatchFrame;
private AwaitFinallyFrame _currentAwaitFinallyFrame = new AwaitFinallyFrame();
private AsyncExceptionHandlerRewriter(
MethodSymbol containingMethod,
NamedTypeSymbol containingType,
SyntheticBoundNodeFactory factory,
AwaitInFinallyAnalysis analysis)
{
_F = factory;
_F.CurrentFunction = containingMethod;
Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2));
_analysis = analysis;
}
/// <summary>
/// Lower a block of code by performing local rewritings.
/// The goal is to not have exception handlers that contain awaits in them.
///
/// 1) Await containing finally blocks:
/// The general strategy is to rewrite await containing handlers into synthetic handlers.
/// Synthetic handlers are not handlers in IL sense so it is ok to have awaits in them.
/// Since synthetic handlers are just blocks, we have to deal with pending exception/branch/return manually
/// (this is the hard part of the rewrite).
///
/// try{
/// code;
/// }finally{
/// handler;
/// }
///
/// Into ===>
///
/// Exception ex = null;
/// int pendingBranch = 0;
///
/// try{
/// code; // any gotos/returns are rewritten to code that pends the necessary info and goes to finallyLabel
/// goto finallyLabel;
/// }catch (ex){ // essentially pend the currently active exception
/// };
///
/// finallyLabel:
/// {
/// handler;
/// if (ex != null) throw ex; // unpend the exception
/// unpend branches/return
/// }
///
/// 2) Await containing catches:
/// try{
/// code;
/// }catch (Exception ex){
/// handler;
/// throw;
/// }
///
///
/// Into ===>
///
/// Object pendingException;
/// int pendingCatch = 0;
///
/// try{
/// code;
/// }catch (Exception temp){ // essentially pend the currently active exception
/// pendingException = temp;
/// pendingCatch = 1;
/// };
///
/// switch(pendingCatch):
/// {
/// case 1:
/// {
/// Exception ex = (Exception)pendingException;
/// handler;
/// throw pendingException
/// }
/// }
/// </summary>
public static BoundStatement Rewrite(
MethodSymbol containingSymbol,
NamedTypeSymbol containingType,
BoundStatement statement,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(containingSymbol != null);
Debug.Assert((object)containingType != null);
Debug.Assert(statement != null);
Debug.Assert(compilationState != null);
Debug.Assert(diagnostics != null);
var analysis = new AwaitInFinallyAnalysis(statement);
if (!analysis.ContainsAwaitInHandlers())
{
return statement;
}
var factory = new SyntheticBoundNodeFactory(containingSymbol, statement.Syntax, compilationState, diagnostics);
var rewriter = new AsyncExceptionHandlerRewriter(containingSymbol, containingType, factory, analysis);
var loweredStatement = (BoundStatement)rewriter.Visit(statement);
return loweredStatement;
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var tryStatementSyntax = node.Syntax;
// If you add a syntax kind to the assertion below, please also ensure
// that the scenario has been tested with Edit-and-Continue.
Debug.Assert(
tryStatementSyntax.IsKind(SyntaxKind.TryStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.UsingStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachVariableStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LockStatement));
BoundStatement finalizedRegion;
BoundBlock rewrittenFinally;
var finallyContainsAwaits = _analysis.FinallyContainsAwaits(node);
if (!finallyContainsAwaits)
{
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.Visit(node.FinallyBlockOpt);
if (rewrittenFinally == null)
{
return finalizedRegion;
}
var asTry = finalizedRegion as BoundTryStatement;
if (asTry != null)
{
// since finalized region is a try we can just attach finally to it
Debug.Assert(asTry.FinallyBlockOpt == null);
return asTry.Update(asTry.TryBlock, asTry.CatchBlocks, rewrittenFinally, asTry.FinallyLabelOpt, asTry.PreferFaultHandler);
}
else
{
// wrap finalizedRegion into a Try with a finally.
return _F.Try((BoundBlock)finalizedRegion, ImmutableArray<BoundCatchBlock>.Empty, rewrittenFinally);
}
}
// rewrite finalized region (try and catches) in the current frame
var frame = PushFrame(node);
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.VisitBlock(node.FinallyBlockOpt);
PopFrame();
var exceptionType = _F.SpecialType(SpecialType.System_Object);
var pendingExceptionLocal = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(exceptionType), SynthesizedLocalKind.TryAwaitPendingException, tryStatementSyntax);
var finallyLabel = _F.GenerateLabel("finallyLabel");
var pendingBranchVar = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(_F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingBranch, tryStatementSyntax);
var catchAll = _F.Catch(_F.Local(pendingExceptionLocal), _F.Block());
var catchAndPendException = _F.Try(
_F.Block(
finalizedRegion,
_F.HiddenSequencePoint(),
_F.Goto(finallyLabel),
PendBranches(frame, pendingBranchVar, finallyLabel)),
ImmutableArray.Create(catchAll),
finallyLabel: finallyLabel);
BoundBlock syntheticFinallyBlock = _F.Block(
_F.HiddenSequencePoint(),
_F.Label(finallyLabel),
rewrittenFinally,
_F.HiddenSequencePoint(),
UnpendException(pendingExceptionLocal),
UnpendBranches(
frame,
pendingBranchVar,
pendingExceptionLocal));
BoundStatement syntheticFinally = syntheticFinallyBlock;
if (_F.CurrentFunction.IsAsync && _F.CurrentFunction.IsIterator)
{
// We wrap this block so that it can be processed as a finally block by async-iterator rewriting
syntheticFinally = _F.ExtractedFinallyBlock(syntheticFinallyBlock);
}
var locals = ArrayBuilder<LocalSymbol>.GetInstance();
var statements = ArrayBuilder<BoundStatement>.GetInstance();
statements.Add(_F.HiddenSequencePoint());
locals.Add(pendingExceptionLocal);
statements.Add(_F.Assignment(_F.Local(pendingExceptionLocal), _F.Default(pendingExceptionLocal.Type)));
locals.Add(pendingBranchVar);
statements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Default(pendingBranchVar.Type)));
LocalSymbol returnLocal = frame.returnValue;
if (returnLocal != null)
{
locals.Add(returnLocal);
}
statements.Add(catchAndPendException);
statements.Add(syntheticFinally);
var completeTry = _F.Block(
locals.ToImmutableAndFree(),
statements.ToImmutableAndFree());
return completeTry;
}
private BoundBlock PendBranches(
AwaitFinallyFrame frame,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
var bodyStatements = ArrayBuilder<BoundStatement>.GetInstance();
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
var proxyLabels = frame.proxyLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var proxied = proxiedLabels[i - 1];
var proxy = proxyLabels[proxied];
PendBranch(bodyStatements, proxy, i, pendingBranchVar, finallyLabel);
}
}
var returnProxy = frame.returnProxyLabel;
if (returnProxy != null)
{
PendBranch(bodyStatements, returnProxy, i, pendingBranchVar, finallyLabel);
}
return _F.Block(bodyStatements.ToImmutableAndFree());
}
private void PendBranch(
ArrayBuilder<BoundStatement> bodyStatements,
LabelSymbol proxy,
int i,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
// branch lands here
bodyStatements.Add(_F.Label(proxy));
// pend the branch
bodyStatements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Literal(i)));
// skip other proxies
bodyStatements.Add(_F.Goto(finallyLabel));
}
private BoundStatement UnpendBranches(
AwaitFinallyFrame frame,
SynthesizedLocal pendingBranchVar,
SynthesizedLocal pendingException)
{
var parent = frame.ParentOpt;
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
var cases = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance();
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var target = proxiedLabels[i - 1];
var parentProxy = parent.ProxyLabelIfNeeded(target);
var caseStatement = _F.SwitchSection(i, _F.Goto(parentProxy));
cases.Add(caseStatement);
}
}
if (frame.returnProxyLabel != null)
{
BoundLocal pendingValue = null;
if (frame.returnValue != null)
{
pendingValue = _F.Local(frame.returnValue);
}
SynthesizedLocal returnValue;
BoundStatement unpendReturn;
var returnLabel = parent.ProxyReturnIfNeeded(_F.CurrentFunction, pendingValue, out returnValue);
if (returnLabel == null)
{
unpendReturn = new BoundReturnStatement(_F.Syntax, RefKind.None, pendingValue);
}
else
{
if (pendingValue == null)
{
unpendReturn = _F.Goto(returnLabel);
}
else
{
unpendReturn = _F.Block(
_F.Assignment(
_F.Local(returnValue),
pendingValue),
_F.Goto(returnLabel));
}
}
var caseStatement = _F.SwitchSection(i, unpendReturn);
cases.Add(caseStatement);
}
return _F.Switch(_F.Local(pendingBranchVar), cases.ToImmutableAndFree());
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
BoundExpression caseExpressionOpt = (BoundExpression)this.Visit(node.CaseExpressionOpt);
BoundLabel labelExpressionOpt = (BoundLabel)this.Visit(node.LabelExpressionOpt);
var proxyLabel = _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label);
return node.Update(proxyLabel, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
Debug.Assert(node.Label == _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label), "conditional leave?");
return base.VisitConditionalGoto(node);
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
SynthesizedLocal returnValue;
var returnLabel = _currentAwaitFinallyFrame.ProxyReturnIfNeeded(
_F.CurrentFunction,
node.ExpressionOpt,
out returnValue);
if (returnLabel == null)
{
return base.VisitReturnStatement(node);
}
var returnExpr = (BoundExpression)(this.Visit(node.ExpressionOpt));
if (returnExpr != null)
{
return _F.Block(
_F.Assignment(
_F.Local(returnValue),
returnExpr),
_F.Goto(
returnLabel));
}
else
{
return _F.Goto(returnLabel);
}
}
private BoundStatement UnpendException(LocalSymbol pendingExceptionLocal)
{
// create a temp.
// pendingExceptionLocal will certainly be captured, no need to access it over and over.
LocalSymbol obj = _F.SynthesizedLocal(_F.SpecialType(SpecialType.System_Object));
var objInit = _F.Assignment(_F.Local(obj), _F.Local(pendingExceptionLocal));
// throw pendingExceptionLocal;
BoundStatement rethrow = Rethrow(obj);
return _F.Block(
ImmutableArray.Create<LocalSymbol>(obj),
objInit,
_F.If(
_F.ObjectNotEqual(
_F.Local(obj),
_F.Null(obj.Type)),
rethrow));
}
private BoundStatement Rethrow(LocalSymbol obj)
{
// conservative rethrow
BoundStatement rethrow = _F.Throw(_F.Local(obj));
var exceptionDispatchInfoCapture = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, isOptional: true);
var exceptionDispatchInfoThrow = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, isOptional: true);
// if these helpers are available, we can rethrow with original stack info
// as long as it derives from Exception
if (exceptionDispatchInfoCapture != null && exceptionDispatchInfoThrow != null)
{
var ex = _F.SynthesizedLocal(_F.WellKnownType(WellKnownType.System_Exception));
var assignment = _F.Assignment(
_F.Local(ex),
_F.As(_F.Local(obj), ex.Type));
// better rethrow
rethrow = _F.Block(
ImmutableArray.Create(ex),
assignment,
_F.If(_F.ObjectEqual(_F.Local(ex), _F.Null(ex.Type)), rethrow),
// ExceptionDispatchInfo.Capture(pendingExceptionLocal).Throw();
_F.ExpressionStatement(
_F.Call(
_F.StaticCall(
exceptionDispatchInfoCapture.ContainingType,
exceptionDispatchInfoCapture,
_F.Local(ex)),
exceptionDispatchInfoThrow)));
}
return rethrow;
}
/// <summary>
/// Rewrites Try/Catch part of the Try/Catch/Finally
/// </summary>
private BoundStatement RewriteFinalizedRegion(BoundTryStatement node)
{
var rewrittenTry = (BoundBlock)this.VisitBlock(node.TryBlock);
var catches = node.CatchBlocks;
if (catches.IsDefaultOrEmpty)
{
return rewrittenTry;
}
var origAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var rewrittenCatches = this.VisitList(node.CatchBlocks);
BoundStatement tryWithCatches = _F.Try(rewrittenTry, rewrittenCatches);
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame != null)
{
var handledLabel = _F.GenerateLabel("handled");
var handlersList = currentAwaitCatchFrame.handlers;
var handlers = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(handlersList.Count);
for (int i = 0, l = handlersList.Count; i < l; i++)
{
handlers.Add(_F.SwitchSection(
i + 1,
_F.Block(
handlersList[i],
_F.Goto(handledLabel))));
}
tryWithCatches = _F.Block(
ImmutableArray.Create<LocalSymbol>(
currentAwaitCatchFrame.pendingCaughtException,
currentAwaitCatchFrame.pendingCatch).
AddRange(currentAwaitCatchFrame.GetHoistedLocals()),
_F.HiddenSequencePoint(),
_F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Default(currentAwaitCatchFrame.pendingCatch.Type)),
tryWithCatches,
_F.HiddenSequencePoint(),
_F.Switch(
_F.Local(currentAwaitCatchFrame.pendingCatch),
handlers.ToImmutableAndFree()),
_F.HiddenSequencePoint(),
_F.Label(handledLabel));
}
_currentAwaitCatchFrame = origAwaitCatchFrame;
return tryWithCatches;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
if (!_analysis.CatchContainsAwait(node))
{
var origCurrentAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var result = base.VisitCatchBlock(node);
_currentAwaitCatchFrame = origCurrentAwaitCatchFrame;
return result;
}
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame == null)
{
Debug.Assert(node.Syntax.IsKind(SyntaxKind.CatchClause));
var tryStatementSyntax = (TryStatementSyntax)node.Syntax.Parent;
currentAwaitCatchFrame = _currentAwaitCatchFrame = new AwaitCatchFrame(_F, tryStatementSyntax);
}
var catchType = node.ExceptionTypeOpt ?? _F.SpecialType(SpecialType.System_Object);
var catchTemp = _F.SynthesizedLocal(catchType);
var storePending = _F.AssignmentExpression(
_F.Local(currentAwaitCatchFrame.pendingCaughtException),
_F.Convert(currentAwaitCatchFrame.pendingCaughtException.Type,
_F.Local(catchTemp)));
var setPendingCatchNum = _F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Literal(currentAwaitCatchFrame.handlers.Count + 1));
// catch (ExType exTemp)
// {
// pendingCaughtException = exTemp;
// catchNo = X;
// }
BoundCatchBlock catchAndPend;
ImmutableArray<LocalSymbol> handlerLocals;
var filterPrologueOpt = node.ExceptionFilterPrologueOpt;
var filterOpt = node.ExceptionFilterOpt;
if (filterOpt == null)
{
Debug.Assert(filterPrologueOpt is null);
// store pending exception
// as the first statement in a catch
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: filterPrologueOpt,
exceptionFilterOpt: null,
body: _F.Block(
_F.HiddenSequencePoint(),
_F.ExpressionStatement(storePending),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
// catch locals live on the synthetic catch handler block
handlerLocals = node.Locals;
}
else
{
handlerLocals = ImmutableArray<LocalSymbol>.Empty;
// catch locals move up into hoisted locals
// since we might need to access them from both the filter and the catch
foreach (var local in node.Locals)
{
currentAwaitCatchFrame.HoistLocal(local, _F);
}
// store pending exception
// as the first expression in a filter
var sourceOpt = node.ExceptionSourceOpt;
var rewrittenPrologue = (BoundStatementList)this.Visit(filterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(filterOpt);
var newFilter = sourceOpt == null ?
_F.MakeSequence(
storePending,
rewrittenFilter) :
_F.MakeSequence(
storePending,
AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame),
rewrittenFilter);
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: rewrittenPrologue,
exceptionFilterOpt: newFilter,
body: _F.Block(
_F.HiddenSequencePoint(),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
}
var handlerStatements = ArrayBuilder<BoundStatement>.GetInstance();
handlerStatements.Add(_F.HiddenSequencePoint());
if (filterOpt == null)
{
var sourceOpt = node.ExceptionSourceOpt;
if (sourceOpt != null)
{
BoundExpression assignSource = AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame);
handlerStatements.Add(_F.ExpressionStatement(assignSource));
}
}
handlerStatements.Add((BoundStatement)this.Visit(node.Body));
var handler = _F.Block(
handlerLocals,
handlerStatements.ToImmutableAndFree()
);
currentAwaitCatchFrame.handlers.Add(handler);
return catchAndPend;
}
private BoundExpression AssignCatchSource(BoundExpression rewrittenSource, AwaitCatchFrame currentAwaitCatchFrame)
{
BoundExpression assignSource = null;
if (rewrittenSource != null)
{
// exceptionSource = (exceptionSourceType)pendingCaughtException;
assignSource = _F.AssignmentExpression(
rewrittenSource,
_F.Convert(
rewrittenSource.Type,
_F.Local(currentAwaitCatchFrame.pendingCaughtException)));
}
return assignSource;
}
public override BoundNode VisitLocal(BoundLocal node)
{
var catchFrame = _currentAwaitCatchFrame;
LocalSymbol hoistedLocal;
if (catchFrame == null || !catchFrame.TryGetHoistedLocal(node.LocalSymbol, out hoistedLocal))
{
return base.VisitLocal(node);
}
return node.Update(hoistedLocal, node.ConstantValueOpt, hoistedLocal.Type);
}
public override BoundNode VisitThrowStatement(BoundThrowStatement node)
{
if (node.ExpressionOpt != null || _currentAwaitCatchFrame == null)
{
return base.VisitThrowStatement(node);
}
return Rethrow(_currentAwaitCatchFrame.pendingCaughtException);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLambda(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLocalFunctionStatement(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
private AwaitFinallyFrame PushFrame(BoundTryStatement statement)
{
var newFrame = new AwaitFinallyFrame(_currentAwaitFinallyFrame, _analysis.Labels(statement), (StatementSyntax)statement.Syntax);
_currentAwaitFinallyFrame = newFrame;
return newFrame;
}
private void PopFrame()
{
var result = _currentAwaitFinallyFrame;
_currentAwaitFinallyFrame = result.ParentOpt;
}
/// <summary>
/// Analyzes method body for try blocks with awaits in finally blocks
/// Also collects labels that such blocks contain.
/// </summary>
private sealed class AwaitInFinallyAnalysis : LabelCollector
{
// all try blocks with yields in them and complete set of labels inside those try blocks
// NOTE: non-yielding try blocks are transparently ignored - i.e. their labels are included
// in the label set of the nearest yielding-try parent
private Dictionary<BoundTryStatement, HashSet<LabelSymbol>> _labelsInInterestingTry;
private HashSet<BoundCatchBlock> _awaitContainingCatches;
// transient accumulators.
private bool _seenAwait;
public AwaitInFinallyAnalysis(BoundStatement body)
{
_seenAwait = false;
this.Visit(body);
}
/// <summary>
/// Returns true if a finally of the given try contains awaits
/// </summary>
public bool FinallyContainsAwaits(BoundTryStatement statement)
{
return _labelsInInterestingTry != null && _labelsInInterestingTry.ContainsKey(statement);
}
/// <summary>
/// Returns true if a catch contains awaits
/// </summary>
internal bool CatchContainsAwait(BoundCatchBlock node)
{
return _awaitContainingCatches != null && _awaitContainingCatches.Contains(node);
}
/// <summary>
/// Returns true if body contains await in a finally block.
/// </summary>
public bool ContainsAwaitInHandlers()
{
return _labelsInInterestingTry != null || _awaitContainingCatches != null;
}
/// <summary>
/// Labels reachable from within this frame without invoking its finally.
/// null if there are no such labels.
/// </summary>
internal HashSet<LabelSymbol> Labels(BoundTryStatement statement)
{
return _labelsInInterestingTry[statement];
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var origLabels = this.currentLabels;
this.currentLabels = null;
Visit(node.TryBlock);
VisitList(node.CatchBlocks);
var origSeenAwait = _seenAwait;
_seenAwait = false;
Visit(node.FinallyBlockOpt);
if (_seenAwait)
{
// this try has awaits in the finally !
var labelsInInterestingTry = _labelsInInterestingTry;
if (labelsInInterestingTry == null)
{
_labelsInInterestingTry = labelsInInterestingTry = new Dictionary<BoundTryStatement, HashSet<LabelSymbol>>();
}
labelsInInterestingTry.Add(node, currentLabels);
currentLabels = origLabels;
}
else
{
// this is a boring try without awaits in finally
// currentLabels = currentLabels U origLabels ;
if (currentLabels == null)
{
currentLabels = origLabels;
}
else if (origLabels != null)
{
currentLabels.UnionWith(origLabels);
}
}
_seenAwait = _seenAwait | origSeenAwait;
return null;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
var origSeenAwait = _seenAwait;
_seenAwait = false;
var result = base.VisitCatchBlock(node);
if (_seenAwait)
{
var awaitContainingCatches = _awaitContainingCatches;
if (awaitContainingCatches == null)
{
_awaitContainingCatches = awaitContainingCatches = new HashSet<BoundCatchBlock>();
}
_awaitContainingCatches.Add(node);
}
_seenAwait |= origSeenAwait;
return result;
}
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
_seenAwait = true;
return base.VisitAwaitExpression(node);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLambda(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLocalFunctionStatement(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
}
// storage of various information about a given finally frame
private sealed class AwaitFinallyFrame
{
// Enclosing frame. Root frame does not have parent.
public readonly AwaitFinallyFrame ParentOpt;
// labels within this frame (branching to these labels does not go through finally).
public readonly HashSet<LabelSymbol> LabelsOpt;
// the try or using-await statement the frame is associated with
private readonly StatementSyntax _statementSyntaxOpt;
// proxy labels for branches leaving the frame.
// we build this on demand once we encounter leaving branches.
// subsequent leaves to an already proxied label redirected to the proxy.
// At the proxy label we will execute finally and forward the control flow
// to the actual destination. (which could be proxied again in the parent)
public Dictionary<LabelSymbol, LabelSymbol> proxyLabels;
public List<LabelSymbol> proxiedLabels;
public GeneratedLabelSymbol returnProxyLabel;
public SynthesizedLocal returnValue;
public AwaitFinallyFrame()
{
// root frame
}
public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet<LabelSymbol> labelsOpt, StatementSyntax statementSyntax)
{
Debug.Assert(parent != null);
Debug.Assert(statementSyntax != null);
Debug.Assert(statementSyntax.Kind() == SyntaxKind.TryStatement ||
(statementSyntax.Kind() == SyntaxKind.UsingStatement && ((UsingStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachVariableStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)statementSyntax).AwaitKeyword != default));
this.ParentOpt = parent;
this.LabelsOpt = labelsOpt;
_statementSyntaxOpt = statementSyntax;
}
public bool IsRoot()
{
return this.ParentOpt == null;
}
// returns a proxy for a label if branch must be hijacked to run finally
// otherwise returns same label back
public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label)
{
// no need to proxy a label in the current frame or when we are at the root
if (this.IsRoot() || (LabelsOpt != null && LabelsOpt.Contains(label)))
{
return label;
}
var proxyLabels = this.proxyLabels;
var proxiedLabels = this.proxiedLabels;
if (proxyLabels == null)
{
this.proxyLabels = proxyLabels = new Dictionary<LabelSymbol, LabelSymbol>();
this.proxiedLabels = proxiedLabels = new List<LabelSymbol>();
}
LabelSymbol proxy;
if (!proxyLabels.TryGetValue(label, out proxy))
{
proxy = new GeneratedLabelSymbol("proxy" + label.Name);
proxyLabels.Add(label, proxy);
proxiedLabels.Add(label);
}
return proxy;
}
public LabelSymbol ProxyReturnIfNeeded(
MethodSymbol containingMethod,
BoundExpression valueOpt,
out SynthesizedLocal returnValue)
{
returnValue = null;
// no need to proxy returns at the root
if (this.IsRoot())
{
return null;
}
var returnProxy = this.returnProxyLabel;
if (returnProxy == null)
{
this.returnProxyLabel = returnProxy = new GeneratedLabelSymbol("returnProxy");
}
if (valueOpt != null)
{
returnValue = this.returnValue;
if (returnValue == null)
{
Debug.Assert(_statementSyntaxOpt != null);
this.returnValue = returnValue = new SynthesizedLocal(containingMethod, TypeWithAnnotations.Create(valueOpt.Type), SynthesizedLocalKind.AsyncMethodReturnValue, _statementSyntaxOpt);
}
}
return returnProxy;
}
}
private sealed class AwaitCatchFrame
{
// object, stores the original caught exception
// used to initialize the exception source inside the handler
// also used in rethrow statements
public readonly SynthesizedLocal pendingCaughtException;
// int, stores the number of pending catch
// 0 - means no catches are pending.
public readonly SynthesizedLocal pendingCatch;
// synthetic handlers produced by catch rewrite.
// they will become switch sections when pending exception is dispatched.
public readonly List<BoundBlock> handlers;
// when catch local must be used from a filter
// we need to "hoist" it up to ensure that both the filter
// and the catch access the same variable.
// NOTE: it must be the same variable, not just same value.
// The difference would be observable if filter mutates the variable
// or/and if a variable gets lifted into a closure.
private readonly Dictionary<LocalSymbol, LocalSymbol> _hoistedLocals;
private readonly List<LocalSymbol> _orderedHoistedLocals;
public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax)
{
this.pendingCaughtException = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Object)), SynthesizedLocalKind.TryAwaitPendingCaughtException, tryStatementSyntax);
this.pendingCatch = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingCatch, tryStatementSyntax);
this.handlers = new List<BoundBlock>();
_hoistedLocals = new Dictionary<LocalSymbol, LocalSymbol>();
_orderedHoistedLocals = new List<LocalSymbol>();
}
public void HoistLocal(LocalSymbol local, SyntheticBoundNodeFactory F)
{
if (!_hoistedLocals.Keys.Any(l => l.Name == local.Name && TypeSymbol.Equals(l.Type, local.Type, TypeCompareKind.ConsiderEverything2)))
{
_hoistedLocals.Add(local, local);
_orderedHoistedLocals.Add(local);
return;
}
// code uses "await" in two sibling catches with exception filters
// locals with same names and types may cause problems if they are lifted
// and become fields with identical signatures.
// To avoid such problems we will mangle the name of the second local.
// This will only affect debugging of this extremely rare case.
Debug.Assert(pendingCatch.SyntaxOpt.IsKind(SyntaxKind.TryStatement));
var newLocal = F.SynthesizedLocal(local.Type, pendingCatch.SyntaxOpt, kind: SynthesizedLocalKind.ExceptionFilterAwaitHoistedExceptionLocal);
_hoistedLocals.Add(local, newLocal);
_orderedHoistedLocals.Add(newLocal);
}
public IEnumerable<LocalSymbol> GetHoistedLocals()
{
return _orderedHoistedLocals;
}
public bool TryGetHoistedLocal(LocalSymbol originalLocal, out LocalSymbol hoistedLocal)
{
return _hoistedLocals.TryGetValue(originalLocal, out hoistedLocal);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The purpose of this rewriter is to replace await-containing catch and finally handlers
/// with surrogate replacements that keep actual handler code in regular code blocks.
/// That allows these constructs to be further lowered at the async lowering pass.
/// </summary>
internal sealed class AsyncExceptionHandlerRewriter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private readonly SyntheticBoundNodeFactory _F;
private readonly AwaitInFinallyAnalysis _analysis;
private AwaitCatchFrame _currentAwaitCatchFrame;
private AwaitFinallyFrame _currentAwaitFinallyFrame = new AwaitFinallyFrame();
private AsyncExceptionHandlerRewriter(
MethodSymbol containingMethod,
NamedTypeSymbol containingType,
SyntheticBoundNodeFactory factory,
AwaitInFinallyAnalysis analysis)
{
_F = factory;
_F.CurrentFunction = containingMethod;
Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2));
_analysis = analysis;
}
/// <summary>
/// Lower a block of code by performing local rewritings.
/// The goal is to not have exception handlers that contain awaits in them.
///
/// 1) Await containing finally blocks:
/// The general strategy is to rewrite await containing handlers into synthetic handlers.
/// Synthetic handlers are not handlers in IL sense so it is ok to have awaits in them.
/// Since synthetic handlers are just blocks, we have to deal with pending exception/branch/return manually
/// (this is the hard part of the rewrite).
///
/// try{
/// code;
/// }finally{
/// handler;
/// }
///
/// Into ===>
///
/// Exception ex = null;
/// int pendingBranch = 0;
///
/// try{
/// code; // any gotos/returns are rewritten to code that pends the necessary info and goes to finallyLabel
/// goto finallyLabel;
/// }catch (ex){ // essentially pend the currently active exception
/// };
///
/// finallyLabel:
/// {
/// handler;
/// if (ex != null) throw ex; // unpend the exception
/// unpend branches/return
/// }
///
/// 2) Await containing catches:
/// try{
/// code;
/// }catch (Exception ex){
/// handler;
/// throw;
/// }
///
///
/// Into ===>
///
/// Object pendingException;
/// int pendingCatch = 0;
///
/// try{
/// code;
/// }catch (Exception temp){ // essentially pend the currently active exception
/// pendingException = temp;
/// pendingCatch = 1;
/// };
///
/// switch(pendingCatch):
/// {
/// case 1:
/// {
/// Exception ex = (Exception)pendingException;
/// handler;
/// throw pendingException
/// }
/// }
/// </summary>
public static BoundStatement Rewrite(
MethodSymbol containingSymbol,
NamedTypeSymbol containingType,
BoundStatement statement,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(containingSymbol != null);
Debug.Assert((object)containingType != null);
Debug.Assert(statement != null);
Debug.Assert(compilationState != null);
Debug.Assert(diagnostics != null);
var analysis = new AwaitInFinallyAnalysis(statement);
if (!analysis.ContainsAwaitInHandlers())
{
return statement;
}
var factory = new SyntheticBoundNodeFactory(containingSymbol, statement.Syntax, compilationState, diagnostics);
var rewriter = new AsyncExceptionHandlerRewriter(containingSymbol, containingType, factory, analysis);
var loweredStatement = (BoundStatement)rewriter.Visit(statement);
return loweredStatement;
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var tryStatementSyntax = node.Syntax;
// If you add a syntax kind to the assertion below, please also ensure
// that the scenario has been tested with Edit-and-Continue.
Debug.Assert(
tryStatementSyntax.IsKind(SyntaxKind.TryStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.UsingStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.ForEachVariableStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ||
tryStatementSyntax.IsKind(SyntaxKind.LockStatement));
BoundStatement finalizedRegion;
BoundBlock rewrittenFinally;
var finallyContainsAwaits = _analysis.FinallyContainsAwaits(node);
if (!finallyContainsAwaits)
{
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.Visit(node.FinallyBlockOpt);
if (rewrittenFinally == null)
{
return finalizedRegion;
}
var asTry = finalizedRegion as BoundTryStatement;
if (asTry != null)
{
// since finalized region is a try we can just attach finally to it
Debug.Assert(asTry.FinallyBlockOpt == null);
return asTry.Update(asTry.TryBlock, asTry.CatchBlocks, rewrittenFinally, asTry.FinallyLabelOpt, asTry.PreferFaultHandler);
}
else
{
// wrap finalizedRegion into a Try with a finally.
return _F.Try((BoundBlock)finalizedRegion, ImmutableArray<BoundCatchBlock>.Empty, rewrittenFinally);
}
}
// rewrite finalized region (try and catches) in the current frame
var frame = PushFrame(node);
finalizedRegion = RewriteFinalizedRegion(node);
rewrittenFinally = (BoundBlock)this.VisitBlock(node.FinallyBlockOpt);
PopFrame();
var exceptionType = _F.SpecialType(SpecialType.System_Object);
var pendingExceptionLocal = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(exceptionType), SynthesizedLocalKind.TryAwaitPendingException, tryStatementSyntax);
var finallyLabel = _F.GenerateLabel("finallyLabel");
var pendingBranchVar = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(_F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingBranch, tryStatementSyntax);
var catchAll = _F.Catch(_F.Local(pendingExceptionLocal), _F.Block());
var catchAndPendException = _F.Try(
_F.Block(
finalizedRegion,
_F.HiddenSequencePoint(),
_F.Goto(finallyLabel),
PendBranches(frame, pendingBranchVar, finallyLabel)),
ImmutableArray.Create(catchAll),
finallyLabel: finallyLabel);
BoundBlock syntheticFinallyBlock = _F.Block(
_F.HiddenSequencePoint(),
_F.Label(finallyLabel),
rewrittenFinally,
_F.HiddenSequencePoint(),
UnpendException(pendingExceptionLocal),
UnpendBranches(
frame,
pendingBranchVar,
pendingExceptionLocal));
BoundStatement syntheticFinally = syntheticFinallyBlock;
if (_F.CurrentFunction.IsAsync && _F.CurrentFunction.IsIterator)
{
// We wrap this block so that it can be processed as a finally block by async-iterator rewriting
syntheticFinally = _F.ExtractedFinallyBlock(syntheticFinallyBlock);
}
var locals = ArrayBuilder<LocalSymbol>.GetInstance();
var statements = ArrayBuilder<BoundStatement>.GetInstance();
statements.Add(_F.HiddenSequencePoint());
locals.Add(pendingExceptionLocal);
statements.Add(_F.Assignment(_F.Local(pendingExceptionLocal), _F.Default(pendingExceptionLocal.Type)));
locals.Add(pendingBranchVar);
statements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Default(pendingBranchVar.Type)));
LocalSymbol returnLocal = frame.returnValue;
if (returnLocal != null)
{
locals.Add(returnLocal);
}
statements.Add(catchAndPendException);
statements.Add(syntheticFinally);
var completeTry = _F.Block(
locals.ToImmutableAndFree(),
statements.ToImmutableAndFree());
return completeTry;
}
private BoundBlock PendBranches(
AwaitFinallyFrame frame,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
var bodyStatements = ArrayBuilder<BoundStatement>.GetInstance();
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
var proxyLabels = frame.proxyLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var proxied = proxiedLabels[i - 1];
var proxy = proxyLabels[proxied];
PendBranch(bodyStatements, proxy, i, pendingBranchVar, finallyLabel);
}
}
var returnProxy = frame.returnProxyLabel;
if (returnProxy != null)
{
PendBranch(bodyStatements, returnProxy, i, pendingBranchVar, finallyLabel);
}
return _F.Block(bodyStatements.ToImmutableAndFree());
}
private void PendBranch(
ArrayBuilder<BoundStatement> bodyStatements,
LabelSymbol proxy,
int i,
LocalSymbol pendingBranchVar,
LabelSymbol finallyLabel)
{
// branch lands here
bodyStatements.Add(_F.Label(proxy));
// pend the branch
bodyStatements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Literal(i)));
// skip other proxies
bodyStatements.Add(_F.Goto(finallyLabel));
}
private BoundStatement UnpendBranches(
AwaitFinallyFrame frame,
SynthesizedLocal pendingBranchVar,
SynthesizedLocal pendingException)
{
var parent = frame.ParentOpt;
// handle proxy labels if have any
var proxiedLabels = frame.proxiedLabels;
// skip 0 - it means we took no explicit branches
int i = 1;
var cases = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance();
if (proxiedLabels != null)
{
for (int cnt = proxiedLabels.Count; i <= cnt; i++)
{
var target = proxiedLabels[i - 1];
var parentProxy = parent.ProxyLabelIfNeeded(target);
var caseStatement = _F.SwitchSection(i, _F.Goto(parentProxy));
cases.Add(caseStatement);
}
}
if (frame.returnProxyLabel != null)
{
BoundLocal pendingValue = null;
if (frame.returnValue != null)
{
pendingValue = _F.Local(frame.returnValue);
}
SynthesizedLocal returnValue;
BoundStatement unpendReturn;
var returnLabel = parent.ProxyReturnIfNeeded(_F.CurrentFunction, pendingValue, out returnValue);
if (returnLabel == null)
{
unpendReturn = new BoundReturnStatement(_F.Syntax, RefKind.None, pendingValue);
}
else
{
if (pendingValue == null)
{
unpendReturn = _F.Goto(returnLabel);
}
else
{
unpendReturn = _F.Block(
_F.Assignment(
_F.Local(returnValue),
pendingValue),
_F.Goto(returnLabel));
}
}
var caseStatement = _F.SwitchSection(i, unpendReturn);
cases.Add(caseStatement);
}
return _F.Switch(_F.Local(pendingBranchVar), cases.ToImmutableAndFree());
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
BoundExpression caseExpressionOpt = (BoundExpression)this.Visit(node.CaseExpressionOpt);
BoundLabel labelExpressionOpt = (BoundLabel)this.Visit(node.LabelExpressionOpt);
var proxyLabel = _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label);
return node.Update(proxyLabel, caseExpressionOpt, labelExpressionOpt);
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
Debug.Assert(node.Label == _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label), "conditional leave?");
return base.VisitConditionalGoto(node);
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
SynthesizedLocal returnValue;
var returnLabel = _currentAwaitFinallyFrame.ProxyReturnIfNeeded(
_F.CurrentFunction,
node.ExpressionOpt,
out returnValue);
if (returnLabel == null)
{
return base.VisitReturnStatement(node);
}
var returnExpr = (BoundExpression)(this.Visit(node.ExpressionOpt));
if (returnExpr != null)
{
return _F.Block(
_F.Assignment(
_F.Local(returnValue),
returnExpr),
_F.Goto(
returnLabel));
}
else
{
return _F.Goto(returnLabel);
}
}
private BoundStatement UnpendException(LocalSymbol pendingExceptionLocal)
{
// create a temp.
// pendingExceptionLocal will certainly be captured, no need to access it over and over.
LocalSymbol obj = _F.SynthesizedLocal(_F.SpecialType(SpecialType.System_Object));
var objInit = _F.Assignment(_F.Local(obj), _F.Local(pendingExceptionLocal));
// throw pendingExceptionLocal;
BoundStatement rethrow = Rethrow(obj);
return _F.Block(
ImmutableArray.Create<LocalSymbol>(obj),
objInit,
_F.If(
_F.ObjectNotEqual(
_F.Local(obj),
_F.Null(obj.Type)),
rethrow));
}
private BoundStatement Rethrow(LocalSymbol obj)
{
// conservative rethrow
BoundStatement rethrow = _F.Throw(_F.Local(obj));
var exceptionDispatchInfoCapture = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, isOptional: true);
var exceptionDispatchInfoThrow = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, isOptional: true);
// if these helpers are available, we can rethrow with original stack info
// as long as it derives from Exception
if (exceptionDispatchInfoCapture != null && exceptionDispatchInfoThrow != null)
{
var ex = _F.SynthesizedLocal(_F.WellKnownType(WellKnownType.System_Exception));
var assignment = _F.Assignment(
_F.Local(ex),
_F.As(_F.Local(obj), ex.Type));
// better rethrow
rethrow = _F.Block(
ImmutableArray.Create(ex),
assignment,
_F.If(_F.ObjectEqual(_F.Local(ex), _F.Null(ex.Type)), rethrow),
// ExceptionDispatchInfo.Capture(pendingExceptionLocal).Throw();
_F.ExpressionStatement(
_F.Call(
_F.StaticCall(
exceptionDispatchInfoCapture.ContainingType,
exceptionDispatchInfoCapture,
_F.Local(ex)),
exceptionDispatchInfoThrow)));
}
return rethrow;
}
/// <summary>
/// Rewrites Try/Catch part of the Try/Catch/Finally
/// </summary>
private BoundStatement RewriteFinalizedRegion(BoundTryStatement node)
{
var rewrittenTry = (BoundBlock)this.VisitBlock(node.TryBlock);
var catches = node.CatchBlocks;
if (catches.IsDefaultOrEmpty)
{
return rewrittenTry;
}
var origAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var rewrittenCatches = this.VisitList(node.CatchBlocks);
BoundStatement tryWithCatches = _F.Try(rewrittenTry, rewrittenCatches);
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame != null)
{
var handledLabel = _F.GenerateLabel("handled");
var handlersList = currentAwaitCatchFrame.handlers;
var handlers = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(handlersList.Count);
for (int i = 0, l = handlersList.Count; i < l; i++)
{
handlers.Add(_F.SwitchSection(
i + 1,
_F.Block(
handlersList[i],
_F.Goto(handledLabel))));
}
tryWithCatches = _F.Block(
ImmutableArray.Create<LocalSymbol>(
currentAwaitCatchFrame.pendingCaughtException,
currentAwaitCatchFrame.pendingCatch).
AddRange(currentAwaitCatchFrame.GetHoistedLocals()),
_F.HiddenSequencePoint(),
_F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Default(currentAwaitCatchFrame.pendingCatch.Type)),
tryWithCatches,
_F.HiddenSequencePoint(),
_F.Switch(
_F.Local(currentAwaitCatchFrame.pendingCatch),
handlers.ToImmutableAndFree()),
_F.HiddenSequencePoint(),
_F.Label(handledLabel));
}
_currentAwaitCatchFrame = origAwaitCatchFrame;
return tryWithCatches;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
if (!_analysis.CatchContainsAwait(node))
{
var origCurrentAwaitCatchFrame = _currentAwaitCatchFrame;
_currentAwaitCatchFrame = null;
var result = base.VisitCatchBlock(node);
_currentAwaitCatchFrame = origCurrentAwaitCatchFrame;
return result;
}
var currentAwaitCatchFrame = _currentAwaitCatchFrame;
if (currentAwaitCatchFrame == null)
{
Debug.Assert(node.Syntax.IsKind(SyntaxKind.CatchClause));
var tryStatementSyntax = (TryStatementSyntax)node.Syntax.Parent;
currentAwaitCatchFrame = _currentAwaitCatchFrame = new AwaitCatchFrame(_F, tryStatementSyntax);
}
var catchType = node.ExceptionTypeOpt ?? _F.SpecialType(SpecialType.System_Object);
var catchTemp = _F.SynthesizedLocal(catchType);
var storePending = _F.AssignmentExpression(
_F.Local(currentAwaitCatchFrame.pendingCaughtException),
_F.Convert(currentAwaitCatchFrame.pendingCaughtException.Type,
_F.Local(catchTemp)));
var setPendingCatchNum = _F.Assignment(
_F.Local(currentAwaitCatchFrame.pendingCatch),
_F.Literal(currentAwaitCatchFrame.handlers.Count + 1));
// catch (ExType exTemp)
// {
// pendingCaughtException = exTemp;
// catchNo = X;
// }
BoundCatchBlock catchAndPend;
ImmutableArray<LocalSymbol> handlerLocals;
var filterPrologueOpt = node.ExceptionFilterPrologueOpt;
var filterOpt = node.ExceptionFilterOpt;
if (filterOpt == null)
{
Debug.Assert(filterPrologueOpt is null);
// store pending exception
// as the first statement in a catch
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: filterPrologueOpt,
exceptionFilterOpt: null,
body: _F.Block(
_F.HiddenSequencePoint(),
_F.ExpressionStatement(storePending),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
// catch locals live on the synthetic catch handler block
handlerLocals = node.Locals;
}
else
{
handlerLocals = ImmutableArray<LocalSymbol>.Empty;
// catch locals move up into hoisted locals
// since we might need to access them from both the filter and the catch
foreach (var local in node.Locals)
{
currentAwaitCatchFrame.HoistLocal(local, _F);
}
// store pending exception
// as the first expression in a filter
var sourceOpt = node.ExceptionSourceOpt;
var rewrittenPrologue = (BoundStatementList)this.Visit(filterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(filterOpt);
var newFilter = sourceOpt == null ?
_F.MakeSequence(
storePending,
rewrittenFilter) :
_F.MakeSequence(
storePending,
AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame),
rewrittenFilter);
catchAndPend = node.Update(
ImmutableArray.Create(catchTemp),
_F.Local(catchTemp),
catchType,
exceptionFilterPrologueOpt: rewrittenPrologue,
exceptionFilterOpt: newFilter,
body: _F.Block(
_F.HiddenSequencePoint(),
setPendingCatchNum),
isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll);
}
var handlerStatements = ArrayBuilder<BoundStatement>.GetInstance();
handlerStatements.Add(_F.HiddenSequencePoint());
if (filterOpt == null)
{
var sourceOpt = node.ExceptionSourceOpt;
if (sourceOpt != null)
{
BoundExpression assignSource = AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame);
handlerStatements.Add(_F.ExpressionStatement(assignSource));
}
}
handlerStatements.Add((BoundStatement)this.Visit(node.Body));
var handler = _F.Block(
handlerLocals,
handlerStatements.ToImmutableAndFree()
);
currentAwaitCatchFrame.handlers.Add(handler);
return catchAndPend;
}
private BoundExpression AssignCatchSource(BoundExpression rewrittenSource, AwaitCatchFrame currentAwaitCatchFrame)
{
BoundExpression assignSource = null;
if (rewrittenSource != null)
{
// exceptionSource = (exceptionSourceType)pendingCaughtException;
assignSource = _F.AssignmentExpression(
rewrittenSource,
_F.Convert(
rewrittenSource.Type,
_F.Local(currentAwaitCatchFrame.pendingCaughtException)));
}
return assignSource;
}
public override BoundNode VisitLocal(BoundLocal node)
{
var catchFrame = _currentAwaitCatchFrame;
LocalSymbol hoistedLocal;
if (catchFrame == null || !catchFrame.TryGetHoistedLocal(node.LocalSymbol, out hoistedLocal))
{
return base.VisitLocal(node);
}
return node.Update(hoistedLocal, node.ConstantValueOpt, hoistedLocal.Type);
}
public override BoundNode VisitThrowStatement(BoundThrowStatement node)
{
if (node.ExpressionOpt != null || _currentAwaitCatchFrame == null)
{
return base.VisitThrowStatement(node);
}
return Rethrow(_currentAwaitCatchFrame.pendingCaughtException);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLambda(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var oldContainingSymbol = _F.CurrentFunction;
var oldAwaitFinallyFrame = _currentAwaitFinallyFrame;
_F.CurrentFunction = node.Symbol;
_currentAwaitFinallyFrame = new AwaitFinallyFrame();
var result = base.VisitLocalFunctionStatement(node);
_F.CurrentFunction = oldContainingSymbol;
_currentAwaitFinallyFrame = oldAwaitFinallyFrame;
return result;
}
private AwaitFinallyFrame PushFrame(BoundTryStatement statement)
{
var newFrame = new AwaitFinallyFrame(_currentAwaitFinallyFrame, _analysis.Labels(statement), (StatementSyntax)statement.Syntax);
_currentAwaitFinallyFrame = newFrame;
return newFrame;
}
private void PopFrame()
{
var result = _currentAwaitFinallyFrame;
_currentAwaitFinallyFrame = result.ParentOpt;
}
/// <summary>
/// Analyzes method body for try blocks with awaits in finally blocks
/// Also collects labels that such blocks contain.
/// </summary>
private sealed class AwaitInFinallyAnalysis : LabelCollector
{
// all try blocks with yields in them and complete set of labels inside those try blocks
// NOTE: non-yielding try blocks are transparently ignored - i.e. their labels are included
// in the label set of the nearest yielding-try parent
private Dictionary<BoundTryStatement, HashSet<LabelSymbol>> _labelsInInterestingTry;
private HashSet<BoundCatchBlock> _awaitContainingCatches;
// transient accumulators.
private bool _seenAwait;
public AwaitInFinallyAnalysis(BoundStatement body)
{
_seenAwait = false;
this.Visit(body);
}
/// <summary>
/// Returns true if a finally of the given try contains awaits
/// </summary>
public bool FinallyContainsAwaits(BoundTryStatement statement)
{
return _labelsInInterestingTry != null && _labelsInInterestingTry.ContainsKey(statement);
}
/// <summary>
/// Returns true if a catch contains awaits
/// </summary>
internal bool CatchContainsAwait(BoundCatchBlock node)
{
return _awaitContainingCatches != null && _awaitContainingCatches.Contains(node);
}
/// <summary>
/// Returns true if body contains await in a finally block.
/// </summary>
public bool ContainsAwaitInHandlers()
{
return _labelsInInterestingTry != null || _awaitContainingCatches != null;
}
/// <summary>
/// Labels reachable from within this frame without invoking its finally.
/// null if there are no such labels.
/// </summary>
internal HashSet<LabelSymbol> Labels(BoundTryStatement statement)
{
return _labelsInInterestingTry[statement];
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var origLabels = this.currentLabels;
this.currentLabels = null;
Visit(node.TryBlock);
VisitList(node.CatchBlocks);
var origSeenAwait = _seenAwait;
_seenAwait = false;
Visit(node.FinallyBlockOpt);
if (_seenAwait)
{
// this try has awaits in the finally !
var labelsInInterestingTry = _labelsInInterestingTry;
if (labelsInInterestingTry == null)
{
_labelsInInterestingTry = labelsInInterestingTry = new Dictionary<BoundTryStatement, HashSet<LabelSymbol>>();
}
labelsInInterestingTry.Add(node, currentLabels);
currentLabels = origLabels;
}
else
{
// this is a boring try without awaits in finally
// currentLabels = currentLabels U origLabels ;
if (currentLabels == null)
{
currentLabels = origLabels;
}
else if (origLabels != null)
{
currentLabels.UnionWith(origLabels);
}
}
_seenAwait = _seenAwait | origSeenAwait;
return null;
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
var origSeenAwait = _seenAwait;
_seenAwait = false;
var result = base.VisitCatchBlock(node);
if (_seenAwait)
{
var awaitContainingCatches = _awaitContainingCatches;
if (awaitContainingCatches == null)
{
_awaitContainingCatches = awaitContainingCatches = new HashSet<BoundCatchBlock>();
}
_awaitContainingCatches.Add(node);
}
_seenAwait |= origSeenAwait;
return result;
}
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
_seenAwait = true;
return base.VisitAwaitExpression(node);
}
public override BoundNode VisitLambda(BoundLambda node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLambda(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
var origLabels = this.currentLabels;
var origSeenAwait = _seenAwait;
this.currentLabels = null;
_seenAwait = false;
base.VisitLocalFunctionStatement(node);
this.currentLabels = origLabels;
_seenAwait = origSeenAwait;
return null;
}
}
// storage of various information about a given finally frame
private sealed class AwaitFinallyFrame
{
// Enclosing frame. Root frame does not have parent.
public readonly AwaitFinallyFrame ParentOpt;
// labels within this frame (branching to these labels does not go through finally).
public readonly HashSet<LabelSymbol> LabelsOpt;
// the try or using-await statement the frame is associated with
private readonly StatementSyntax _statementSyntaxOpt;
// proxy labels for branches leaving the frame.
// we build this on demand once we encounter leaving branches.
// subsequent leaves to an already proxied label redirected to the proxy.
// At the proxy label we will execute finally and forward the control flow
// to the actual destination. (which could be proxied again in the parent)
public Dictionary<LabelSymbol, LabelSymbol> proxyLabels;
public List<LabelSymbol> proxiedLabels;
public GeneratedLabelSymbol returnProxyLabel;
public SynthesizedLocal returnValue;
public AwaitFinallyFrame()
{
// root frame
}
public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet<LabelSymbol> labelsOpt, StatementSyntax statementSyntax)
{
Debug.Assert(parent != null);
Debug.Assert(statementSyntax != null);
Debug.Assert(statementSyntax.Kind() == SyntaxKind.TryStatement ||
(statementSyntax.Kind() == SyntaxKind.UsingStatement && ((UsingStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.ForEachVariableStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
(statementSyntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)statementSyntax).AwaitKeyword != default));
this.ParentOpt = parent;
this.LabelsOpt = labelsOpt;
_statementSyntaxOpt = statementSyntax;
}
public bool IsRoot()
{
return this.ParentOpt == null;
}
// returns a proxy for a label if branch must be hijacked to run finally
// otherwise returns same label back
public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label)
{
// no need to proxy a label in the current frame or when we are at the root
if (this.IsRoot() || (LabelsOpt != null && LabelsOpt.Contains(label)))
{
return label;
}
var proxyLabels = this.proxyLabels;
var proxiedLabels = this.proxiedLabels;
if (proxyLabels == null)
{
this.proxyLabels = proxyLabels = new Dictionary<LabelSymbol, LabelSymbol>();
this.proxiedLabels = proxiedLabels = new List<LabelSymbol>();
}
LabelSymbol proxy;
if (!proxyLabels.TryGetValue(label, out proxy))
{
proxy = new GeneratedLabelSymbol("proxy" + label.Name);
proxyLabels.Add(label, proxy);
proxiedLabels.Add(label);
}
return proxy;
}
public LabelSymbol ProxyReturnIfNeeded(
MethodSymbol containingMethod,
BoundExpression valueOpt,
out SynthesizedLocal returnValue)
{
returnValue = null;
// no need to proxy returns at the root
if (this.IsRoot())
{
return null;
}
var returnProxy = this.returnProxyLabel;
if (returnProxy == null)
{
this.returnProxyLabel = returnProxy = new GeneratedLabelSymbol("returnProxy");
}
if (valueOpt != null)
{
returnValue = this.returnValue;
if (returnValue == null)
{
Debug.Assert(_statementSyntaxOpt != null);
this.returnValue = returnValue = new SynthesizedLocal(containingMethod, TypeWithAnnotations.Create(valueOpt.Type), SynthesizedLocalKind.AsyncMethodReturnValue, _statementSyntaxOpt);
}
}
return returnProxy;
}
}
private sealed class AwaitCatchFrame
{
// object, stores the original caught exception
// used to initialize the exception source inside the handler
// also used in rethrow statements
public readonly SynthesizedLocal pendingCaughtException;
// int, stores the number of pending catch
// 0 - means no catches are pending.
public readonly SynthesizedLocal pendingCatch;
// synthetic handlers produced by catch rewrite.
// they will become switch sections when pending exception is dispatched.
public readonly List<BoundBlock> handlers;
// when catch local must be used from a filter
// we need to "hoist" it up to ensure that both the filter
// and the catch access the same variable.
// NOTE: it must be the same variable, not just same value.
// The difference would be observable if filter mutates the variable
// or/and if a variable gets lifted into a closure.
private readonly Dictionary<LocalSymbol, LocalSymbol> _hoistedLocals;
private readonly List<LocalSymbol> _orderedHoistedLocals;
public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax)
{
this.pendingCaughtException = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Object)), SynthesizedLocalKind.TryAwaitPendingCaughtException, tryStatementSyntax);
this.pendingCatch = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingCatch, tryStatementSyntax);
this.handlers = new List<BoundBlock>();
_hoistedLocals = new Dictionary<LocalSymbol, LocalSymbol>();
_orderedHoistedLocals = new List<LocalSymbol>();
}
public void HoistLocal(LocalSymbol local, SyntheticBoundNodeFactory F)
{
if (!_hoistedLocals.Keys.Any(l => l.Name == local.Name && TypeSymbol.Equals(l.Type, local.Type, TypeCompareKind.ConsiderEverything2)))
{
_hoistedLocals.Add(local, local);
_orderedHoistedLocals.Add(local);
return;
}
// code uses "await" in two sibling catches with exception filters
// locals with same names and types may cause problems if they are lifted
// and become fields with identical signatures.
// To avoid such problems we will mangle the name of the second local.
// This will only affect debugging of this extremely rare case.
Debug.Assert(pendingCatch.SyntaxOpt.IsKind(SyntaxKind.TryStatement));
var newLocal = F.SynthesizedLocal(local.Type, pendingCatch.SyntaxOpt, kind: SynthesizedLocalKind.ExceptionFilterAwaitHoistedExceptionLocal);
_hoistedLocals.Add(local, newLocal);
_orderedHoistedLocals.Add(newLocal);
}
public IEnumerable<LocalSymbol> GetHoistedLocals()
{
return _orderedHoistedLocals;
}
public bool TryGetHoistedLocal(LocalSymbol originalLocal, out LocalSymbol hoistedLocal)
{
return _hoistedLocals.TryGetValue(originalLocal, out hoistedLocal);
}
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Features/Core/Portable/Diagnostics/Analyzers/DocumentDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Diagnostics;
// for backward compat with TypeScript (https://github.com/dotnet/roslyn/issues/43313)
[assembly: TypeForwardedTo(typeof(DocumentDiagnosticAnalyzer))]
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Diagnostics;
// for backward compat with TypeScript (https://github.com/dotnet/roslyn/issues/43313)
[assembly: TypeForwardedTo(typeof(DocumentDiagnosticAnalyzer))]
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Analyzers/Core/CodeFixes/UseCoalesceExpression/UseCoalesceExpressionForNullableCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseCoalesceExpression
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared]
internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public UseCoalesceExpressionForNullableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionTypeOpt = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1");
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var generator = editor.Generator;
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);
var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);
syntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var condition, out var whenTrue, out var whenFalse);
editor.ReplaceNode(conditionalExpression,
(c, g) =>
{
syntaxFacts.GetPartsOfConditionalExpression(
c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse);
var coalesceExpression = whenPart == whenTrue
? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue))
: g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse));
if (semanticFacts.IsInExpressionTree(
semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken))
{
coalesceExpression = coalesceExpression.WithAdditionalAnnotations(
WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime));
}
return coalesceExpression;
});
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_coalesce_expression, createChangedDocument, nameof(AnalyzersResources.Use_coalesce_expression))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseCoalesceExpression
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.UseCoalesceExpressionForNullable), Shared]
internal class UseCoalesceExpressionForNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public UseCoalesceExpressionForNullableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
=> !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionTypeOpt = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1");
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var generator = editor.Generator;
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);
var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);
syntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var condition, out var whenTrue, out var whenFalse);
editor.ReplaceNode(conditionalExpression,
(c, g) =>
{
syntaxFacts.GetPartsOfConditionalExpression(
c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse);
var coalesceExpression = whenPart == whenTrue
? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue))
: g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse));
if (semanticFacts.IsInExpressionTree(
semanticModel, conditionalExpression, expressionTypeOpt, cancellationToken))
{
coalesceExpression = coalesceExpression.WithAdditionalAnnotations(
WarningAnnotation.Create(AnalyzersResources.Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime));
}
return coalesceExpression;
});
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_coalesce_expression, createChangedDocument, nameof(AnalyzersResources.Use_coalesce_expression))
{
}
}
}
}
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_Formatting.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature
Partial Public Class ChangeSignatureTests
Inherits AbstractChangeSignatureTests
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_KeepCountsPerLine() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$Method(a As Integer, b As Integer, c As Integer,
d As Integer, e As Integer,
f As Integer)
Method(1,
2, 3,
4, 5, 6)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {5, 4, 3, 2, 1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub Method(f As Integer, e As Integer, d As Integer,
c As Integer, b As Integer,
a As Integer)
Method(6,
5, 4,
3, 2, 1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_SubMethods() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$Method(x As Integer,
y As Integer)
Method(1,
2)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub Method(y As Integer,
x As Integer)
Method(2,
1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_FunctionMethods() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$Method(x As Integer,
y As Integer)
Method(1,
2)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub Method(y As Integer,
x As Integer)
Method(2,
1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Events() As Task
Dim markup = <Text><![CDATA[
Class C
Public Event $$MyEvent(a As Integer,
b As Integer)
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Public Event MyEvent(b As Integer,
a As Integer)
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_CustomEvents() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub $$MyDelegate(a As Integer,
b As Integer)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(a As Integer,
b As Integer)
End RaiseEvent
End Event
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(b As Integer,
a As Integer)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(b As Integer,
a As Integer)
End RaiseEvent
End Event
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Constructors() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$New(a As Integer,
b As Integer)
End Sub
Sub M()
Dim x = New C(1,
2)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub New(b As Integer,
a As Integer)
End Sub
Sub M()
Dim x = New C(2,
1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Properties() As Task
Dim markup = <Text><![CDATA[
Class C
Public Property $$NewProperty(x As Integer,
y As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Sub M()
Dim x = NewProperty(1,
2)
NewProperty(1,
2) = x
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Public Property NewProperty(y As Integer,
x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Sub M()
Dim x = NewProperty(2,
1)
NewProperty(2,
1) = x
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Attribute() As Task
Dim markup = <Text><![CDATA[
<Custom(1,
2)>
Class CustomAttribute
Inherits Attribute
Sub $$New(x As Integer, y As Integer)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
<Custom(2,
1)>
Class CustomAttribute
Inherits Attribute
Sub New(y As Integer, x As Integer)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_DelegateFunction() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Function $$MyDelegate(x As Integer,
y As Integer)
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Function MyDelegate(y As Integer,
x As Integer)
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_MultilineSubLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub $$MyDelegate(a As Integer, b As Integer)
Sub M(del As MyDelegate)
M(Sub(a As Integer,
b As Integer)
End Sub)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(b As Integer, a As Integer)
Sub M(del As MyDelegate)
M(Sub(b As Integer,
a As Integer)
End Sub)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_MultilineFunctionLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(a As Integer,
b As Integer)
Return 1
End Function)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Function MyDelegate(b As Integer, a As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(b As Integer,
a As Integer)
Return 1
End Function)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_SingleLineSubLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub $$MyDelegate(a As Integer, b As Integer)
Sub M(del As MyDelegate)
M(Sub(a As Integer,
b As Integer) System.Console.WriteLine("Test"))
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(b As Integer, a As Integer)
Sub M(del As MyDelegate)
M(Sub(b As Integer,
a As Integer) System.Console.WriteLine("Test"))
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_SingleLineFunctionLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(a As Integer,
b As Integer) 1)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Function MyDelegate(b As Integer, a As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(b As Integer,
a As Integer) 1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature
Partial Public Class ChangeSignatureTests
Inherits AbstractChangeSignatureTests
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_KeepCountsPerLine() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$Method(a As Integer, b As Integer, c As Integer,
d As Integer, e As Integer,
f As Integer)
Method(1,
2, 3,
4, 5, 6)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {5, 4, 3, 2, 1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub Method(f As Integer, e As Integer, d As Integer,
c As Integer, b As Integer,
a As Integer)
Method(6,
5, 4,
3, 2, 1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_SubMethods() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$Method(x As Integer,
y As Integer)
Method(1,
2)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub Method(y As Integer,
x As Integer)
Method(2,
1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_FunctionMethods() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$Method(x As Integer,
y As Integer)
Method(1,
2)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub Method(y As Integer,
x As Integer)
Method(2,
1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Events() As Task
Dim markup = <Text><![CDATA[
Class C
Public Event $$MyEvent(a As Integer,
b As Integer)
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Public Event MyEvent(b As Integer,
a As Integer)
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_CustomEvents() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub $$MyDelegate(a As Integer,
b As Integer)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(a As Integer,
b As Integer)
End RaiseEvent
End Event
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(b As Integer,
a As Integer)
Custom Event MyEvent As MyDelegate
AddHandler(value As MyDelegate)
End AddHandler
RemoveHandler(value As MyDelegate)
End RemoveHandler
RaiseEvent(b As Integer,
a As Integer)
End RaiseEvent
End Event
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Constructors() As Task
Dim markup = <Text><![CDATA[
Class C
Sub $$New(a As Integer,
b As Integer)
End Sub
Sub M()
Dim x = New C(1,
2)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Sub New(b As Integer,
a As Integer)
End Sub
Sub M()
Dim x = New C(2,
1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Properties() As Task
Dim markup = <Text><![CDATA[
Class C
Public Property $$NewProperty(x As Integer,
y As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Sub M()
Dim x = NewProperty(1,
2)
NewProperty(1,
2) = x
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Public Property NewProperty(y As Integer,
x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Sub M()
Dim x = NewProperty(2,
1)
NewProperty(2,
1) = x
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_Attribute() As Task
Dim markup = <Text><![CDATA[
<Custom(1,
2)>
Class CustomAttribute
Inherits Attribute
Sub $$New(x As Integer, y As Integer)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
<Custom(2,
1)>
Class CustomAttribute
Inherits Attribute
Sub New(y As Integer, x As Integer)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_DelegateFunction() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Function $$MyDelegate(x As Integer,
y As Integer)
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Function MyDelegate(y As Integer,
x As Integer)
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_MultilineSubLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub $$MyDelegate(a As Integer, b As Integer)
Sub M(del As MyDelegate)
M(Sub(a As Integer,
b As Integer)
End Sub)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(b As Integer, a As Integer)
Sub M(del As MyDelegate)
M(Sub(b As Integer,
a As Integer)
End Sub)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_MultilineFunctionLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(a As Integer,
b As Integer)
Return 1
End Function)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Function MyDelegate(b As Integer, a As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(b As Integer,
a As Integer)
Return 1
End Function)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_SingleLineSubLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Sub $$MyDelegate(a As Integer, b As Integer)
Sub M(del As MyDelegate)
M(Sub(a As Integer,
b As Integer) System.Console.WriteLine("Test"))
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Sub MyDelegate(b As Integer, a As Integer)
Sub M(del As MyDelegate)
M(Sub(b As Integer,
a As Integer) System.Console.WriteLine("Test"))
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function TestChangeSignature_Formatting_SingleLineFunctionLambda() As Task
Dim markup = <Text><![CDATA[
Class C
Delegate Function $$MyDelegate(a As Integer, b As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(a As Integer,
b As Integer) 1)
End Sub
End Class
]]></Text>.NormalizedValue()
Dim updatedSignature = {1, 0}
Dim expectedUpdatedCode = <Text><![CDATA[
Class C
Delegate Function MyDelegate(b As Integer, a As Integer) As Integer
Sub M(del As MyDelegate)
M(Function(b As Integer,
a As Integer) 1)
End Sub
End Class
]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/ConversionsILGenTestSource2.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.
Option Strict Off
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Module Module1
Sub Main()
System.Console.WriteLine("Conversions from Nothing literal:")
PrintResultBo(Nothing)
PrintResultSB(Nothing)
PrintResultBy(Nothing)
PrintResultSh(Nothing)
PrintResultUs(Nothing)
PrintResultIn(Nothing)
PrintResultUI(Nothing)
PrintResultLo(Nothing)
PrintResultUL(Nothing)
PrintResultSi(Nothing)
PrintResultDo(Nothing)
PrintResultDe(Nothing)
PrintResultDa(Nothing)
'PrintResultCh(Nothing)
PrintResultSt(Nothing)
PrintResultOb(Nothing)
PrintResultGuid(Nothing)
PrintResultIComparable(Nothing)
PrintResultValueType(Nothing)
PrintResultSt(GenericParamTestHelperOfString.NothingToT())
PrintResultGuid(GenericParamTestHelperOfGuid.NothingToT())
End Sub
Class GenericParamTestHelper(Of T)
Public Shared Function ObjectToT(val As Object) As T
Return val
End Function
Public Shared Function TToObject(val As T) As Object
Return val
End Function
Public Shared Function TToIComparable(val As T) As IComparable
Return val
End Function
Public Shared Function IComparableToT(val As IComparable) As T
Return val
End Function
Public Shared Function NothingToT() As T
Dim val As T
val = Nothing
Return val
End Function
End Class
Class GenericParamTestHelperOfString
Inherits GenericParamTestHelper(Of String)
End Class
Class GenericParamTestHelperOfGuid
Inherits GenericParamTestHelper(Of Guid)
End Class
Sub PrintResultBo(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResultSB(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResultBy(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResultSh(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResultUs(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResultIn(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResultUI(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResultLo(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResultUL(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResultDe(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val)
End Sub
Sub PrintResultSi(val As Single)
System.Console.WriteLine("Single: {0}", val)
End Sub
Sub PrintResultDo(val As Double)
System.Console.WriteLine("Double: {0}", val)
End Sub
Sub PrintResultDa(val As Date)
System.Console.WriteLine("Date: {0}", val.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub PrintResultCh(val As Char)
System.Console.WriteLine("Char: [{0}]", val)
End Sub
Sub PrintResultSZCh(val As Char())
System.Console.WriteLine("Char(): {0}", New String(val))
End Sub
Sub PrintResultSt(val As String)
System.Console.WriteLine("String: [{0}]", val)
End Sub
Sub PrintResultOb(val As Object)
System.Console.WriteLine("Object: [{0}]", val)
End Sub
Sub PrintResultGuid(val As System.Guid)
System.Console.WriteLine("Guid: {0}", val)
End Sub
Sub PrintResultIComparable(val As IComparable)
System.Console.WriteLine("IComparable: [{0}]", val)
End Sub
Sub PrintResultValueType(val As ValueType)
System.Console.WriteLine("ValueType: [{0}]", val)
End Sub
Sub PrintResultIEOfChar(val As IEnumerable(Of Char))
System.Console.WriteLine("IEnumerable(Of Char): {0}", val)
End Sub
Sub PrintResultICOfChar(val As ICollection(Of Char))
System.Console.WriteLine("ICollection(Of Char): {0}", val)
End Sub
Sub PrintResultIListOfChar(val As IList(Of Char))
System.Console.WriteLine("IList(Of Char): {0}", val)
End Sub
End Module
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Option Strict Off
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Module Module1
Sub Main()
System.Console.WriteLine("Conversions from Nothing literal:")
PrintResultBo(Nothing)
PrintResultSB(Nothing)
PrintResultBy(Nothing)
PrintResultSh(Nothing)
PrintResultUs(Nothing)
PrintResultIn(Nothing)
PrintResultUI(Nothing)
PrintResultLo(Nothing)
PrintResultUL(Nothing)
PrintResultSi(Nothing)
PrintResultDo(Nothing)
PrintResultDe(Nothing)
PrintResultDa(Nothing)
'PrintResultCh(Nothing)
PrintResultSt(Nothing)
PrintResultOb(Nothing)
PrintResultGuid(Nothing)
PrintResultIComparable(Nothing)
PrintResultValueType(Nothing)
PrintResultSt(GenericParamTestHelperOfString.NothingToT())
PrintResultGuid(GenericParamTestHelperOfGuid.NothingToT())
End Sub
Class GenericParamTestHelper(Of T)
Public Shared Function ObjectToT(val As Object) As T
Return val
End Function
Public Shared Function TToObject(val As T) As Object
Return val
End Function
Public Shared Function TToIComparable(val As T) As IComparable
Return val
End Function
Public Shared Function IComparableToT(val As IComparable) As T
Return val
End Function
Public Shared Function NothingToT() As T
Dim val As T
val = Nothing
Return val
End Function
End Class
Class GenericParamTestHelperOfString
Inherits GenericParamTestHelper(Of String)
End Class
Class GenericParamTestHelperOfGuid
Inherits GenericParamTestHelper(Of Guid)
End Class
Sub PrintResultBo(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResultSB(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResultBy(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResultSh(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResultUs(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResultIn(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResultUI(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResultLo(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResultUL(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResultDe(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val)
End Sub
Sub PrintResultSi(val As Single)
System.Console.WriteLine("Single: {0}", val)
End Sub
Sub PrintResultDo(val As Double)
System.Console.WriteLine("Double: {0}", val)
End Sub
Sub PrintResultDa(val As Date)
System.Console.WriteLine("Date: {0}", val.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub PrintResultCh(val As Char)
System.Console.WriteLine("Char: [{0}]", val)
End Sub
Sub PrintResultSZCh(val As Char())
System.Console.WriteLine("Char(): {0}", New String(val))
End Sub
Sub PrintResultSt(val As String)
System.Console.WriteLine("String: [{0}]", val)
End Sub
Sub PrintResultOb(val As Object)
System.Console.WriteLine("Object: [{0}]", val)
End Sub
Sub PrintResultGuid(val As System.Guid)
System.Console.WriteLine("Guid: {0}", val)
End Sub
Sub PrintResultIComparable(val As IComparable)
System.Console.WriteLine("IComparable: [{0}]", val)
End Sub
Sub PrintResultValueType(val As ValueType)
System.Console.WriteLine("ValueType: [{0}]", val)
End Sub
Sub PrintResultIEOfChar(val As IEnumerable(Of Char))
System.Console.WriteLine("IEnumerable(Of Char): {0}", val)
End Sub
Sub PrintResultICOfChar(val As ICollection(Of Char))
System.Console.WriteLine("ICollection(Of Char): {0}", val)
End Sub
Sub PrintResultIListOfChar(val As IList(Of Char))
System.Console.WriteLine("IList(Of Char): {0}", val)
End Sub
End Module
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/VisualStudio/VisualBasic/Impl/CodeModel/Interop/IVBGenericExtender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop
<ComImport>
<InterfaceType(ComInterfaceType.InterfaceIsDual)>
<Guid("2AD71E0D-AD9E-4735-BD4A-AA9AC430A883")>
Friend Interface IVBGenericExtender
ReadOnly Property GetBaseTypesCount As Integer
ReadOnly Property GetBaseGenericName(index As Integer) As String
ReadOnly Property GetImplementedTypesCount As Integer
ReadOnly Property GetImplTypeGenericName(index As Integer) As String
End Interface
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop
<ComImport>
<InterfaceType(ComInterfaceType.InterfaceIsDual)>
<Guid("2AD71E0D-AD9E-4735-BD4A-AA9AC430A883")>
Friend Interface IVBGenericExtender
ReadOnly Property GetBaseTypesCount As Integer
ReadOnly Property GetBaseGenericName(index As Integer) As String
ReadOnly Property GetImplementedTypesCount As Integer
ReadOnly Property GetImplTypeGenericName(index As Integer) As String
End Interface
End Namespace
| -1 |
dotnet/roslyn | 56,139 | Remove declaration-only-compilation from CompilationTracker | We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | CyrusNajmabadi | "2021-09-02T21:35:54Z" | "2021-09-08T23:38:33Z" | ef6e65fa1185f7aff571277420227446bf6eafa0 | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | Remove declaration-only-compilation from CompilationTracker. We used this compilation to speed up some string searches for certain features (and some public APIs we have). Turns out we don't need this given the indices we already have for features like FAR and NavTo. Given this, we can remove this compilation and simplify the compilation tracker a bunch. | ./src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingCancellationCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[Name(PredefinedCommandHandlerNames.RenameTrackingCancellation)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpBeforeCompletion)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)]
[Order(After = PredefinedCommandHandlerNames.AutomaticCompletion)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
[Order(After = PredefinedCommandHandlerNames.QuickInfo)]
[Order(After = PredefinedCommandHandlerNames.EventHookup)]
internal class RenameTrackingCancellationCommandHandler : ICommandHandler<EscapeKeyCommandArgs>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RenameTrackingCancellationCommandHandler()
{
}
public string DisplayName => EditorFeaturesResources.Rename_Tracking_Cancellation;
public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context)
{
var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
return document != null &&
RenameTrackingDismisser.DismissVisibleRenameTracking(document.Project.Solution.Workspace, document.Id);
}
public CommandState GetCommandState(EscapeKeyCommandArgs args)
=> CommandState.Unspecified;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[Name(PredefinedCommandHandlerNames.RenameTrackingCancellation)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpBeforeCompletion)]
[Order(After = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)]
[Order(After = PredefinedCommandHandlerNames.AutomaticCompletion)]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
[Order(After = PredefinedCommandHandlerNames.QuickInfo)]
[Order(After = PredefinedCommandHandlerNames.EventHookup)]
internal class RenameTrackingCancellationCommandHandler : ICommandHandler<EscapeKeyCommandArgs>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RenameTrackingCancellationCommandHandler()
{
}
public string DisplayName => EditorFeaturesResources.Rename_Tracking_Cancellation;
public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context)
{
var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
return document != null &&
RenameTrackingDismisser.DismissVisibleRenameTracking(document.Project.Solution.Workspace, document.Id);
}
public CommandState GetCommandState(EscapeKeyCommandArgs args)
=> CommandState.Unspecified;
}
}
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.